线性回归模型实例
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 模拟数据
train_X = np.linspace(-1, 1, 100)
train_Y = 2 * train_X + np.random.randn(* train_X.shape) * 0.3
plt.plot(train_X, train_Y, 'ro', label='Origin data')
plt.legend()
plt.show()
tf.reset_default_graph()
# 创建模型
X = tf.placeholder("float")
Y = tf.placeholder("float")
W = tf.Variable(tf.random_normal([1]), name="weight")
b = tf.Variable(tf.zeros([1]), name="bias")
z = tf.multiply(X, W) + b
tf.summary.histogram('z', z) # 将预测值以直方图形式显示
# 反向优化
cost = tf.reduce_mean(tf.square(Y-z))
tf.summary.scalar('loss_function', cost) # 将损失值以标量形式显示
learning_rate = 0.01
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # 梯度下降函数
# 初始化所有变量
init = tf.global_variables_initializer()
# 定义参数
training_epochs = 20
display_step