【问题标题】:simulation of linear regression scikit-learn pythonscikit-learn python的线性回归模拟
【发布时间】:2021-04-01 12:43:15
【问题描述】:

我想运行线性回归,但此代码从“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"])

错误信息: ValueError:预期的 2D 数组,得到 1D 数组: 数组=[ 0.39507346 -0.01013895 -0.83918156 ... 0.47254883 0.02202747 0.50782984]。 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果数据包含单个样本,则使用 array.reshape(1, -1)。

有什么提示吗?

【问题讨论】:

标签: python pandas scikit-learn regression simulation


【解决方案1】:

使用.values.reshape(-1, 1):

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

【讨论】:

  • 谢谢,它有效,但我不明白为什么我的版本会出现问题..
  • 如果有帮助,则通过将其标记为解决方案来结束问题。提前祝圣诞快乐:)
猜你喜欢
  • 2016-05-10
  • 2019-05-14
  • 2017-12-25
  • 2018-07-31
  • 2017-01-04
  • 2015-12-15
  • 2015-12-14
  • 2016-10-23
  • 2017-03-26
相关资源
最近更新 更多