简体   繁体   中英

simulation of linear regression scikit-learn python

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?

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

reg.fit(df['v1'].values.reshape(-1, 1), df["target"].values.reshape(-1, 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM