代码如下:
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
def Linear1():
# 正规方程的优化方法对波士顿房价进行预测
# 1获取数据集
boston = load_boston()
# print('特征数量:\n',boston)
# 2划分数据集
x_train,x_test,y_train,y_test = train_test_split(boston.data,boston.target,random_state=22)
# 3特征工程:
# 无量纲化-标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
print('====================================')
# 4预估器流程
# fit() --->模型
# coef_intercept
estimator = LinearRegression()
estimator.fit(x_train,y_train)
# 5得出模型
print('正规方程权重系数为:\n',estimator.coef_)
print('正规方程偏置为:\n',estimator.intercept_)
# 6模型评估
y_predict = estimator.predict(x_test)
print('预测房价:\n',y_predict)
error = mean_squared_error(y_test,y_predict)
print('正规方程均方误差为:\n',error)
# print('虚拟变量特征:\n',list(boston.feature_names))
# # 使用模型做出预测
# t = [[6.320e-03,1.800e+01,2.310e+00,0.000e+00,5.380e-01,6.575e+00,6.520e+01,4.090e+00,1.000e+00,2.960e+02,1.530e+01,3.969e+02,4.980e+00]]
t = [[0.00332, 15.0, 1.31, 0.0, 0.238, 3.575, 35.2, 1.09, 1.0, 293.0, 12.3, 393.9, 1.98],
[0.00432, 16.0, 2.11, 0.0, 0.338, 4.575, 45.2, 2.09, 1.0, 294.0, 13.3, 394.9, 2.98],
[0.00532, 17.0, 2.21, 0.0, 0.438, 5.575, 55.2, 3.09, 1.0, 295.0, 14.3, 395.9, 3.98],
[0.00632, 18.0, 2.31, 0.0, 0.538, 6.575, 65.2, 4.09, 1.0, 296.0, 15.3, 396.9, 4.98]]
t_predict = estimator.predict(t)
print('t的预测结果',t_predict)
Linear1()
那不是亏死了