import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data/', one_hot=True)
trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testlabel = mnist.test.labels
# 輸入和輸出
n_input = 784
n_output = 10
#卷積神經網路的引數初始化(w,b)
weights = {
'wc1': tf.Variable(tf.random.normal([3, 3, 1, 64], stddev=0.1)), #第一層卷積層權重引數[3, 3, 1, 64]卷積核的大小(3*3*1);卷積核的個數64(特征圖的個數)
'wc2': tf.Variable(tf.random.normal([3, 3, 64, 128], stddev=0.1)), #第二層卷積層權重引數[3, 3, 64, 128]卷積核的大小(3*3*64(與輸入影像深度對應));卷積核的個數128(特征圖的個數)
'wd1': tf.Variable(tf.random.normal([7*7*128, 1024], stddev=0.1)),#第一層全連接層權重引數(由于該模型中卷積并未改變輸入影像的大小,經過兩次池化原始影像大小(28*28)變為(7*7))
'wd2': tf.Variable(tf.random.normal([1024, n_output], stddev=0.1))#第二層全連接層權重引數(10分類)
}
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):
# 輸入預處理(轉換為TensorFlow支持的格式)的
_input_r = tf.reshape(_input, shape=[-1, 28, 28, 1])#第一維:batchsize的大小(-1讓TensorFlow根據其余值推斷該值的大小);第二維:影像的高度;第三維:影像的寬度;第四維:影像的深度
# 第一層卷積
_conv1 = tf.nn.conv2d(_input_r, _w['wc1'], strides=[1, 1, 1, 1], padding='SAME')
#print(help(tf.nn.conv2d))查看函式的幫助檔案
#strides=[batchsize的stride大小, h的stride大小, w的stride大小, c的stride大小]
#padding='SAME'/'VALID':自動填充0(推薦)/不進行填充
#_mean, _var = tf.nn.moments(_conv1, [0, 1, 2])
#_conv1 = tf.nn.batch_normalization(_conv1, _mean, _var, 0, 1, 0.0001)
_conv1 = tf.nn.relu(tf.nn.bias_add(_conv1, _b['bc1']))#卷積之后進行激活
_pool1 = tf.nn.max_pool(_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
#池化操作,ksize視窗大小(batchsize的大小;影像的高度;影像的寬度;影像的深度),strides=[1, 2, 2, 1]:h和w方向步長均為2
_pool_dr1 = tf.nn.dropout(_pool1, _keepratio)#dropout(隨機地減少部分節點)
# 第二層卷積
_conv2 = tf.nn.conv2d(_pool_dr1, _w['wc2'], strides=[1, 1, 1, 1], padding='SAME')
#_mean, _var = tf.nn.moments(_conv2, [0, 1, 2])
#_conv2 = tf.nn.batch_normalization(_conv2, _mean, _var, 0, 1, 0.0001)
_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)
# 全連接層
_dense1 = tf.reshape(_pool_dr2, [-1, _w['wd1'].get_shape().as_list()[0]])#定義全連接的輸入
# 第一層全連接層(神經網路)
_fc1 = tf.nn.relu(tf.add(tf.matmul(_dense1, _w['wd1']), _b['bd1']))
_fc_dr1 = tf.nn.dropout(_fc1, _keepratio)
# 第一、二層全連接層
_out = tf.add(tf.matmul(_fc_dr1, _w['wd2']), _b['bd2'])
# 定義回傳值
out = { 'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool_dr1,
'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'dense1': _dense1,
'fc1': _fc1, 'fc_dr1': _fc_dr1, 'out': _out
}
return out
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_v2(y, _pred))
optm = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
_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()
sess = tf.Session()
sess.run(init)
training_epochs = 15
batch_size = 100 #網路結果比較復雜,這里取小一些,方便演示,正常情況下要稍大一些
display_step = 1
for epoch in range(training_epochs):
avg_cost = 0.
#total_batch = int(mnist.train.num_examples/batch_size)
total_batch = 10 #簡單示例,正常情況如上
# Loop over all batches
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# Fit training using batch data
sess.run(optm, feed_dict={x: batch_xs, y: batch_ys, keepratio:0.7})
# Compute average loss
avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keepratio:1.})/total_batch
# Display logs per epoch step
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))
#test_acc = sess.run(accr, feed_dict={x: testimg, y: testlabel, keepratio:1.})
#print (" Test accuracy: %.3f" % (test_acc))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/274907.html
上一篇:求助代碼仿真
下一篇:一道python基礎題
