# （二）代码示例

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

# 启用动态图机制
tf.enable_eager_execution()

# 设定学习率
learning_rate = 0.01
# 训练迭代次数
train_steps = 1000
# 构造训练数据
train_X = np.array([[3.3],[4.4],[5.5],[6.71],[6.93],[4.168],[9.799],[6.182],[7.59],[2.167],[7.042],[10.791],[5.313],[7.997],[5.654],[9.27],[3.1]],dtype = np.float32)
train_Y = np.array([[1.7],[2.76],[2.09],[3.19],[1.694],[1.573],[3.366],[2.596],[2.53],[1.221],[2.827],[3.465],[1.65],[2.904],[2.42],[2.94],[1.3]],dtype = np.float32)
# 输入数据
def network(data_x, data_y):
X = data_x
Y_ = data_y
# 定义模型参数
w = tf.Variable(tf.random_normal([1, 1]),name = "weight")
b = tf.Variable(tf.zeros([1]), name = "bias")
# 构建模型Y = weight*X + bias
# 定义损失函数
loss = tf.reduce_sum(tf.pow((Y-Y_), 2))/17

print(loss)

return loss

# 训练1000次
for i in range(0, 1000):
# 在动态图机制下，minimize要求接收一个函数
optimizer.minimize((lambda: network(train_X, train_Y)))

# 输 出：
···
tf.Tensor(54.92399, shape=(), dtype=float32)
tf.Tensor(6.5630927, shape=(), dtype=float32)
tf.Tensor(4.874648, shape=(), dtype=float32)
tf.Tensor(23.35061, shape=(), dtype=float32)
tf.Tensor(27.08449, shape=(), dtype=float32)
tf.Tensor(55.983494, shape=(), dtype=float32)
tf.Tensor(18.76203, shape=(), dtype=float32)
···


# （三）总 结

©️2019 CSDN 皮肤主题: 黑客帝国 设计师: 上身试试