TensorFlow入门篇(二):线性回归

版权声明:本文为博主原创文章,博主欢迎各位转载。 https://blog.csdn.net/tuwenqi2013/article/details/84557600

理论知识:https://www.cnblogs.com/GuoJiaSheng/p/3928160.html

环境:Python 3.7

          TensorFlow 1.12

          numpy 1.15.4

代码:

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

# 生成带有噪声的随机点
x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]
noise = np.random.normal(0, 0.02, x_data.shape)
y_data = np.square(x_data) + noise

# 定义两个placeholder
x = tf.placeholder(tf.float32, [None, 1])
y = tf.placeholder(tf.float32, [None, 1])

# 定义神经网络中间层
weight_1 = tf.Variable(tf.random.normal([1, 10]))
biase_1 = tf.Variable(tf.zeros([1, 10]))
out_z1 = tf.matmul(x, weight_1) + biase_1
L1 = tf.nn.tanh(out_z1)    # 激活函数

# 定义神经网络输出层
weight_2 = tf.Variable(tf.random.normal([10, 1]))
biase_2 = tf.Variable(tf.zeros(1, 1))
out_z2 = tf.matmul(L1, weight_2) + biase_2
prediction = tf.nn.tanh(out_z2)    # 激活函数

# 定义损失函数
loss = tf.reduce_mean(tf.square(y - prediction))

# 定义神经网络训练方法
train_step = tf.train.GradientDescentOptimizer(0.6).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for _ in range(500):
        sess.run(train_step, feed_dict={x: x_data, y: y_data})
    # 获得最新预测值
    prediction_value = sess.run(prediction, feed_dict={x: x_data})
    # 画图
    plt.figure()
    plt.scatter(x_data, y_data)
    plt.plot(x_data, prediction_value, 'r-', lw=5)
    plt.show()

结果:

猜你喜欢

转载自blog.csdn.net/tuwenqi2013/article/details/84557600