数字数据的每层输出

# -*- 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 = 21    # 训练轮数
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 = []
    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%5==0):
            input_image = mnist.train.images[3:103]
            # 第二层池化后的特征图
            h_conv_1 = sess.run(h_conv1, feed_dict={x:input_image})          #[32, 7, 7, 1]
            h_conv_reshape_1 = sess.run(tf.reshape(h_conv_1, [16, 100, 28, 28]))
            print("h_conv1______________________________",h_conv_reshape_1.shape)
            
            h_pool_1 = sess.run(h_pool1, feed_dict={x:input_image})          #[32, 7, 7, 1]
            h_pool_reshape_1 = sess.run(tf.reshape(h_pool_1, [16, 100, 14, 14]))
            print("h_pool1______________________________",h_pool_reshape_1.shape)
        
            h_conv_2 = sess.run(h_conv2, feed_dict={x:input_image})          #[32, 7, 7, 1]
            h_conv_reshape_2 = sess.run(tf.reshape(h_conv_2, [32, 100, 14, 14]))
            print("h_conv2______________________________",h_conv_reshape_2.shape)
            
            h_pool_2 = sess.run(h_pool2, feed_dict={x:input_image})          #[32, 7, 7, 1]
            h_pool_reshape_2 = sess.run(tf.reshape(h_pool_2, [32, 100, 7, 7]))
            print("h_pool2______________________________",h_pool_reshape_2.shape)
            
            for A in range(100):
                with open('E:/TensorFlow/Tensorflow_data/h_conv1_'+str(i)+'/Conv'+str(A)+'.txt', 'w') as f:        
                    for zjj in range(16):
                        for yjj in range(28):
                            for xjj in range(28):
                                f.write(str(h_conv_reshape_1[zjj][A][xjj][yjj]))
                                f.write(',')
                            f.write('\n')
            print("SUCCESS______WRITEN________CONV___________")
            for B in range(100):
                with open('E:/TensorFlow/Tensorflow_data/h_pool1_'+str(i)+'/pool'+str(B)+'.txt', 'w') as f:        
                    for zjj in range(16):
                        for yjj in range(14):
                            for xjj in range(14):
                                f.write(str(h_pool_reshape_1[zjj][B][xjj][yjj]))
                                f.write(',')
                            f.write('\n')
            print("SUCCESS______WRITEN________POOL___________")
            for C in range(100):
                with open('E:/TensorFlow/Tensorflow_data/h_conv2_'+str(i)+'/Conv'+str(C)+'.txt', 'w') as f:        
                    for zjj in range(16):
                        for yjj in range(14):
                            for xjj in range(14):
                                f.write(str(h_conv_reshape_2[zjj][C][xjj][yjj]))
                                f.write(',')
                            f.write('\n')
            print("SUCCESS______WRITEN________CONV___________")
            for D in range(100):
                with open('E:/TensorFlow/Tensorflow_data/h_pool2_'+str(i)+'/pool'+str(D)+'.txt', 'w') as f:        
                    for zjj in range(16):
                        for yjj in range(7):
                            for xjj in range(7):
                                f.write(str(h_pool_reshape_2[zjj][D][xjj][yjj]))
                                f.write(',')
                            f.write('\n')
            print("SUCCESS______WRITEN________POOL___________")
            print("accususe",i)

#----------------------------------各个层特征可视化-------------------------------
    # imput image
    fig2,ax2 = plt.subplots(figsize=(2,2))
    ax2.imshow(np.reshape(mnist.train.images[13], (28, 28)))
    plt.show()
    
    

posted @ 2018-06-28 12:33  The_kat  阅读(171)  评论(0编辑  收藏  举报