"""
Created on Mon Oct 22 13:04:34 2018
@author: lg
"""
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
n_train_samples = 200
X_train = np.linspace(-5, 5, n_train_samples)
Y_train = 1.2*X_train + np.random.uniform(-1.0, 1.0, n_train_samples)
n_test_samples = 50
X_test = np.linspace(-5, 5, n_test_samples)
Y_test = 1.2*X_test
learning_rate = 0.01
batch_size = 20
summary_dir = 'logs'
print('~~~~~~~~~~开始设计计算图~~~~~~~~')
with tf.name_scope('Input'):
X = tf.placeholder(dtype=tf.float32, shape=None, name='X')
Y = tf.placeholder(dtype=tf.float32, shape=None, name='Y')
with tf.name_scope('Inference'):
W = tf.Variable(initial_value=tf.truncated_normal(shape=[1]), name='weight')
b = tf.Variable(initial_value=tf.truncated_normal(shape=[1]), name='bias')
Y_pred = tf.multiply(X, W) + b
with tf.name_scope('Loss'):
loss = tf.reduce_mean(tf.square(Y_pred - Y), name='loss')
tf.summary.scalar('loss', loss)
with tf.name_scope('Optimization'):
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
init = tf.global_variables_initializer()
merge = tf.summary.merge_all()
with tf.Session() as sess:
sess.run(init)
summary_writer = tf.summary.FileWriter(logdir=summary_dir, graph=sess.graph)
for i in range(201):
j = np.random.randint(0, 10)
X_batch = X_train[batch_size*j: batch_size*(j+1)]
Y_batch = Y_train[batch_size*j: batch_size*(j+1)]
_, summary, train_loss, W_pred, b_pred = sess.run([optimizer, merge, loss, W, b], feed_dict={X: X_batch, Y: Y_batch})
test_loss = sess.run(loss, feed_dict={X: X_test, Y: Y_test})
summary_writer.add_summary(summary, global_step=i)
print('step:{}, losses:{}, test_loss:{}, w_pred:{}, b_pred:{}'.format(i, train_loss, test_loss, W_pred[0], b_pred[0]))
if i == 200:
plt.plot(X_train, Y_train, 'bo', label='Train data')
plt.plot(X_test, Y_test, 'gx', label='Test data')
plt.plot(X_train, X_train * W_pred + b_pred, 'r', label='Predicted data')
plt.legend()
plt.show()
summary_writer.close()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)