Unverified Commit 9393c215 authored by Kiryuu Sakuya's avatar Kiryuu Sakuya 🎵
Browse files

Update Code

parent bc7928f7
...@@ -4,14 +4,65 @@ import tensorflow as tf ...@@ -4,14 +4,65 @@ import tensorflow as tf
import numpy import numpy
import matplotlib.pyplot as pyplot import matplotlib.pyplot as pyplot
numpy.random.seed() with tf.compat.v1.Session() as sess:
# 生成 x_data numpy.random.seed()
x_data = numpy.linspace(0, 100, 500)
# 生成 y_data # 生成 x_data
y_data = 3.1234 * x_data + 2.98 + numpy.random.randn(*x_data.shape) * 0.9 x_data = numpy.linspace(0, 100, 500)
# 画出散点图 # 生成 y_data
pyplot.scatter(x_data, y_data) y_data = 3.1234 * x_data + 2.98 + numpy.random.randn(*x_data.shape) * 0.9
# 画出想要学习的目标函数 # 画出散点图
pyplot.plot(x_data, 3.1234 * x_data + 2.98, color = "red", linewidth = 1) pyplot.scatter(x_data, y_data)
# pyplot.show() # 画出想要学习的目标函数
\ No newline at end of file pyplot.plot(x_data, 3.1234 * x_data + 2.98, color = "red", linewidth = 1)
# pyplot.show()
# 构建模型
# https://stackoverflow.com/questions/58986126/replacing-placeholder-for-tensorflow-v2
x = tf.keras.Input(name = "x", shape = (), dtype = tf.dtypes.float32)
y = tf.keras.Input(name = "y", shape = (), dtype = tf.dtypes.float32)
# 定义模型
def model(x, w, b):
return tf.multiply(x, w) + b
# 定义模型结构
w = tf.Variable(2.5, name = "w0")
b = tf.Variable(2.0, name = "b0")
# predict 是预测值,前向计算
predict = model(x, w, b)
# 训练模型
# 迭代次数,即训练轮数
train_rounds = 10
# 设置学习率
learning_rate = 0.0251
# 定义损失函数,本处采用均方差
# 交叉熵也是一个常见的 L2 损失函数
loss_function = tf.reduce_mean(tf.square(y - predict))
# 定义优化器
# 本处初始化梯度下降优化器
# https://stackoverflow.com/questions/55682718/module-tensorflow-api-v2-train-has-no-attribute-gradientdescentoptimizer
# https://stackoverflow.com/questions/58722591/typeerror-minimize-missing-1-required-positional-argument-var-list
optimizer = tf.optimizers.SGD(learning_rate).minimize(loss_function, var_list=[w, b])
# 开始训练
# 记录训练步数
step = 0
# 用于保存loss值的列表
loss_list = []
# 设置迭代轮次
for epoch in range(train_rounds):
for xs, ys in zip(x_data, y_data):
_, loss = sess.run([optimizer, loss_function], feed_dict = {x: xs, y: ys})
# 将每一次的损失值放入列表
loss_list.append(loss)
step = step + 1
# 每训练20个样本输出一次损失值
display_step = 20
if step % display_step == 0:
print("Train Epoch: %02d" % (epoch + 1),"Step: %04d" % step, "loss = ", "{:.9f}".format(loss))
# 每一轮训练完,有一个w,b值
b0temp = b.eval(session = sess)
w0temp = w.eval(session = sess)
# 画出训练模型
pyplot.plot(x_data, w0temp * x_data + b0temp)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment