深度学习框架tensorflow学习与应用5(softmax函数+交叉熵代价函数和二次代价函数的比较)

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


# In[3]:

#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

#每个批次的大小
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size

#定义两个placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])

#创建一个简单的神经网络
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W)+b)

#二次代价函数
# loss = tf.reduce_mean(tf.square(y-prediction))

#交叉熵函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs,batch_ys =  mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
        
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))

注释:从代码中可以看到,TensorFlow进行softmax建模只需要一句:y = tf.nn.softmax(tf.matmul(x,W) + b);

为了计算交叉熵,添加了一个占位符用于输入正确值:y_ = tf.placeholder("float", [None,10]),然后计算交叉熵。
代码中使用梯度下降算法以0.01的学习率最小化交叉熵,TensorFlow也提供了其他的优化算法。

TensorFlow实际做的是,在后台给计算图增加一系列新的计算操作单元用于实现反向传播算法和梯度下降算法。
tf.argmax 给出某个tensor对象在某一维上的数据最大值的索引值。由于标签向量由0,1组成,因此最大值1所在的索引位置就是类别标签。tf.argmax(y,1)返回的是模型对于任一输入x预测到的标签值,而 tf.argmax(y_,1) 代表正确的标签,用 tf.equal 检测预测结果是否和真实标签一致。

TensorFlow实际做的是,在后台给计算图增加一系列新的计算操作单元用于实现反向传播算法和梯度下降算法。
tf.argmax 给出某个tensor对象在某一维上的数据最大值的索引值。由于标签向量由0,1组成,因此最大值1所在的索引位置就是类别标签。tf.argmax(y,1)返回的是模型对于任一输入x预测到的标签值,而 tf.argmax(y_,1) 代表正确的标签,用 tf.equal 检测预测结果是否和真实标签一致。

  • 实验结果:

二次代价函数:

交叉熵函数:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


# In[3]:

#载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)

#每个批次的大小
batch_size = 100
#计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size

#定义两个placeholder
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])


#定义神经网络中间层
w1 = tf.Variable(tf.random_normal([784, 1000]))
b1 = tf.Variable(tf.zeros([1, 1000]))
w_plus_b_1 =tf.matmul(x,w1)+b1
l1 =tf.nn.tanh(w_plus_b_1)


#定义神经网络输出层
w2 = tf.Variable(tf.random_normal([1000, 10]))
b2 = tf.Variable(tf.zeros([1, 10]))
w_plus_b_2 = tf.matmul(l1, w2)+b2
prediction = tf.nn.softmax(w_plus_b_2)

#二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))

#交叉熵函数
# loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))#argmax返回一维张量中最大的值所在的位置
#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(20):
        for batch in range(n_batch):
            batch_xs, batch_ys =  mnist.train.next_batch(batch_size)
            sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})
            # print(sess.run(y,feed_dict={y: batch_ys}))
        # if epoch % 20 ==0:
        #     acc = sess.run(accuracy,feed_dict={x: mnist.test.images, y: mnist.test.labels})
        #     print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
        # lo = sess.run(loss, feed_dict={x: batch_xs, y: batch_ys})
        # prediction1 = sess.run(prediction, feed_dict={x: batch_xs, y: batch_ys})
        acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
        print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
        # if epoch ==10:
        #    print(",loss:"+ str(prediction1))

改写成两层的神经网络后发现,在迭代20个epoh后没有精度下降了,这看的出来可能是过拟合了。

这应该是正常的,CS231n提到当神经网络层数增大到一定程度时,才能体现出神经网络结构的优势。

Iter 0,Testing Accuracy 0.2358
Iter 1,Testing Accuracy 0.2855
Iter 2,Testing Accuracy 0.3231
Iter 3,Testing Accuracy 0.3489
Iter 4,Testing Accuracy 0.3711
Iter 5,Testing Accuracy 0.3954
Iter 6,Testing Accuracy 0.4138
Iter 7,Testing Accuracy 0.4247
Iter 8,Testing Accuracy 0.4375
Iter 9,Testing Accuracy 0.4484
Iter 10,Testing Accuracy 0.4559
Iter 11,Testing Accuracy 0.4632
Iter 12,Testing Accuracy 0.4702
Iter 13,Testing Accuracy 0.4749
Iter 14,Testing Accuracy 0.4785
Iter 15,Testing Accuracy 0.4816
Iter 16,Testing Accuracy 0.4844
Iter 17,Testing Accuracy 0.4877
Iter 18,Testing Accuracy 0.4913
Iter 19,Testing Accuracy 0.4934

这是看到别人这么写softmax分类器的代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
 
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
 
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print("Download Done!")
 
x = tf.placeholder(tf.float32, [None, 784])
 
# 参数定义
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
 
y = tf.nn.softmax(tf.matmul(x, W) + b) #softmax模型建立
y_ = tf.placeholder(tf.float32, [None, 10]) #实际的标签
 
# softmax损失函数,交叉熵
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))
#梯度下降法最优化
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

 
# 所有参数初始化并建立Session
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
 
# 训练模型,进行1000次迭代 
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
#评估模型
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
 
print("Accuarcy on Test-dataset: ", sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

从测试结果来看,简单神经网络得到的准确度低于softmax分类的测试结果。这应该是正常的,CS231n提到当神经网络层数增大到一定程度时,才能体现出神经网络结构的优势。
参考:
https://www.tensorflow.org/get_started/mnist/beginners

http://www.jeyzhang.com/tensorflow-learning-notes.html

TensorFlow实例
 

猜你喜欢

转载自blog.csdn.net/qq_37791134/article/details/84711451