使用TensorFlow 构造一个神经元,简单的线性回归网络。
问题:
现有一组有噪声的样本数据,共2000个,每一个样本 x 有 3 个特征, 对应一个标签 y 值。从数据样本中学习 y = w × x + b y=w\times x + b y=w×x+b 中的参数
首先我们来生成样本数据,w_real 和 b_real 是控制样本数据的参数的真实值,
- np.random.randn(num, shape): 生成指定数量的随机数,使用默认的高斯分布(mean = 0, stddev = 1)
- np.matmul(a, b): 矩阵乘法,左行(由axis 0 索引)对右列(由axis 1 索引)
x_data = np.random.randn(2000, 4)
w_real = [0.2, 0.3, 0.1, 0.3]
b_real = -0.3
noise = np.random.randn(1, 2000)*0.1
y_data = np.matmul(w_real, x_data.T) + b_real + noise
编写神经网络
下面会用到的 Tensorflow API
- tf.reset_default_graph() : 清除默认图中的内容
- tf.Graph(): 创建一张图
- with g.as_default() : 在with 语句块范围内, 将 g 设置为默认图, as_default() 返回对象是 python ContextManager
- tf.placeholder(dtype, shape, name=None): 在默认图上放置一个 placeholder 节点, 用以接收输入数据
- tf.Variable(init_val, dtype, name=None): 创建变量型Tensor, 每次执行都会创建新的,可用tf.get_variable(name, shape, dtype, initializer)
- tf.reduce_mean(x, name=None) 计算成员平均值,reduce 的意思是输出降维,默认输出是标量(常量)
- tf.transpose(x): 转置, 可以加 perm = [3, 1, 0, 2] 参数控制数轴交换顺序。
- tf.add() : 张量加法
- tf.square(): 张量的平方
- tf.train.GradientDescentOptimizer(lr, name=None) : 在图上构造SGD优化器
- optimizer.minimize(loss_op, name=None): 在图上加入基于loss_op 的优化运算节点
- tf.global_variables_initializer() : 创建全局初始化节点,它会自动收集并信赖所有的Tensor 的初始化节点
- tf.Session(): 创建一个会话
- session.run(fetches, feed_dict=None): 运行 fetches 指定的节点, 自动分析节点的依赖情况并依次运行,fetches 节点的依赖如果有重复,只会运行一次,后续会直接取之前的运算结果,用相同的fetches 多次调用.run() 则会每次重新计算。
官方TensorFlow 文档
全部源代码实现:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 创建数据模拟
x_data = np.random.randn(2000, 4)
w_real = [0.2, 0.3, 0.1, 0.3]
b_real = -0.3
noise = np.random.randn(1, 2000)*0.1
y_data = np.matmul(w_real, x_data.T) + b_real + noise
# 清除默认图中的内容
tf.reset_default_graph()
# 设置步数
NUM_STEP = 10
# 学习率
learning_rate = 0.5
# 创建图
g = tf.Graph()
# 存储wb
wb_sess = []
with g.as_default():
# x, y_true 占位符
x = tf.placeholder(tf.float32, name = 'x')
y_true = tf.placeholder(tf.float32, name = 'y_true')
# w, b 变量
w = tf.Variable([[0,0,0,0]], dtype = tf.float32, name = 'w')
b = tf.Variable(0, dtype = tf.float32, name = 'b')
# 预测值 y = w * x + b
y_pred = tf.add(tf.matmul(w, tf.transpose(x)), b, name = 'y_pred')
# 损失 计算成员平均值
loss = tf.reduce_mean(tf.square(y_true - y_pred), name = 'loss')
# 优化器,SGD
optimizer = tf.train.GradientDescentOptimizer(learning_rate, name='SGD')
train = optimizer.minimize(loss, name = 'train')
# 全局初始化节点
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(NUM_STEP):
sess.run(train, {x: x_data, y_true: y_data})
wb_sess.append(sess.run([w, b]))
if (step % 5 == 0):
print(step + 1, sess.run([w, b]))
print(NUM_STEP, sess.run([w, b]))
总结:
这只会让你了解TensorFlow的一些API 特性,加强使用这些API,简单模型。