简单神经网络

三层简单神经网络

import tensorflow as tf

定义变量

w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
x = tf.constant([[0.7, 0.9]])   # 输入

定义前向传播的神经网络(forward-propagation)

[a = xw_1; y = aw_2 ]

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

调用会话输出结果

with tf.Session() as sess:
    sess.run(w1.initializer)  
    sess.run(w2.initializer)  
    print(sess.run(y)) 
[[3.957578]]

使用 placeholder

placeholder 机制可避免计算图太大,因为,每次使用 tf.constant 便需要创建一个节点。

# 虽然维度不一定要指定,但是指定后可以降低出错率。
x = tf.placeholder(tf.float32, shape=(1, 2), name="input")
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

init_op = tf.global_variables_initializer()  # 调用初始化变量

with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(y, feed_dict={x: [[0.7, 0.9]]}))
[[3.957578]]

增加多个输入

x = tf.placeholder(tf.float32, shape=(3, 2), name="input")
a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

sess = tf.Session()
#使用tf.global_variables_initializer()来初始化所有的变量
init_op = tf.global_variables_initializer()  
sess.run(init_op)

print(sess.run(y, feed_dict={x: [[0.7,0.9],[0.1,0.4],[0.5,0.8]]}))   # 输入3个样例
[[ 3.95757794]
 [ 1.15376544]
 [ 3.16749239]]

import tensorflow as tf
from numpy.random import RandomState

完整神经网络样例程序

定义神经网络的参数,输入和输出节点。

batch_size = 8  # 定义训练数据batch的大小

# 通过`seed`设定随机种子,可以保证每次运行得到的结果是一样的。
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))

# 在 `shape`的一个维度上使用`None`可以方便使用不大的batch大小。
# 在训练时需要把数据分成比较小的batch,但是在测试时,可以一次性的使用全部的数据。当
# 数据集比较小时方便测试,但数据集比较大时会导致内存溢出。
x = tf.placeholder(tf.float32, shape=(None, 2), name="x-input")
y_ = tf.placeholder(tf.float32, shape=(None, 1), name='y-input')

定义前向传播过程,损失函数及反向传播算法(back-propagation)。

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)
cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))    # 交叉熵,`y_` 代表正确结果,`y` 代表预测值
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)      # 反向传播优化方法

生成模拟数据集。

rdm = RandomState(1)
X = rdm.rand(128,2)
#  定义规则来给出样本的标签,在这里所有的 `x1 + x2 < 1` 的样本被认为是正样本,而其他样本为负样本。
Y = [[int(x1+x2 < 1)] for (x1, x2) in X]

创建一个会话来运行TensorFlow程序。

with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    
    # 输出目前(未经训练)的参数取值。
    print("w1:", sess.run(w1))
    print("w2:", sess.run(w2))
    print("
")
    
    # 训练模型。
    STEPS = 5000      # 设定训练轮数
    for i in range(STEPS):
        # 每次选取batch_size个样本进行训练
        start = (i*batch_size) % 128
        end = (i*batch_size) % 128 + batch_size

        # 通过选取的样本训练神经网络并更新参数
        sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]})
        if i % 1000 == 0:
            # 每隔一段时间计算在所有数据的交叉熵并输出
            total_cross_entropy = sess.run(cross_entropy, feed_dict={x: X, y_: Y})
            print("After %d training step(s), cross entropy on all data is %g" % (i, total_cross_entropy))
    
    # 输出训练后的参数取值。
    print("
")
    print("w1:", sess.run(w1))
    print("w2:", sess.run(w2))
w1: [[-0.8113182   1.4845988   0.06532937]
 [-2.4427042   0.0992484   0.5912243 ]]
w2: [[-0.8113182 ]
 [ 1.4845988 ]
 [ 0.06532937]]


After 0 training step(s), cross entropy on all data is 0.0674925
After 1000 training step(s), cross entropy on all data is 0.0163385
After 2000 training step(s), cross entropy on all data is 0.00907547
After 3000 training step(s), cross entropy on all data is 0.00714436
After 4000 training step(s), cross entropy on all data is 0.00578471


w1: [[-1.9618274  2.582354   1.6820377]
 [-3.4681718  1.0698233  2.11789  ]]
w2: [[-1.8247149]
 [ 2.6854665]
 [ 1.418195 ]]
原文地址:https://www.cnblogs.com/q735613050/p/7632965.html