【问题标题】:.fit() error: Found arrays with inconsistent numbers of samples.fit() 错误:发现样本数量不一致的数组
【发布时间】:2016-10-29 17:38:06
【问题描述】:

y1 是一个长度为 106 的 numpy.ndarray(表示以米为单位的高度)

x1 是一个长度为 106 的 numpy.ndarray(代表身高对应的男孩的年龄)

我正在尝试使用梯度下降通过线性回归预测给定年龄的身高,然后将其绘制为 3D 曲面图。

当我尝试执行 .fit() 时,它会告诉我

ValueError:发现样本数量不一致的数组:[1 106]

import numpy as np
from sklearn import linear_model

x1 = np.fromfile('ex2x.dat', float)
y1 = np.fromfile('ex2y.dat', float)

clf = linear_model.SGDRegressor(alpha=.007)

clf.fit(x1, y1)


y_predicted = clf.predict(3.5)

【问题讨论】:

标签: python numpy scikit-learn


【解决方案1】:

预期的数组形状是:

  • (n_samples, 1) 表示 x1,表示具有一列的二维数组(因为您有一个特征)
  • (n_samples,) 表示 y1,表示一维数组。

如果你的第一个数组是一维的,你应该重塑它:

x1 = np.fromfile('ex2x.dat', float).reshape(-1, 1)

这是一个独立的小例子:

import numpy as np
from sklearn import linear_model

x1 = np.array(range(10)).reshape(-1, 1)
y1 = np.array([k**.5 for k in range(10)])

clf = linear_model.SGDRegressor(alpha=.0007)
clf.fit(x1, y1)

y_predicted = clf.predict(3.5)

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 2019-12-31
    • 2016-05-17
    • 2016-05-24
    • 2016-09-12
    • 2020-02-24
    • 2015-08-29
    • 2017-10-24
    相关资源
    最近更新 更多