【发布时间】:2017-06-12 20:14:22
【问题描述】:
我正在研究多项式训练测试拟合问题,并希望将列表对象转换为 (4, 100) 形式的 numpy 数组。 (即 4 行 100 列) 我有以下代码:
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from numpy import array
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)
results = []
pred_data = np.linspace(0,10,100)
degree = [1,3,6,9]
y_train1 = y_train.reshape(-1,1)
for i in degree:
poly = PolynomialFeatures(degree=i)
pred_poly1 = poly.fit_transform(pred_data[:,np.newaxis])
X_F1_poly = poly.fit_transform(X_train[:,np.newaxis])
linreg = LinearRegression().fit(X_F1_poly, y_train1)
pred = linreg.predict(pred_poly1)
results.append(pred)
dataArray = np.array(results).reshape(4, 100)
return dataArray
代码工作正常并返回一个 (4, 100) 的数组,但输出看起来像 100 行和 4 列的东西,一旦我从 np.reshape(4, 100) 中删除了“.reshape(4, 100)”部分。数组函数,输出的维度变为 (4, 100, 1)。 (我为我的无知道歉,1 in (4, 100, 1) 代表什么?)
我想我的列表理解有问题,我目前无法弄清楚。谁能帮我指出我的代码错误或就如何将输出数组转换/重塑为所需的 (4, 100) 格式提出建议?
谢谢。
【问题讨论】:
-
重塑不适合你吗?
-
您了解
np.newaxis在索引表达式中的作用吗? -
让我们明确一点;是
results.shape(100,4) 还是 (4,100,1)? -
感谢您的回复。 1.重塑似乎不起作用。 2. 据我了解,“np.newaxis”将结果选择的维度扩展了一个单位长度维度(我应该删除它吗?)
-
'np.array(results).shape' 为 (4, 100, 1),'np.array(results).reshape(4, 100)' 为 (4, 100),但它似乎仍然保留了 1 个额外的维度(即,一个额外的 [])。