tensorflow一元线性回归模型,实现函数的拟合

#2021.10.11 HIT ATCI LZH
#一元线性回归模型,实现函数的拟合
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
X_train = np.linspace(0.,1.,101)[:,np.newaxis]
Y_train = X_train*3+0.02
n_samples = 101
#为训练数据申明Tensorflow占位符
X = tf.placeholder(dtype = tf.float32, shape=(None, 1), name='X')
Y = tf.placeholder(dtype = tf.float32, shape=(None, 1), name='Y')
#创建Tensorflow的权重和偏置且初始值设为0
w = tf.Variable(0.0)
b = tf.Variable(0.0)
#定义用于预测的线性回归模型
Y_hat = X*w + b

#定义损失函数
#loss = tf.square(Y - Y_hat, name='loss')
loss = tf.reduce_mean(tf.square(Y - Y_hat))#损失函数,均方误差
#选择梯度下降优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.02).minimize(loss) #学习率
#申明初始化操作符
init_op = tf.global_variables_initializer()
total = []#定义一个空列表
#启动计算图
with tf.Session() as sess:
    sess.run(init_op)#初始化变量
    for i in range(1000):
        _, l = sess.run([optimizer, loss],feed_dict = {X:X_train, Y:Y_train})
        total.append(l)
    b_value, w_value = sess.run([b, w])
    print(b_value)
    print(w_value)
#查看结果
Y_pred = X_train * w_value + b_value
print('Done')
#plot the result
plt.plot(X_train,Y_train,'bo',label='Real Date')
plt.plot(X_train,Y_pred,'r',label='Predict Data')
plt.legend()#
plt.show()
plt.plot(total)
plt.show()

你可能感兴趣的:(Tensorflow深度学习,tensorflow,深度学习,神经网络)