1. 程式人生 > 實用技巧 >tensorflow2.0——波士頓房價資料預測(3)

tensorflow2.0——波士頓房價資料預測(3)

import tensorflow as tf
import matplotlib.pylab as plt
import numpy as np

# 呼叫資料
boston_house = tf.keras.datasets.boston_housing
(train_x, train_y), (test_x, test_y) = boston_house.load_data(test_split=0.1)
print(train_x.shape,train_y.shape)

#   樣本資料歸一化
    #   測試樣本
X = (train_x - train_x.min(axis = 0)) / (train_x.max(axis = 0) - train_x.min(axis = 0))
    
# 訓練樣本 t_X = (test_x - test_x.min(axis = 0)) / (test_x.max(axis = 0) - test_x.min(axis = 0)) print('X:',X,X.shape) Y = train_y.reshape(-1,1) # 將房價y轉化為列向量 # 測試集 t_Y = test_y.reshape(-1,1) print('Y.shape:',Y.shape) # 超引數 iter =20000 # 迭代次數 learn_rate = 0.01 # 學習率
# 設定模型引數初始值 w = np.random.randn(13,1) W = tf.Variable(w) loss_list = [] test_loss_list = [] # print('W:{},W.shape:{}'.format(W,W.shape)) for i in range(iter): with tf.GradientTape() as tape: pre_price = tf.matmul(X,W) pre_test = tf.matmul(t_X, W) loss = 0.5 * (tf.reduce_mean(pow(Y - pre_price,2))) test_loss
= 0.5 * (tf.reduce_mean(pow(t_Y - pre_test,2))) loss_list.append(loss) test_loss_list.append(test_loss) dloss_dw = tape.gradient(loss,W) # 偏導也是一個2維向量 # print('dloss_dw:',dloss_dw) W.assign_sub(learn_rate * dloss_dw) if i % 1000 == 0: print('訓練集:i:{},loss:{},W:{}'.format(i,loss,W)) print('測試集:i:{},test_loss:{},W:{}'.format(i, test_loss, W)) pre_test = tf.matmul(t_X,W) test_loss = 0.5 * (tf.reduce_mean(pow(t_Y - pre_test,2))) print('測試集loss為:',test_loss) # 畫圖 plt.rcParams["font.family"] = 'SimHei' # 將字型改為中文 plt.rcParams['axes.unicode_minus'] = False # 設定了中文字型預設後,座標的"-"號無法顯示,設定這個引數就可以避免 plt.subplot(221) plt.plot(loss_list,label = '訓練集損失值') plt.legend() plt.subplot(223) plt.plot(test_loss_list,label = '測試集損失值') plt.legend() plt.show()