常规数学建模比赛大杀器!tensorflow实现梯度下降,多元拟合
代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
ds=pd.read_csv('dateset.csv') #导入dateset
x1=np.array(ds.iloc[:,1:5]) #读入data
y =np.array(ds.iloc[:,5]) #读入y数据
Y=y.reshape(-1,1) #将y转置为(2000,1)
#设置训练集
trainx=x1[0:600][:]
trainy=Y[0:600][:]
#设置测试集
testx=x1[600:][:]
testy=Y[600:][:]
num_train=len(trainx) #设定num_train用于后方增加一列同长度的一列 1做x0
num_test=len(testx) #设定num_test用于后方增加一列同长度的一列 1做x0
xtrain=(trainx-trainx.min(axis=0))/(trainx.max(axis=0)-trainx.min(axis=0)) #进行线性归一化
ytrain=trainy #让我的标签方式变得一致,嘻嘻嘻
xtest=(testx-testx.min(axis=0))/(testx.max(axis=0)-testx.min(axis=0)) #进行线性归一化
ytest=testy
x0_train=np.ones(num_train).reshape(-1,1) #设定一列x0=1
x0_test=np.ones(num_test).reshape(-1,1) #设定一列x0=1
Xtrain=tf.cast(tf.concat([x0_train,xtrain],axis=1),tf.float32) #增加一列x0都为1使计算方便
Xtest=tf.cast(tf.concat([x0_test,xtest],axis=1),tf.float32) #增加一列x0都为1使计算方便
Ytrain=tf.constant(ytrain,tf.float32) #转化为tesor对象
Ytest=tf.constant(ytest,tf.float32) #转化为tesor对象
learn_rate=0.4 #设置学习率
iter=2780 #设定迭代次数
display=20 #设置展示参数
np.random.seed(16) #设置种子保证每次生成的随机数据相同
W=tf.Variable(np.random.randn(5,1),dtype=tf.float32) #随机生成可训练variable W
mse_train=[] #记录loss——train
mse_test=[] #记录loss_test
for i in range(0,iter+1):
with tf.GradientTape() as tape: #利用tf的自动求导机制
pred_train=tf.matmul(Xtrain,W) #设定拟和函数
loss_train=0.5*tf.reduce_mean(tf.square(Ytrain-pred_train)) #设定train损失函数
pred_test=tf.matmul(Xtest,W) #设定拟和函数
loss_test=0.5*tf.reduce_mean(tf.square(Ytest-pred_test)) #设定test损失函数
mse_train.append(loss_train) #记录train损失函数
mse_test.append(loss_test) #记录test损失函数
dl_dw=tape.gradient(loss_train,W) #求出train的梯度
W.assign_sub(learn_rate*dl_dw) #更新W_train
if i % display==0:
print("i: %d, trainloss: %f,testloss: %f"%(i,loss_train,loss_test)) #展示部分数据
print(W)
plt.figure()
#画出两个集的loss曲线
plt.plot(mse_train,color="g",linewidth=6)
plt.plot(mse_test,color="red",linewidth=2)
plt.figure()
#画出train的数