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)
x1 = train_x[:, 5] # 房间数
x2 = train_x[:,7] # 另一个参数
# 样本数据归一化
x1 = (x1 - x1.min())/ (x1.max() - x1.min())
x2 = (x2 - x2.min())/ (x2.max() - x2.min())
# 维度转换
X = np.stack((x1,x2),axis=1) # 转化成一个二维数组
# print('X:',X,X.shape)
Y = train_y.reshape(-1,1) # 将房价y转化为列向量
# 超参数
iter =1000 # 迭代次数
learn_rate = 0.01 # 学习率
# 设置模型参数初始值
w = np.random.randn(2,1)
W = tf.Variable(w)
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)
loss = 0.5 * (tf.reduce_mean(pow(Y - pre_price,2)))
loss_list.append(loss)
dloss_dw = tape.gradient(loss,W) # 偏导也是一个2维向量
# print('dloss_dw:',dloss_dw)
W.assign_sub(learn_rate * dloss_dw)
if i % 100 == 0:
print('i:{},loss:{},w:{}'.format(i,loss,w))
# 画图
plt.rcParams["font.family"] = 'SimHei' # 将字体改为中文
plt.rcParams['axes.unicode_minus'] = False # 设置了中文字体默认后,坐标的"-"号无法显示,设置这个参数就可以避免
plt.plot(loss_list,label = '损失值')
plt.legend()
plt.show()
![]()