求助帖 机器学习

  • Post author:
  • Post category:其他


求助帖 机器学习



以下为代码

from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression,SGDRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error

def mylinear():
"""
线性回归直接预测房子价格
:return: None
"""
#获取数据
lb = load_boston()
#分割数据集到训练集和测试集
x_train,x_test,y_train,y_test = train_test_split(lb.data,lb.target,test_size=0.25)
#进行标准化处理(?) 目标值处理(?)
#特征值和标准值都必须进行标准化处理,实例化两个标准化API
std_x = StandardScaler()



x_train = std_x.fit_transform(x_train)
x_test = std_x.transform(x_test)
#目标值
std_y = StandardScaler()
y_train = std_y.fit_transform(y_train.reshape(-1,1))
y_test = std_y.transform(y_test)
#estimator预测
#正规方程求解方式预测结果
lr = LinearRegression()
lr.fit(x_train,y_train)
print(lr.coef_)
#预测测试机的房子价格
y_lr_predict = std_y.inverse_transform(lr.predict(x_test))
print("梯度下降测试集里面每个房子的预测价格:",y_lr_predict)
print("梯度下降的均方误差:",mean_squared_error(std_y.inverse_transform(y_test),y_lr_predict))
#梯度下降去进行放假预测
sgd = SGDRegressor()
sgd.fit(x_train,y_train)
print(sgd.coef_)
#预测测试集的房子价格
y_sgd_predict = std_y.inverse_transform(sgd.predict(x_test))
print("测试集里面每个房子的预测价格:", y_sgd_predict)
return None

if __name__ =="__main__":
mylinear()



报错

D:\Anaconda3\envs\tensorflow_gpu\python.exe D:/untitled/demo_04.py

Traceback (most recent call last):

File “D:/untitled/demo_04.py”, line 46, in

mylinear()

File “D:/untitled/demo_04.py”, line 26, in mylinear

y_test = std_y.transform(y_test)

File “D:\Anaconda3\envs\tensorflow_gpu\lib\site-packages\sklearn\preprocessing\data.py”, line 758, in transform

force_all_finite=‘allow-nan’)

File “D:\Anaconda3\envs\tensorflow_gpu\lib\site-packages\sklearn\utils\validation.py”, line 521, in check_array

“if it contains a single sample.”.format(array))

ValueError: Expected 2D array, got 1D array instead:

array=[50. 18.8 35.4 26.4 20.6 14.6 25. 29. 29.1 20.6 13.2 34.9 20.3 19.3

28.7 19.3 27.9 43.1 11. 17.4 18.7 22.2 22.5 17.3 13.4 21.9 17.5 20.6

22.8 13.8 12.1 33.1 30.1 32. 15.6 17.9 24.2 16.1 22.9 22.3 21.5 17.

18.8 33.4 19.2 25. 23.3 23. 21.6 19.1 23. 21.7 50. 19.9 18.9 23.3

29.8 50. 25. 50. 13.9 33.2 7.2 8.7 17.1 15.2 13.8 17.7 27.5 23.1

14.9 32.5 21.6 23.1 21. 7.4 20.8 12. 17.2 25. 11.3 33.1 27.5 21.8

23.7 20. 16.4 22.5 13.4 13.8 20.2 14.4 35.4 21.7 13.6 5. 14.1 25.

15.2 24.8 21.4 20.7 8.8 48.5 42.8 24.4 37. 21. 36.4 31.2 21.2 38.7

20.5 14.5 17.2 15. 29.8 8.5 14.5 21.2 18.7 16.1 13.9 19.5 32.4 23.1

18.5].

Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

Process finished with exit code 1



感谢各位指导



版权声明:本文为xhh923原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。