利用keras自帶房價數據集進行房價預測

 1 import numpy as np
 2 from keras.datasets import boston_housing
 3 from keras import layers
 4 from keras import models
 5 from keras import optimizers
 6 from keras.utils.np_utils import to_categorical
 7 import matplotlib.pyplot as plt
 8 
 9 def main():
10     (train_data, train_labels), (test_data, test_labels) = boston_housing.load_data()
11     mean = train_data.mean(axis = 0)# 經過(x-均值)/方差 把數據變爲均值爲0,方差爲1
12     std = train_data.std(axis = 0)
13     train_data -= mean
14     train_data /= std
15     test_data -= mean
16     test_data /= std
17 
18     model = models.Sequential()
19     model.add(layers.Dense(64, activation = 'relu', input_shape = (train_data.shape[1], )))
20     model.add(layers.Dense(64, activation = 'relu'))
21     model.add(layers.Dense(1))
22 
23     model.compile(optimizer = 'rmsprop', loss = 'mse', metrics = ['mae'])# mae: 平均絕對偏差
24 
25     model.fit(train_data, train_labels, epochs = 80, batch_size = 16)
26 
27     _, mae = model.evaluate(test_data, test_labels)
28     print(mae)
29 
30 if __name__ == "__main__":
31     main()

最後預測的房價仍是和實際價格相差約 2000美圓左右
lua

相關文章
相關標籤/搜索