发布时间:2024-05-02 18:01
from sklearn.datasets import load_boston
import joblib
from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
\"\"\"线性回归预测房子价格\"\"\"
# 获取数据
lb = load_boston()
print(lb)
# 分割数据集 (训练集、测试集)
x_train, x_text, y_train, y_test = train_test_split(lb.data, lb.target, test_size=0.25)
# 进行标准化
# 特征值 目标值 都标准化
std_x = StandardScaler()
x_train = std_x.fit_transform(x_train)
x_text = std_x.fit_transform(x_text)
std_y = StandardScaler()
y_train = std_y.fit_transform(y_train.reshape(-1, 1)) # 传入数据必须二维
y_test = std_y.fit_transform(y_test.reshape(-1, 1))
# estimator预测
# 正规方程求解方式
lr = LinearRegression()
lr.fit(x_train, y_train)
# print(lr.coef_)
y_lr_predict = std_y.inverse_transform(lr.predict(x_text))
# print(\"预测:\\n\", y_lr_predict)
print(\"均方误差:\", mean_squared_error(std_y.inverse_transform(y_test), y_lr_predict))
print(f\"R : {lr.score(x_test, y_test)}\")
# 梯度下降方式
sgd = SGDRegressor()
sgd.fit(x_train, y_train)
y_sgd_predict = std_y.inverse_transform(sgd.predict(x_text))
print(y_sgd_predict)
print(\"均方误差:\", mean_squared_error(std_y.inverse_transform(y_test), y_sgd_predict))
print(f\"R : {sgd.score(x_test, y_test)}\")
本文参考的是下面这篇博文:
这篇文章里有些东西其实已经用不了了,我自己改了下