波士顿房价预测实验
1 from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge, LogisticRegression
2 from sklearn.datasets import load_boston
3 from sklearn.model_selection import train_test_split
4 from sklearn.preprocessing import StandardScaler
5 from sklearn.metrics import mean_squared_error
6 import joblib
7 from sklearn.metrics import r2_score
8 from sklearn.neural_network import MLPRegressor
9
10 import pandas as pd
11 import numpy as np
12
13 lb = load_boston()
14 x_train, x_test, y_train, y_test = train_test_split(lb.data, lb.target, test_size=0.2)
15
16
17 # 为数据增加一个维度,相当于把[1, 5, 10] 变成 [[1, 5, 10],]
18 y_train = y_train.reshape(-1, 1)
19 y_test = y_test.reshape(-1, 1)
20
21 # 进行标准化
22 std_x = StandardScaler()
23 x_train = std_x.fit_transform(x_train)
24 x_test = std_x.transform(x_test)
25
26 std_y = StandardScaler()
27 y_train = std_y.fit_transform(y_train)
28 y_test = std_y.transform(y_test)
1 # 正规方程预测 2 lr = LinearRegression() 3 lr.fit(x_train, y_train) 4 print("r2 score of Linear regression is",r2_score(y_test,lr.predict(x_test)))
1 #岭回归 2 from sklearn.linear_model import RidgeCV 3 4 cv = RidgeCV(alphas=np.logspace(-3, 2, 100)) 5 cv.fit (x_train , y_train) 6 print("r2 score of Linear regression is",r2_score(y_test,cv.predict(x_test)))
1 #梯度下降 2 sgd = SGDRegressor() 3 sgd.fit(x_train, y_train) 4 print("r2 score of Linear regression is",r2_score(y_test,sgd.predict(x_test)))
好看请赞,养成习惯:) 本文来自博客园,作者:靠谱杨, 转载请注明原文链接:https://www.cnblogs.com/rainbow-1/p/16051985.html
欢迎来我的51CTO博客主页踩一踩 我的51CTO博客
文章中的公众号名称可能有误,请统一搜索:靠谱杨的秘密基地