1

我正在尝试使用线性回归技术查找 linnerud 数据集的性能和均方误差。我在传递数据时卡住并收到错误“ValueError:找到样本数量不一致的输入变量:[10, 1]”。Linnerud 数据集在目标中具有三个特征和三列,我只想使用一个特征,即 chinup。有人可以帮我解决我卡住的问题吗?

以下是我迄今为止尝试过的,参考https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html

from sklearn import datasets
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
import numpy as np

linnerud = datasets.load_linnerud()
print(linnerud)

# Use only one feature
linnerud_X = linnerud.data[:, np.newaxis, 0]
print(linnerud_X)
X = np.array(linnerud_X).reshape((1,-1))
print(X)
# Split the data into training/testing sets
linnerud_X_train = linnerud_X[:-10]
linnerud_X_test = linnerud_X[-10:]
#print(linnerud_X_train)
#print(linnerud_X_test)


Y = np.array(linnerud.target).reshape((1,-1))

# Split the targets into training/testing sets
linnerud_y_train = Y
#linnerud_y_test #= Y[-10:]
print(linnerud_y_train)
#print(linnerud_y_test)

# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(linnerud_X_train, linnerud_y_train)

# Make predictions using the testing set
linnerud_y_pred = regr.predict(linnerud_X_test)

我期待在以下示例中取得类似的结果, https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html

4

1 回答 1

1

因变量和自变量中的条目数不相同。

>>> linnerud_y_train.shape
(1, 60)
>>> linnerud_X_train.shape
(10, 1)

此外,您对目标所做的重塑不正确(我不确定您在那里尝试做什么)。

特征被拆分为训练和测试,但没有在目标上完成拆分。这就是您收到值错误的原因。

但更好的方法是:

linnerud = datasets.load_linnerud()
linnerud_X = linnerud.data[:, np.newaxis, 0]   # Use only one feature

# Split to train and test
linnerud_X_train = linnerud_X[:10]
linnerud_X_test = linnerud_X[10:]

Y = linnerud.target[: np.newaxis, 0]
linnerud_y_train = Y[:10]
linnerud_y_test = Y[10:]

regr = linear_model.LinearRegression()
regr.fit(linnerud_X_train, linnerud_y_train)
于 2019-11-08T15:58:40.830 回答