1. 程式人生 > >CNN輸出每一層的卷積核,即每一層的權重矩陣和偏移量矩陣

CNN輸出每一層的卷積核,即每一層的權重矩陣和偏移量矩陣

var 圖像 cas 值轉換 auth git dom 轉換 訓練

技術分享圖片

分別是16個5*5的一通道的卷積核,以及16個偏移量。A2是轉置一下,為了輸出每一個卷積核,TensorFlow保存張量方法和人的理解有很大區別,A21 A31 A41 A51都是卷積核的權重矩陣偏移量

——————————————————————————————————————————————————————————————————————————————————————————————————

# -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 10:16:39 2018

@author: DBSF
"""
import numpy as np
import matplotlib.pyplot as plt
import input_data
import tensorflow as tf
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

train_epochs = 2 # 訓練輪數
batch_size = 100 # 隨機出去數據大小
display_step = 1 # 顯示訓練結果的間隔
learning_rate= 0.0001 # 學習效率
drop_prob = 0.5 # 正則化,丟棄比例
fch_nodes = 512 # 全連接隱藏層神經元的個數

# 網絡模型需要的一些輔助函數
# 權重初始化(卷積核初始化)
# tf.truncated_normal()不同於tf.random_normal(),返回的值中不會偏離均值兩倍的標準差
# 參數shpae為一個列表對象,例如[5, 5, 1, 32]對應
# 5,5 表示卷積核的大小, 1代表通道channel,對彩色圖片做卷積是3,單色灰度為1
# 最後一個數字32,卷積核的個數,(也就是卷基層提取的特征數量)
# 顯式聲明數據類型,切記
def weight_init(shape):
weights = tf.truncated_normal(shape, stddev=0.1,dtype=tf.float32)
return tf.Variable(weights)

# 偏置的初始化
def biases_init(shape):
biases = tf.random_normal(shape,dtype=tf.float32)
return tf.Variable(biases)

# 隨機選取mini_batch
def get_random_batchdata(n_samples, batchsize):
start_index = np.random.randint(0, n_samples - batchsize)
return (start_index, start_index + batchsize)

def xavier_init(layer1, layer2, constant = 1):
Min = -constant * np.sqrt(6.0 / (layer1 + layer2))
Max = constant * np.sqrt(6.0 / (layer1 + layer2))
return tf.Variable(tf.random_uniform((layer1, layer2), minval = Min, maxval = Max, dtype = tf.float32))

def conv2d(x, w):
return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding=‘SAME‘)

def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=‘SAME‘)

x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])
# 把灰度圖像一維向量,轉換為28x28二維結構
x_image = tf.reshape(x, [-1, 28, 28, 1])

w_conv1 = weight_init([5, 5, 1, 16]) # 5x5,深度為1,16個
b_conv1 = biases_init([16])
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1) # 輸出張量的尺寸:28x28x16
h_pool1 = max_pool_2x2(h_conv1) # 池化後張量尺寸:14x14x16
# h_pool1 , 14x14的16個特征圖

w_conv2 = weight_init([5, 5, 16, 32]) # 5x5,深度為16,32個
b_conv2 = biases_init([32])
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2) # 輸出張量的尺寸:14x14x32
h_pool2 = max_pool_2x2(h_conv2) # 池化後張量尺寸:7x7x32
# h_pool2 , 7x7的32個特征圖
# h_pool2是一個7x7x32的tensor,將其轉換為一個一維的向量
h_fpool2 = tf.reshape(h_pool2, [-1, 7*7*32])
# 全連接層,隱藏層節點為512個
# 權重初始化
w_fc1 = xavier_init(7*7*32, fch_nodes)
b_fc1 = biases_init([fch_nodes])
h_fc1 = tf.nn.relu(tf.matmul(h_fpool2, w_fc1) + b_fc1)

h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob=drop_prob)

# 隱藏層與輸出層權重初始化
w_fc2 = xavier_init(fch_nodes, 10)
b_fc2 = biases_init([10])

# 未激活的輸出
y_ = tf.add(tf.matmul(h_fc1_drop, w_fc2), b_fc2)
# 激活後的輸出
y_out = tf.nn.softmax(y_)

# 交叉熵代價函數
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(y_out), reduction_indices = [1]))

# tensorflow自帶一個計算交叉熵的方法
# 輸入沒有進行非線性激活的輸出值 和 對應真實標簽
#cross_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_, y))

# 優化器選擇Adam(有多個選擇)
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)

# 準確率
# 每個樣本的預測結果是一個(1,10)的vector
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_out, 1))
# tf.cast把bool值轉換為浮點數
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init = tf.global_variables_initializer()
mnist = input_data.read_data_sets(‘MNIST/mnist‘, one_hot=True)
n_samples = int(mnist.train.num_examples)
total_batches = int(n_samples / batch_size)

with tf.Session() as sess:
sess.run(init)
Cost = []
Accuracy = []
variable_names = [v.name for v in tf.trainable_variables()]
values = sess.run(variable_names)
for i in range(train_epochs):

for j in range(100):
start_index, end_index = get_random_batchdata(n_samples, batch_size)

batch_x = mnist.train.images[start_index: end_index]
batch_y = mnist.train.labels[start_index: end_index]
_, cost, accu = sess.run([ optimizer, cross_entropy,accuracy], feed_dict={x:batch_x, y:batch_y})
Cost.append(cost)
Accuracy.append(accu)
if i % display_step ==0:
print (‘Epoch : %d , Cost : %.7f‘%(i+1, cost))
A1=values[0]
A11=values[1]
A21=values[2]
A31=values[3]
A41=values[4]
A51=values[5]
A2=A1.transpose([3,2,1,0])
# with open(‘E:/TensorFlow/test00003.txt‘, ‘w‘) as f:
# for z in range(16):
# for y in range(5):
# for x in range(5):
# f.write(str(A2[z][0][x][y]))
# f.write(‘,‘)
# f.write(‘****************\n‘)
# f.write(‘\n\n‘)







CNN輸出每一層的卷積核,即每一層的權重矩陣和偏移量矩陣