基于XILINX FPGA的卷积神经网络(二)

Python+tensorflow代码 model.py importtensorflowastf defweight_variable(shape):   initial=tf.truncated_normal(shape,stddev=0.1)   returntf.Variable(initial) defbias_variable(shape):   initial=tf.con

Python+tensorflow代码


model.py



import tensorflow as tf




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




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




def cnn(x, y_, keep_prob):
    W_conv1 = weight_variable([5, 5, 1, 6])
    b_conv1 = bias_variable([6])
    h_conv1 = tf.nn.relu(conv2d(x, W_conv1) + b_conv1)
    h_pool1 = max_pooling_2x2(h_conv1)


    W_conv2 = weight_variable([5, 5, 6, 12])
    b_conv2 = bias_variable([12])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pooling_2x2(h_conv2)


    W_fc1 = weight_variable([3*3*12, 10])
    b_fc1 = bias_variable([10])
    h_pool2_flat = tf.reshape(h_pool2, [-1, 3*3*12])
    y_conv = tf.nn.softmax(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
    c = tf.matmul(h_pool2_flat, W_fc1) + b_fc1


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


    # W_fc2 = weight_variable([16, 10])
    # b_fc2 = bias_variable([10])


    # y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
    loss = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv), reduction_indices=[1]))


    return y_conv, loss, c



mnist_train,py


import scipy.io as sio
import tensorflow as tf
import random
from model import cnn
import matplotlib.pyplot as plt






# input data
trainset_image = sio.loadmat('./trainset_image.mat')
train_image = trainset_image['image']/255.0
trainset_label = sio.loadmat('./trainset_label.mat')
train_label = trainset_label['label']


testset_image = sio.loadmat('./testset_image.mat')
test_image = testset_image['image']/255.0
testset_label = sio.loadmat('./testset_label.mat')
test_label = testset_label['label']




sess = tf.InteractiveSession()


# x = tf.reshape(train_image[887, :], [24, 24])
# sess.run(tf.initialize_all_variables())
# a = sess.run(x)
# plt.figure('1')
# plt.imshow(a, cmap='gray')
# plt.axis('off')
# plt.show()


batch_size = 64
epochs = 20
learning_rate = 1e-4
model_path = "/media/cj/141C6F521C6F2E44/example3_mnist/logs/model.ckpt"


x = tf.placeholder(tf.float32, [None, 24*24])
y_ = tf.placeholder(tf.float32, [None, 10])
x_image = tf.reshape(x, [-1, 24, 24, 1])


keep_prob = tf.placeholder(tf.float32)


y_conv, loss = cnn(x_image, y_, keep_prob)


train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)




sess.run(tf.initialize_all_variables())




train_size = train_image.shape[0]
index = range(train_size)
random.shuffle(index)
train_image, train_label = train_image[index], train_label[index]


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


for i in range(epochs):
    random.shuffle(index)
    train_image, train_label = train_image[index], train_label[index]
    for j in xrange(0, train_size, batch_size):
        train_step.run(feed_dict={x: train_image[j:j+batch_size],
                                  y_: train_label[j:j+batch_size], keep_prob: 0.5})
    train_accuracy = accuracy.eval(feed_dict={x: train_image[j:j+batch_size],
                                  y_: train_label[j:j+batch_size], keep_prob: 1.0})
    print("step %d, training accuracy %g" % (i, train_accuracy))


print("test accuracy %g" % accuracy.eval(feed_dict={x: test_image, y_: test_label, keep_prob: 1.0}))


save_path = saver.save(sess, model_path)



mnist_test.py




import tensorflow as tf
import matplotlib.pyplot as plt
import scipy.io as sio
from model import cnn


testset_image = sio.loadmat('./testset_image.mat')
test_image = testset_image['image']/255.0
testset_label = sio.loadmat('./testset_label.mat')
test_label = testset_label['label']




sess = tf.InteractiveSession()




model_path = "/media/uesr/LENOVO/tensorflowtest/mnist_tensorflow/logs/model.ckpt"
# define the placeholder of input


x = tf.placeholder(tf.float32, [None, 24*24])
y_ = tf.placeholder(tf.float32, [None, 10])
x_image = tf.reshape(x, [-1, 24, 24, 1])
keep_prob = tf.placeholder(tf.float32)


y_conv, loss, result = cnn(x_image, y_, keep_prob)
# evaluation


correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


# start training


sess.run(tf.initialize_all_variables())
saver = tf.train.Saver()
load_path = saver.restore(sess, model_path)
print("test accuracy %g" % accuracy.eval(feed_dict={x: test_image, y_: test_label, keep_prob: 1.0}))
landmark = sess.run(result, feed_dict={x: test_image[1:2], keep_prob: 1.0})
print landmark




#sio.savemat('result_10.mat', {'a': landmark})




作者:会思考的程序猿
原文链接:https://blog.csdn.net/cj1343395571/article/details/77005921

  • 发表于 2019-03-11 14:37
  • 阅读 ( 758 )
  • 分类:神经网络

0 条评论

请先 登录 后评论

作家榜 »

  1. AI君 10 文章
  2. Tzung-Wen Liau 0 文章
  3. blairan 0 文章
  4. rookie 0 文章
  5. 陈凯 0 文章
  6. huanxue 0 文章
  7. admin 0 文章
  8. Lzs1998_csdn 0 文章