预测一个 Y = 0.1 X + 0.3 一次函数。
import tensorflow as tf
import numpy as np
#测试数据
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3
#初始化权重和偏置
Weights = tf.Variable(tf.random.uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))
#输出激励值
y = Weights * x_data + biases
#设置损失函数
loss = tf.reduce_mean(tf.square(y - y_data))
#设置SGD 学习率为0.5
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
#初始化
init = tf.compat.v1.global_variables_initializer()
sess = tf.compat.v1.Session()
sess.run(init)
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(Weights), sess.run(biases))
测试结果:
更新了tensorflow2.0
import tensorflow as tf
from tensorflow.keras import layers
from matplotlib import pyplot
class Linear(tf.keras.Model):
def __init__(self):
super(Linear, self).__init__()
self.W = tf.Variable(5., name='weight')
self.B = tf.Variable(10., name='bias')
def call(self, inputs):
return inputs*self.W + self.B
NUM_EXAMPLES = 2000
training_inputs = tf.random.normal([NUM_EXAMPLES])
print(training_inputs)
noise = tf.random.normal([NUM_EXAMPLES])
training_outputs = training_inputs * 3 + 2 + noise
def loss(model, inputs, targets):
error = model(inputs) - targets
return tf.reduce_mean(tf.square(error))
def grad(model, inputs, targets):
with tf.GradientTape() as tape:
loss_value = loss(model, inputs, targets)
return tape.gradient(loss_value, [model.W, model.B])
model = Linear()
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
print("Initial loss: {:.3f}".format(loss(model, training_inputs, training_outputs)))
steps = 300
for i in range(steps):
grads = grad(model, training_inputs, training_outputs)
optimizer.apply_gradients(zip(grads, [model.W, model.B]))
if i % 20 == 0:
print("loss at step {:03d}: {:.3f}".format(i, loss(model, training_inputs, training_outputs)))
print("final loss {:.3f}".format(loss(model, training_inputs, training_outputs)))
print("W = {}, B = {}".format(model.W.numpy(), model.B.numpy()))