模型的保存:tf.train.Saver類(lèi)中的save
在訓(xùn)練一個(gè)TensorFlow模型之后,可以將訓(xùn)練好的模型保存成文件,這樣可以方便下一次對(duì)新的數(shù)據(jù)進(jìn)行預(yù)測(cè)的時(shí)候直接加載訓(xùn)練好的模型即可獲得結(jié)果,可以通過(guò)TensorFlow提供的tf.train.Saver函數(shù),將一個(gè)模型保存成文件,一般習(xí)慣性的將TensorFlow的模型文件命名為*.ckpt文件。
模型的讀取:tf.train.Saver類(lèi)中的restore
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#將參數(shù)固化到磁盤(pán)上
mnist = input_data.read_data_sets('data/', one_hot=True)
trainimg = mnist.train.images
trainlabel=mnist.train.labels
testimg=mnist.test.images[0:1500]#針對(duì)可能出現(xiàn)的分配超過(guò)系統(tǒng)內(nèi)存的問(wèn)題
testlabel=mnist.test.labels[0:1500]
print("MNIST Ready")
n_input = 784
n_output = 10
weights = {
'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64], stddev=0.1)),
'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.1)),
'wd1': tf.Variable(tf.random_normal([7*7*128, 1024], stddev=0.1)),
'wd2': tf.Variable(tf.random_normal([1024, n_output], stddev=0.1))
}
biases = {
'bc1': tf.Variable(tf.random_normal([64], stddev=0.1)),
'bc2': tf.Variable(tf.random_normal([128], stddev=0.1)),
'bd1': tf.Variable(tf.random_normal([1024], stddev=0.1)),
'bd2': tf.Variable(tf.random_normal([n_output], stddev=0.1))
}
def conv_basic(_input, _w, _b, _keepratio): # 卷積神經(jīng)網(wǎng)絡(luò)的前向傳播
# 對(duì)輸入進(jìn)行簡(jiǎn)單的預(yù)處理[n,h,w,c]-bitchsize大小,圖像的高度、寬度,深度
_input_r = tf.reshape(_input, shape=[-1, 28, 28, 1]) # -1意思是讓TensorFlow自己做一個(gè)推斷,確定了其他所有維,可推斷出第一維
'''
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
除去name參數(shù)用以指定該操作的name,與方法有關(guān)的一共五個(gè)參數(shù):
第一個(gè)參數(shù)input:指需要做卷積的輸入圖像,它要求是一個(gè)Tensor,具有[batch, in_height, in_width, in_channels]這樣的shape,
具體含義是[訓(xùn)練時(shí)一個(gè)batch的圖片數(shù)量, 圖片高度, 圖片寬度, 圖像通道數(shù)],注意這是一個(gè)4維的Tensor,要求類(lèi)型為float32和float64其中之一
第二個(gè)參數(shù)filter:相當(dāng)于CNN中的卷積核,它要求是一個(gè)Tensor,具有[filter_height, filter_width, in_channels, out_channels]這樣的shape,
具體含義是[卷積核的高度,卷積核的寬度,圖像通道數(shù),卷積核個(gè)數(shù)],要求類(lèi)型與參數(shù)input相同,有一個(gè)地方需要注意,第三維in_channels,就是參數(shù)input的第四維
第三個(gè)參數(shù)strides:卷積時(shí)在圖像每一維的步長(zhǎng),這是一個(gè)一維的向量,長(zhǎng)度4
第四個(gè)參數(shù)padding:string類(lèi)型的量,只能是"SAME","VALID"其中之一,這個(gè)值決定了不同的卷積方式
第五個(gè)參數(shù):use_cudnn_on_gpu:bool類(lèi)型,是否使用cudnn加速,默認(rèn)為true
'''
# "VALID" 僅舍棄最后列,或最后行的數(shù)據(jù)
# "SAME" 嘗試在數(shù)據(jù)左右均勻的填充0,若填充個(gè)數(shù)為奇數(shù)時(shí),則將多余的填充值放數(shù)據(jù)右側(cè).
_conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
_conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))
'''
tf.nn.max_pool(value, ksize, strides, padding, name=None)
參數(shù)是四個(gè),和卷積很類(lèi)似:
第一個(gè)參數(shù)value:需要池化的輸入,一般池化層接在卷積層后面,所以輸入通常是feature map,依然是[batch, height, width, channels]這樣的shape
第二個(gè)參數(shù)ksize:池化窗口的大小,取一個(gè)四維向量,一般是[1, height, width, 1],因?yàn)槲覀儾幌朐赽atch和channels上做池化,所以這兩個(gè)維度設(shè)為了1
第三個(gè)參數(shù)strides:和卷積類(lèi)似,窗口在每一個(gè)維度上滑動(dòng)的步長(zhǎng),一般也是[1, stride, stride, 1]
第四個(gè)參數(shù)padding:和卷積類(lèi)似,可以取'VALID'或者'SAME'
返回一個(gè)Tensor,類(lèi)型不變,shape仍然是[batch, height, width, channels]這種形式
'''
_pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
_pool1_dr1 = tf.nn.dropout(_pool1, _keepratio) # _keepratio表示保留的比例
_conv2 = tf.nn.conv2d(_pool1_dr1, _w['wc2'], strides=[1, 1, 1, 1], padding='SAME')
_conv2 = tf.nn.relu(tf.nn.bias_add(_conv2, _b['bc2']))
_pool2 = tf.nn.max_pool(_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
_pool_dr2 = tf.nn.dropout(_pool2, _keepratio)
# 全連接層——把輸出轉(zhuǎn)換為矩陣(向量)的形式
_densel = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])
_fc1 = tf.nn.relu(tf.add(tf.matmul(_densel, _w['wd1']), _b['bd1']))
_fc_dr1 = tf.nn.dropout(_fc1, _keepratio)
'''
tf.nn.dropout(x, keep_prob, noise_shape=None, seed=None, name=None)
根據(jù)給出的keep_prob參數(shù),將輸入tensor x按比例輸出。
使用說(shuō)明:
參數(shù) keep_prob: 表示的是保留的比例,假設(shè)為0.8 則 20% 的數(shù)據(jù)變?yōu)?,然后其他的數(shù)據(jù)乘以 1/keep_prob;keep_prob 越大,保留的越多;
參數(shù) noise_shape:干擾形狀。 此字段默認(rèn)是None,表示第一個(gè)元素的操作都是獨(dú)立,但是也不一定。比例:數(shù)據(jù)的形狀是shape(x)=[k, l, m, n],而noise_shape=[k, 1, 1, n],則第1和4列是獨(dú)立保留或刪除,第2和3列是要么全部保留,要么全部刪除。
'''
_out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])
out = {'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool1_dr1,
'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'densel': _densel,
'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out}
return out
print("CNN READY")
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keepratio = tf.placeholder(tf.float32)
_pred = conv_basic(x, weights, biases, keepratio)['out']
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred, labels=y))
optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)#優(yōu)化器的選擇
_corr = tf.equal(tf.argmax(_pred, 1), tf.argmax(y, 1))
accr = tf.reduce_mean(tf.cast(_corr, tf.float32))
init = tf.global_variables_initializer()
save_step=1
saver=tf.train.Saver(max_to_keep=3)
print("FUNCTIONS READY")
do_train=0
sess = tf.Session()
sess.run(init)
training_epochs = 15
batch_size = 16 # 示范,防止過(guò)慢
display_step = 1
if do_train ==1:
for epoch in range(training_epochs):
avg_cost = 0
total_batch = 10 # 示范,防止過(guò)慢
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio: 0.7})
avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio: 1.}) / total_batch
if epoch % display_step == 0:
print("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio: 1.})
print("Training accuracy: %.3f" % (train_acc))
if epoch % save_step ==0:
saver.save(sess,"save/nets/cnn_mnist_basic.ckpt-"+str(epoch))
print("FINISHED")
if do_train ==0:
epoch=training_epochs -1
saver.restore(sess,"save/nets/cnn_mnist_basic.ckpt-"+str(epoch))
test_acc=sess.run(accr,feed_dict= {x:testimg ,y:testlabel ,keepratio:1.})
print("TEST ACCURACY: %.3f"% (test_acc))