【问题标题】:why is array len changed from 15 to 1 by using poly.fit_transform为什么使用 poly.fit_transform 将数组 len 从 15 更改为 1
【发布时间】:2017-07-19 16:56:28
【问题描述】:
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge

np.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10

X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

poly = PolynomialFeatures(degree=1)
X_poly = poly.fit_transform(X_train)
model = LinearRegression().fit(X_poly, y_ploy)

和 ValueError:发现样本数量不一致的输入变量:[1, 15]

我发现: 长度(x)->15,

array([  0.35281047,   0.79431716,   1.62431903,   2.59103578,
         3.23065446,   3.375973  ,   4.47573197,   4.96972856,
         5.69364194,   6.51069113,   7.17166586,   8.14799756,
         8.72363612,   9.31004929,  10.08877265])

在 poly.fit_transform 之后, len(X_poly)->1,包含16个数字,好像加了1,不知道为什么会这样?

array([[  1.        ,   0.35281047,   0.79431716,   1.62431903,
          2.59103578,   3.23065446,   3.375973  ,   4.47573197,
          4.96972856,   5.69364194,   6.51069113,   7.17166586,
          8.14799756,   8.72363612,   9.31004929,  10.08877265]])

所以模型无法完成,但我该如何修复它?

【问题讨论】:

    标签: python arrays numpy machine-learning linear-regression


    【解决方案1】:

    有点难以理解你想要做什么,因为你还没有定义你所指的所有变量。

    但是,当您使用 numpy ndarrays 时,您不应该使用 len 来查找数组的大小。你应该使用np.shape(x)x.shape 而不是len(x)。在这种情况下,您会发现 np.shape(X_F1_poly) 是 (1,16)。如果您仔细查看您打印的数组,您会发现第二个中包含双嵌套方括号,而不是第一个中的单个方括号。这意味着在X_F1_poly 中,您基本上有一个包含单个元素(因此长度为 1)的列表,并且该元素是另一个 16 元素列表。

    要使列表长度为 16,请使用 np.squeeze(X_F1_poly) 删除该嵌套。

    【讨论】:

    • 我想说为什么poly.fit_transform()可以改变原来数组的结构,我还是一头雾水,也谢谢。
    猜你喜欢
    • 2014-11-10
    • 2013-02-09
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多