Tensorflow-交叉熵&過擬合

清風紫雪發表於2021-01-28

交叉熵

二次代價函式

 

 

 原理

 

 

 缺陷

 

 

 假如我們目標是收斂到0。A點為0.82離目標比較近,梯度比較大,權值調整比較大。B點為0.98離目標比較遠,梯度比較小,權值調整比較小。調整方案不合理。

交叉熵代價函式(cross-entropy)

換一個思路,我們不改變啟用函式,而是改變代價函式,改用交叉熵代價函式:

 

 

 原理

 

 

 用法

 

 

 實戰

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
tf.compat.v1.disable_eager_execution()
import numpy as np


#載入資料集
mnist=input_data.read_data_sets("MNIST_data",one_hot=True)

#每個批次大小
batch_size=100
#計算一共有多少個批次
n_bath=mnist.train.num_examples // batch_size
print(n_bath)
#定義兩個placeholder
x=tf.compat.v1.placeholder(tf.float32,[None,784])
y=tf.compat.v1.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.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#梯度下降
train_step=tf.compat.v1.train.GradientDescentOptimizer(0.2).minimize(loss)

#初始化變數
init=tf.compat.v1.global_variables_initializer()

#結果存放在一個布林型列表中
#返回的是一系列的True或False argmax返回一維張量中最大的值所在的位置,對比兩個最大位置是否一致
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))

#求準確率
#cast:將布林型別轉換為float,將True為1.0,False為0,然後求平均值
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))


with tf.compat.v1.Session() as sess:
    sess.run(init)
    for epoch in range(21):
        for batch in range(n_bath):
            #獲得一批次的資料,batch_xs為圖片,batch_ys為圖片標籤
            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))

輸出:明顯可以看到有了巨大的變化

 

 

 擬合

 

 

 防止過擬合

 

 

 程式碼

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
tf.compat.v1.disable_eager_execution()
import numpy as np


#載入資料集
mnist=input_data.read_data_sets("MNIST_data",one_hot=True)


# 批次的大小
batch_size = 128
n_batch = mnist.train.num_examples // batch_size

x = tf.compat.v1.placeholder(tf.float32, [None,784])
y = tf.compat.v1.placeholder(tf.float32, [None, 10])
keep_prob = tf.compat.v1.placeholder(tf.float32)

# 建立神經網路
W1 = tf.Variable(tf.compat.v1.truncated_normal([784,2000],stddev=0.1))
b1 = tf.Variable(tf.zeros([1, 2000]))
# 啟用層
layer1 = tf.nn.relu(tf.matmul(x,W1) + b1)
# drop層
layer1 = tf.nn.dropout(layer1,keep_prob)

# 第二層
W2 = tf.Variable(tf.compat.v1.truncated_normal([2000,500],stddev=0.1))
b2 = tf.Variable(tf.zeros([1, 500]))
layer2 = tf.nn.relu(tf.matmul(layer1,W2) + b2)
layer2 = tf.nn.dropout(layer2,keep_prob)

# 第三層
W3 = tf.Variable(tf.compat.v1.truncated_normal([500,10],stddev=0.1))
b3 = tf.Variable(tf.zeros([1,10]))
prediction = tf.nn.sigmoid(tf.matmul(layer2,W3) + b3)

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))

# 梯度下降法
# train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)#得到97的正確率
train_step = tf.compat.v1.train.AdadeltaOptimizer(0.1).minimize(loss)


# 初始化變數
init = tf.compat.v1.global_variables_initializer()

prediction_2 = tf.nn.softmax(prediction)
# 得到一個布林型列表,存放結果是否正確
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction_2,1)) #argmax 返回一維張量中最大值索引

# 求準確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) # 把布林值轉換為浮點型求平均數

with tf.compat.v1.Session() as sess:
    sess.run(init)
    for epoch in range(100):
        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, keep_prob:0.8})
        test_acc = sess.run(accuracy, feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0} )
        train_acc = sess.run(accuracy, feed_dict={x: mnist.train.images, y: mnist.train.labels, keep_prob: 1.0})
        print("Iter " + str(epoch) + ",Testing Accuracy " + str(test_acc) + ",Train Accuracy " + str(train_acc))

 

相關文章