波士顿房价预测

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# 导入数据
boston_housing=tf.keras.datasets.boston_housing
(train_x,train_y),(test_x,test_y)=boston_housing.load_data()
# 数据归一化
num_train=len(train_x)
num_test=len(test_x)
x_train=(train_x-train_x.min(axis=0))/(train_x.max(axis=0)-train_x.min(axis=0))
y_train=train_y
x_test=(test_x-test_x.min(axis=0))/(test_x.max(axis=0)-test_x.min(axis=0))
y_test=test_y

x0_train=np.ones(num_train).reshape(-1,1)
x0_test=np.ones(num_test).reshape(-1,1)

# 训练集与测试集
X_train=tf.cast(tf.concat([x0_train,x_train],axis=1),tf.float32)
X_test=tf.cast(tf.concat([x0_test,x_test],axis=1),tf.float32)

Y_train=tf.constant(y_train.reshape(-1,1),tf.float32)
Y_test=tf.constant(y_test.reshape(-1,1),tf.float32)

# 设置超参数
learn_rate=0.01
iter=8000
display_step=500

# 初始化参数
np.random.seed(6)
W=tf.Variable(np.random.randn(14,1),dtype=tf.float32)

# 训练模型
mse_train=[]
mse_test=[]

for i in range(0,iter+1):
    with tf.GradientTape() as tape:
        PRED_train=tf.matmul(X_train,W)
        Loss_train=0.5*tf.reduce_mean(tf.square(Y_train-PRED_train))
        PRED_test=tf.matmul(X_test,W)
        Loss_test=0.5*tf.reduce_mean(tf.square(Y_test-PRED_test))
    mse_train.append(Loss_train)
    mse_test.append(Loss_test)
    
    dL_dW=tape.gradient(Loss_train,W)
    W.assign_sub(learn_rate*dL_dW)
    
    if i % display_step==0:
        print('i:%i,Train Loss:%f,Test Loss:%f'%(i,Loss_train,Loss_test))
# 结果可视化
plt.figure(figsize=(15,5))
plt.subplot(121)
plt.plot(mse_train,color='blue',linewidth=3,label='Train')
plt.plot(mse_test,color='red',linewidth=3,label='Test')
plt.xlabel('Iteration',fontsize=14)
plt.ylabel('MSE',fontsize=14)
plt.legend()
plt.subplot(122)
plt.plot(y_test,color='blue',marker='o',label='true_price')
plt.plot(PRED_test,color='red',marker='*',label='predict_price')
plt.xlabel('Sample',fontsize=14)
plt.ylabel('Price',fontsize=14)
plt.legend()
plt.show()

 

posted @ 2022-11-07 21:58  山海自有归期  阅读(135)  评论(0编辑  收藏  举报