Tensorflow一元一次方程线性回归示例

Tensorflow一元一次方程线性回归示例

下面针对:y = w.x + b

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

# 归一化函数
def  normalize(X):
    mean = np.mean(X)
    print("mean=", mean)
    std = np.std(X)
    print("std=", std)
    X = (X - mean)/std
    return X

#1. 训练数据接收占位符
X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")

#2. 初始化权重和偏置变量
b = tf.Variable(0.0, name="b")
w = tf.Variable(0.0, name="w")

#3. 定义预测的线性模型
Y_hat = X * w + b

#4. 定义损失函数
loss = tf.square(Y - Y_hat, name= "loss")

#5. 选择优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01, name="optimizer").minimize(loss)

#6. 申明初始化操作符
init_op = tf.global_variables_initializer()
total = []

with tf.Session() as sess:
     X_train = normalize(np.array([1.0, 3.0, 5.0, 7.0, 8.0]))
     Y_train = normalize(np.array([2.0, 1.0, 3.0, 4.0, 6.0]))
     n_sample = len(X_train)
     sess.run(init_op, feed_dict={X: X_train, Y: Y_train})
     writer = tf.summary.FileWriter("graphs", sess.graph)
     for i in range(100):
         total_loss = 0
         for x,y in zip(X_train, Y_train):
             _,l = sess.run([optimizer, loss], feed_dict={X:x, Y: y})
             total_loss += l
         total.append(total_loss/l)
         print("epoch {0}: loss {1}".format(i, total_loss/l))
     writer.close()
     b_value,w_value = sess.run([b,w])


Y_pred = X_train * w_value + b_value

#画图--训练数据与回归实线
#实点
plt.plot(X_train, Y_train, 'bo',  label="real_data")
#实线
plt.plot(X_train, Y_pred, label = "pred_data")
plt.legend()
plt.show()

#损失函数训练过程
plt.plot(total)
plt.show()
  • 模拟方程与训练数据的图示如下:
    在这里插入图片描述
    -损失函数训练过程如下(100次训练)
    在这里插入图片描述
    -Tensorflow Board 图示如下
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值