0

I would like to run a linear regression but this code generates an error starting from "reg = LinearRegression()"

import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from scipy.stats import binom

from scipy.stats import norm
# generate random numbers from N(0,1)
x = norm.rvs(size=10000,loc=0,scale=1)
y = norm.rvs(size=10000,loc=0,scale=1)
z = binom.rvs(n=10,p=0.8,size=10000)
df = pd.DataFrame(data={'v1':x.flatten(),'target':y.flatten(),'label':z.flatten()})
df.head(10)

reg = LinearRegression()
reg.fit(df['v1'], df["target"])

error message: ValueError: Expected 2D array, got 1D array instead: array=[ 0.39507346 -0.01013895 -0.83918156 ... 0.47254883 0.02202747 0.50782984]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

any hint about what's wrong?

progster
  • 877
  • 3
  • 15
  • 27
  • Does this answer your question? [ValueError: Expected 2D array, got 1D array instead:](https://stackoverflow.com/questions/51150153/valueerror-expected-2d-array-got-1d-array-instead) – Nathan Furnal Dec 22 '20 at 20:03

1 Answers1

1

Use .values.reshape(-1, 1):

reg.fit(df['v1'].values.reshape(-1, 1), df["target"].values.reshape(-1, 1))
Pygirl
  • 12,969
  • 5
  • 30
  • 43