【问题标题】:Sklearn.linear_model import LinearRegression does not work on data series but does for data frames. Why?Sklearn.linear_model import LinearRegression 不适用于数据系列,但适用于数据帧。为什么?
【发布时间】:2020-04-24 13:33:00
【问题描述】:

我使用了以下代码块,但出现回溯错误;

代码(在下面的代码中,X_train 和 y_train 是数据系列(单列数据)):

from sklearn.linear_model import LinearRegression
regressor = LinearRegression(fit_intercept=True)
regressor.fit(X_train, y_train)

Error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-167-3392c2ad36e2> in <module>
      2 from sklearn.linear_model import LinearRegression
      3 regressor = LinearRegression(fit_intercept=True)#Instantiating an object of the LinearRegression class.#"fit_intercept = True" is asking the linear regressor to assume that there is a y-intercept.
----> 4 regressor.fit(X_train, y_train) #Passing in our training data

~\Anaconda3\lib\site-packages\sklearn\linear_model\base.py in fit(self, X, y, sample_weight)
    461         n_jobs_ = self.n_jobs
    462         X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'],
--> 463                          y_numeric=True, multi_output=True)
    464 
    465         if sample_weight is not None and np.atleast_1d(sample_weight).ndim > 1:

在我将 X_train 和 y_train 更改为具有以下语法的数据帧后,该代码有效; X = pd.DataFrame(IceCream.Temperature) 和 y = pd.DataFrame(IceCream.Revenue) 问题是我不知道为什么会这样,但不是数据系列。我正在学习 SuperDataScience.com 的机器学习课程,并且该问题顶部的代码块为讲师工作,而无需将数据系列转换为数据帧。任何帮助将不胜感激。

【问题讨论】:

  • 也许 check_X_y 函数会抛出异常,因为您的 X_train 不是 2d。检查X_train.shape,您会看到类似(n,) 的内容,其中nX_train 的长度。当您将X_train 转换为数据框时,它变为二维(形状(n,1))并通过验证。
  • 只需使用 np.array(series) 转换系列,然后将其放入模型中。

标签: python pandas dataframe series sklearn-pandas


【解决方案1】:

SKLearn 关于线性回归的文档

sklearn.linear_model.LinearRegression

清楚地统计了 fit 方法 X : {array-like, sparse matrix} 形状 (n_samples, n_features)

熊猫系列不满足此要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2022-01-18
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    相关资源
    最近更新 更多