tensorflow 交叉熵 softmax分类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/philosophyatmath/article/details/80666938

THE MNIST DATABASE

http://yann.lecun.com/exdb/mnist/
https://blog.csdn.net/simple_the_best/article/details/75267863

交叉熵(cross entropy)的定义

对多分类问题(multi-class),通常使用 cross-entropy 作为 loss function。cross entropy 最早是信息论(information theory)中的概念,由信息熵(information entropy,与压缩比率有关)变化而来,然后被用到很多地方,包括通信,纠错码,博弈论和机器学习等。交叉熵与信息熵的关系请见:
机器学习基础(六)—— 交叉熵代价函数(cross-entropy error)

H ( y , y ) = H y ( y ) = i y i log y i

交叉熵考察的是两个的信息(分布)的期望:,熵考察的是单个的信息(分布)的期望.

神经元的输出设为:

z i = j w i j x i j + b

其中 w i j 是第i个神经元的第j个权重,b是偏移值。 z i 表示该网络的第i个输出。
给这个输出加上一个softmax函数,那就变成了这样:
a i = e z i k e z k
a i 代表softmax的第i个输出值,右侧就是套用了softmax函数。

损失函数 loss function

在神经网络反向传播中,要求一个损失函数,这个损失函数其实表示的是真实值与网络的估计值的误差,知道误差了,才能知道怎样去修改网络中的权重。
损失函数可以有很多形式,这里用的是交叉熵函数,主要是由于这个求导结果比较简单,易于计算,并且交叉熵解决某些损失函数学习缓慢的问题。交叉熵的函数是这样的:
C = i y i ln a i

其中 y i 表示数据集中真实的类别, a i

推导过程

C z i
C z i = C a j a j z i
C a j = ( j y j ln a j ) a j = j y j 1 a j

如果i=j:

a i z i = ( e z i k e z k ) z i = k e z k e z i ( e z i ) 2 ( k e z k ) 2 = ( e z i k e z k ) ( 1 e z i k e z k ) = a i ( 1 a i )

如果i≠j:

a j z i = ( e z j k e z k ) z i = 0 e z j e z i ( k e z k ) 2 = a i a j

组合起来:

C z i = ( j y j 1 a j ) a j z i = y i a i a i ( 1 a i ) + j i y j a j a i a j = y i + y i a i + j i y j a i = y i + a i j y j

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : Zhang DaPeng
# @File    : softmax_test.py
# @Software: PyCharm

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
# 本程序是tensorflow中的基本例程: 使用softmax回归实现手写数字识别
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # 只显示error

mnist = input_data.read_data_sets("../cnn_example/MNIST_data",one_hot=True)
print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.labels.shape)
#print(mnist.train.labels[0])

sess = tf.InteractiveSession()
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) # 预测值
y_ = tf.placeholder(tf.float32,[None,10]) # 真实值
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),axis=1))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

tf.global_variables_initializer().run()

for i in range(1000):
    batch_xs,batch_ys = mnist.train.next_batch(100)
    train_step.run({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,tf.float32))

print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))

猜你喜欢

转载自blog.csdn.net/philosophyatmath/article/details/80666938
今日推荐