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)) # 0.19版本以后要求是二维,不知道样本数,所以-1,一个特征所以1
y_test = std_y.transform(y_test.reshape(-1, 1))
# estimstor预测
# 正规方程求解方式预测结果
lr = LinearRegression()
lr.fit(x_train, y_train)
print("正规方程回归系数:", lr.coef_)
# 预测的房价
y_predict = std_y.inverse_transform(lr.predict(x_test))
print("正规方程测试集里每个房子的预测价格:", y_predict)
print("正规方程的均方误差:", mean_squared_error(std_y.inverse_transform(y_test), y_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)
print("梯度下降的均值误差:", mean_squared_error(std_y.inverse_transform(y_test), y_sgd_predict))
return None
sklearn 线性回归
最新推荐文章于 2024-07-14 14:24:15 发布