1 回归模型
回归算法模型用来预测连续数值型,其目标不是分类值而是数字。为了评估这些回归预测值是否与实际目标相符,我们需要度量两者间的距离,打印训练过程中的损失,最终评估模型损失。
这里使用的例子是从均值为1、标准差为0.1的正态分布中抽样随机数,然后乘以变量A,损失函数为L2正则损失函数。理论上,A的最优值是10,因为生成的样例数据均值是1。回归算法模型拟合常数乘法,目标值是10。
1.1 实现模型
# TensorFlow实现、训练并评估回归模型
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
# 1.创建计算图、数据集、变量和占位符。
# 创建完数据后,将它们随机分割成训练数据集和测试数据集。
# 不管算法模型预测的如何,我们都需要测试算法模型,这点相当重要。
# 在训练数据和测试数据上都进行模型评估,以搞清楚模型是否过拟合:
sess = tf.Session()
x_vals = np.random.normal(1, 0.1, 100)
y_vals = np.repeat(10., 100)
x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
batch_size = 25
train_indices = np.random.choice(len(x_vals),
round(len(x_vals) * 0.8),
replace=False)
test_indices = np.array(list(set(range(len(x_vals))) -
set(train_indices)))
x_vals_train = x_vals[train_indices]
x_vals_test = x_vals[test_indices]
y_vals_train = y_vals[train_indices]
y_vals_test = y_vals[test_indices]
A = tf.Variable(tf.random_normal(shape=[1, 1]))
# 2.声明算法模型、损失函数和优化器算法。初始化模型变量A
my_output = tf.matmul(x_data, A)
loss = tf.reduce_mean(tf.square(my_output - y_target))
init = tf.global_variables_initializer()
sess.run(init)
my_opt = tf.train.GradientDescentOptimizer(0.02)
train_step = my_opt.minimize(loss)
1.2 训练模型
# 3.迭代训练模型
for i in range(100):
rand_index = np.random.choice(len(x_vals_train),size=batch_size)
rand_x = np.transpose([x_vals_train[rand_index]