1.神经网络(neural network,缩写NN)
神经网络主要由:输入层,隐藏层,输出层构成。当隐藏层只有一层时,该网络为三层神经网络,当没有隐藏层时,网络为两层的神经网络。实际中,网络输入层的每个神经元代表了一个特征,输出层个数代表了分类个数,而隐藏层层数以及隐藏层神经元是由人工设定。一个基本的三层神经网络可见下图:
2.神经网络目标函数
3.神经网络优化算法
损失函数
4.例子
4.1简单神经网络对手写体字的识别——NN:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("data/", one_hot=True)
#利用tf.truncated_normal实现截断的正态分布,其标准差为0.1 [-1, 784]x[784, 300]
W = tf.Variable(tf.truncated_normal([784,300],stddev=0.1))
b = tf.Variable(tf.zeros([300]))
#[784, 300]x[300, 10]
W1 = tf.Variable(tf.truncated_normal([300,10]))
b1 = tf.Variable(tf.zeros([10]))
#定义输入x,Dropout的比率keep_prob(通常在训练时小于1,而预测时等于1)
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder("float", [None,10])
keep_prob = tf.placeholder(tf.float32)
#hidden1:隐含层 y = relu(W1*x+b1)
hidden1 = tf.nn.relu(tf.matmul(x,W) + b)
# 调用tf.nn.dropout实现Dropout,keep_prob在训练时小于1,用于制造随机性,防止过拟合;
# 在预测时等于1,即使用全部特征来预测样本类别
hidden1_drop = tf.nn.dropout(hidden1, keep_prob)
#prediction
y = tf.nn.softmax(tf.matmul(hidden1_drop, W1)+b1)
#2.训练模型:交叉熵
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y)))
#梯度下降算法
train_step = tf.train.AdadeltaOptimizer(0.3).minimize(cross_entropy)
#4.评估模型predict
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#3.train
init = tf.initialize_all_variables()
# 开启会话训练:
with tf.Session() as sess:
# 初始化变量
sess.run(init)
#训练1000次:
for i in range(3000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys,keep_prob: 0.75})
if i % 500 == 0:
train_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels,keep_prob:1.0})
print("step %d, training accuracy %g" % (i, train_accuracy))
#测试:94%
print(sess.run(accuracy,{x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
4.2两层神经网络:
#有一个隐含层的而且还使用dropout解决过拟合的问题
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("data/", one_hot=True)
#多层感知机 :NN
#利用tf.truncated_normal实现截断的正态分布,其标准差为0.1 [-1, 784]x[784, 300]
W = tf.Variable(tf.truncated_normal([784,300],stddev=0.1))
b = tf.Variable(tf.zeros([300]))
#[784, 300]x[300, 10]
W1 = tf.Variable(tf.truncated_normal([300,10]))
b1 = tf.Variable(tf.zeros([10]))
#定义输入x,Dropout的比率keep_prob(通常在训练时小于1,而预测时等于1)
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder("float", [None,10])
keep_prob = tf.placeholder(tf.float32)
#hidden1:隐含层 y = relu(W1*x+b1)
hidden1 = tf.nn.relu(tf.matmul(x,W) + b)
# 调用tf.nn.dropout实现Dropout,keep_prob在训练时小于1,用于制造随机性,防止过拟合;
# 在预测时等于1,即使用全部特征来预测样本类别
hidden1_drop = tf.nn.dropout(hidden1, keep_prob)
#prediction
y = tf.nn.softmax(tf.matmul(hidden1_drop, W1)+b1)
#2.训练模型:交叉熵
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y)))
#梯度下降算法
train_step = tf.train.AdadeltaOptimizer(0.3).minimize(cross_entropy)
#4.评估模型predict
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#3.train
init = tf.initialize_all_variables()
# 开启会话训练:
with tf.Session() as sess:
# 初始化变量
sess.run(init)
#训练1000次:
for i in range(3000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys,keep_prob: 0.75})
if i % 500 == 0:
train_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels,keep_prob:1.0})
print("step %d, training accuracy %g" % (i, train_accuracy))
#测试:94%
print(sess.run(accuracy,{x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
4.3CNN识别:
#卷积神经网络来训练
#输入图像和目标输出类别创建节点
x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])
#变量:
# W = tf.Variable(tf.zeros([784,10]))
# b = tf.Variable(tf.zeros([10]))
#权重初始化
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
#卷积和池化
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
# 第一层卷积
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
#
keep_prob = tf.placeholder(tf.float32)
fc1_drop=tf.nn.dropout(h_pool1,keep_prob)
# 第二层卷积
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(fc1_drop, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
fc1_drop2=tf.nn.dropout(h_pool2,keep_prob)
# 密集连接层
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(fc1_drop2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# dropput 减少过拟合,我们在输出层之前加入dropout。
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 输出层
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
# 训练和评估模型
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#评估准确率;
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 定义一个初始化变量op
init_op = tf.global_variables_initializer()
# 开启会话运行
with tf.Session() as sess:
sess.run(init_op)
#迭代训练:
for i in range(2000):
batch = mnist.train.next_batch(50)
# 运行train_训练
sess.run(train_step, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
if i % 100 == 0:
train_accuracy = sess.run(accuracy,feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g" % (i, train_accuracy))
#测试:
#print("test accuracy %g" % sess.run(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))