import numpy as np
import tensorflow as tf
# 这里是为了演示numpy和tf的区别。
np.random.seed(43)
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
# w = np.random.rand()
# print(w)
# print(y_data)
# todo 2、 tf代码
# 一、构建模型图
with tf.Graph().as_default():
print(tf.get_default_graph())
w = tf.Variable(initial_value=tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y_hat = x_data * w + b
# print(y_hat)
loss = tf.reduce_mean(tf.square(y_data - y_hat))
print(loss)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.3)
train_opt = optimizer.minimize(loss)
epochs = 201
# 二、执行会话。
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for e in range(epochs):
_, train_loss = sess.run([train_opt, loss])
if e % 30 == 0:
print('Epoch:{} - Train Loss:{}'.format(e, train_loss))