欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

tensorflow feature map显示与保存

程序员文章站 2024-01-04 09:46:22
...

feature map就是图片在网络中经过卷积等操作后的的图像

保存需要通过sess.run 将feature map 类型转换为numpy.nadarry,方便图片的处理

tensorflow feature map显示与保存

import sys
sys.path.append(r'E:\anaconda\Lib\site-packages')
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import cv2

sess = tf.InteractiveSession()
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

#网络参数
training_step = 10000
batch_size = 100
conv1in = 1
conv1out = 16
conv2out = 32
fc1size = 512


def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

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')



#初始化参数
W_conv1 = weight_variable([5, 5, conv1in, conv1out])
b_conv1 = bias_variable([conv1out])

W_conv2 = weight_variable([5, 5, conv1out, conv2out])
b_conv2 = bias_variable([conv2out])

W_fc1 = weight_variable([7 * 7 * conv2out, fc1size])
b_fc1 = bias_variable([fc1size])

keep_prob = tf.placeholder(tf.float32)

W_fc2 = weight_variable([fc1size, 10])
b_fc2 = bias_variable([10])


#inference
x_image = tf.reshape(x, [-1,28,28,1])

h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*conv2out])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2

cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))


train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

saver = tf.train.Saver() 

sess.run(tf.global_variables_initializer())

tra_accuracy = []
test_acc = []

'''
画准确率曲线
'''
def draw_pic(k):   
    plt.plot(np.linspace(0, (k+1)*10, len(tra_accuracy)),tra_accuracy,'b-',label='train acc')
    plt.plot(np.linspace(0, k*10, len(test_acc)),test_acc,'k-.',label='text acc')
    plt.legend(loc='lower right')
    plt.show()
    
'''
保存特征图,将特征图的深度方向的图在row方向上展开
'''

def save_conv1_feature_map(k):
    feature_map = np.zeros((28*10,28*conv1out))
    for j in range(10):        
        aa = sess.run(h_conv1,feed_dict={x: batch[0], keep_prob: 1})[j,:,:,:]    #shape  (28, 28, 16)   
        for i in range(conv1out):
            feature_map[j*28:(j+1)*28 , i*28:(i+1)*28] = aa[:,:,i] * 200
        cv2.imwrite(r'C:\Users\Administrator\Desktop\tensorflow_mnist\conv1_feature_map\{}con1.jpg'.format(k),feature_map)

def save_conv2_feature_map(k):
    feature_map = np.zeros((14*10,14*conv2out))
    for j in range(10):        
        aa = sess.run(h_conv2,feed_dict={x: batch[0], keep_prob: 1})[j,:,:,:]    #shape  (28, 28, 16)   
        for i in range(conv2out):
            feature_map[j*14:(j+1)*14 , i*14:(i+1)*14] = aa[:,:,i] * 200
        cv2.imwrite(r'C:\Users\Administrator\Desktop\tensorflow_mnist\conv2_feature_map\{}conv2.jpg'.format(k),feature_map)


def save_pool1_feature_map(k):
    feature_map = np.zeros((14*10,14*conv1out))
    for j in range(10):        
        aa = sess.run(h_pool1,feed_dict={x: batch[0], keep_prob: 1})[j,:,:,:]    #shape  (28, 28, 16)   
        for i in range(conv1out):
            feature_map[j*14:(j+1)*14 , i*14:(i+1)*14] = aa[:,:,i] * 200
        cv2.imwrite(r'C:\Users\Administrator\Desktop\tensorflow_mnist\pool1_feature_map\{}pool1.jpg'.format(k),feature_map)
        
   
k = 0
j = 0
for i in range(training_step):
  batch = mnist.train.next_batch(batch_size)
  if i%200 == 0:
    k += 1
    train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
    test_accuracy = accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})
    tra_accuracy.append(train_accuracy)
    test_acc.append(test_accuracy)
    print("step %d, training accuracy %g ,test accuracy %g"%(i, train_accuracy, test_accuracy))
    '''
    每200步保存一次feature map
    '''
    if i > 200:
        draw_pic(k)
        save_conv1_feature_map(i)
        save_conv2_feature_map(i)
        save_pool1_feature_map(i)
        j += 1
        
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})  
  if i%200 == 0:     
    saver.save(sess, r'C:\Users\Administrator\Desktop\tensorflow_mnist\model\model{}.ckpt'.format(i))  
    
    

上一篇:

下一篇: