實驗1-波士頓房價預測
1
from sklearn.linear_model import LinearRegression, SGDRegressor, Ridge, LogisticRegression
# from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
# from sklearn.externals import joblib
import joblib
from sklearn.metrics import r2_score
from sklearn.neural_network import MLPRegressor
import pandas as pd
import numpy as np
# lb = load_boston()
# x_train, x_test, y_train, y_test = train_test_split(lb.data, lb.target, test_size=0.2)
data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
x_train, x_test, y_train, y_test = train_test_split(data, target, test_size=0.2)
# 為資料增加一個維度,相當於把[1, 5, 10] 變成 [[1, 5, 10],]
y_train = y_train.reshape(-1, 1)
y_test = y_test.reshape(-1, 1)
# 進行標準化
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)
y_test = std_y.transform(y_test)
# 正規方程預測
lr = LinearRegression()
lr.fit(x_train, y_train)
print("r2 score of Linear regression is",r2_score(y_test,lr.predict(x_test)))
2
#迴歸
from sklearn.linear_model import RidgeCV
cv = RidgeCV(alphas=np.logspace(-3, 2, 100))
cv.fit (x_train , y_train)
print("r2 score of Linear regression is",r2_score(y_test,cv.predict(x_test)))
3
#梯度下降
sgd = SGDRegressor()
sgd.fit(x_train, y_train)
print("r2 score of Linear regression is",r2_score(y_test,sgd.predict(x_test)))
4
from keras.models import Sequential
from keras.layers import Dense
#基準NN
#使用標準化後的資料
seq = Sequential()
#構建神經網路模型
#input_dim來隱含的指定輸入資料shape
seq.add(Dense(64, activation='relu'))
seq.add(Dense(64, activation='relu'))
seq.add(Dense(1, activation='relu'))
seq.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
seq.fit(x_train, y_train, epochs=300, batch_size = 16, shuffle = False)
score = seq.evaluate(x_test, y_test,batch_size=16) #loss value & metrics values
print("score:",score)
print('r2 score:',r2_score(y_test, seq.predict(x_test)))