# coding: utf-8

import time
import numpy as np
import tensorflow as tf
import _pickle as pickle
import matplotlib.pyplot as plt def unpickle(filename):
import pickle
with open(filename, 'rb') as fo:
data = pickle.load(fo, encoding='latin1')
return data def onehot(labels):
n_sample = len(labels)
n_class = max(labels) + 1
onehot_labels = np.zeros((n_sample, n_class))
onehot_labels[np.arange(n_sample), labels] = 1
return onehot_labels # 训练数据集
data1 = unpickle('F:\\TensorFlow_deep_learn\\cifar-10-batches-py\\data_batch_1')
data2 = unpickle('F:\\TensorFlow_deep_learn\\cifar-10-batches-py\\data_batch_2')
data3 = unpickle('F:\\TensorFlow_deep_learn\\cifar-10-batches-py\\data_batch_3')
data4 = unpickle('F:\\TensorFlow_deep_learn\\cifar-10-batches-py\\data_batch_4')
data5 = unpickle('F:\\TensorFlow_deep_learn\\cifar-10-batches-py\\data_batch_5') X_train = np.concatenate((data1['data'], data2['data'], data3['data'], data4['data'], data5['data']), axis=0)
y_train = np.concatenate((data1['labels'], data2['labels'], data3['labels'], data4['labels'], data5['labels']), axis=0)
y_train = onehot(y_train)
# 测试数据集
test = unpickle('F:\\TensorFlow_deep_learn\\cifar-10-batches-py\\test_batch')
X_test = test['data'][:5000, :]
y_test = onehot(test['labels'])[:5000, :] print('Training dataset shape:', X_train.shape)
print('Training labels shape:', y_train.shape)
print('Testing dataset shape:', X_test.shape)
print('Testing labels shape:', y_test.shape) with tf.device('/cpu:0'): # 模型参数
learning_rate = 1e-3
training_iters = 200
batch_size = 50
display_step = 5
n_features = 3072 # 32*32*3
n_classes = 10
n_fc1 = 384
n_fc2 = 192 # 构建模型
x = tf.placeholder(tf.float32, [None, n_features])
y = tf.placeholder(tf.float32, [None, n_classes]) W_conv = {
'conv1': tf.Variable(tf.truncated_normal([5, 5, 3, 32], stddev=0.0001)),
'conv2': tf.Variable(tf.truncated_normal([5, 5, 32, 64],stddev=0.01)),
'fc1': tf.Variable(tf.truncated_normal([8*8*64, n_fc1], stddev=0.1)),
'fc2': tf.Variable(tf.truncated_normal([n_fc1, n_fc2], stddev=0.1)),
'fc3': tf.Variable(tf.truncated_normal([n_fc2, n_classes], stddev=0.1))
}
b_conv = {
'conv1': tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[32])),
'conv2': tf.Variable(tf.constant(0.1, dtype=tf.float32, shape=[64])),
'fc1': tf.Variable(tf.constant(0.1, dtype=tf.float32, shape=[n_fc1])),
'fc2': tf.Variable(tf.constant(0.1, dtype=tf.float32, shape=[n_fc2])),
'fc3': tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[n_classes]))
} x_image = tf.reshape(x, [-1, 32, 32, 3])
# 卷积层 1
conv1 = tf.nn.conv2d(x_image, W_conv['conv1'], strides=[1, 1, 1, 1], padding='SAME')
conv1 = tf.nn.bias_add(conv1, b_conv['conv1'])
conv1 = tf.nn.relu(conv1)
# 池化层 1
pool1 = tf.nn.avg_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')
# LRN层,Local Response Normalization
norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001/9.0, beta=0.75)
# 卷积层 2
conv2 = tf.nn.conv2d(norm1, W_conv['conv2'], strides=[1, 1, 1, 1], padding='SAME')
conv2 = tf.nn.bias_add(conv2, b_conv['conv2'])
conv2 = tf.nn.relu(conv2)
# LRN层,Local Response Normalization
norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001/9.0, beta=0.75)
# 池化层 2
pool2 = tf.nn.avg_pool(norm2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')
reshape = tf.reshape(pool2, [-1, 8*8*64]) fc1 = tf.add(tf.matmul(reshape, W_conv['fc1']), b_conv['fc1'])
fc1 = tf.nn.relu(fc1)
# 全连接层 2
fc2 = tf.add(tf.matmul(fc1, W_conv['fc2']), b_conv['fc2'])
fc2 = tf.nn.relu(fc2)
# 全连接层 3, 即分类层
fc3 = tf.nn.softmax(tf.add(tf.matmul(fc2, W_conv['fc3']), b_conv['fc3'])) # 定义损失
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=fc3, labels=y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss)
# 评估模型
correct_pred = tf.equal(tf.argmax(fc3, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) init = tf.global_variables_initializer() with tf.Session() as sess:
sess.run(init)
c = []
total_batch = int(X_train.shape[0] / batch_size)
# for i in range(training_iters):
start_time = time.time()
for i in range(200):
for batch in range(total_batch):
batch_x = X_train[batch*batch_size : (batch+1)*batch_size, :]
batch_y = y_train[batch*batch_size : (batch+1)*batch_size, :]
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})
acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})
print(acc)
c.append(acc)
end_time = time.time()
print('time: ', (end_time - start_time))
start_time = end_time
print("---------------%d onpech is finished-------------------",i)
print("Optimization Finished!") # Test
test_acc = sess.run(accuracy, feed_dict={x: X_test, y: y_test})
print("Testing Accuracy:", test_acc)
plt.plot(c)
plt.xlabel('Iter')
plt.ylabel('Cost')
plt.title('lr=%f, ti=%d, bs=%d, acc=%f' % (learning_rate, training_iters, batch_size, test_acc))
plt.tight_layout()
plt.savefig('F:\\cnn-tf-cifar10-%s.png' % test_acc, dpi=200)

吴裕雄 python深度学习与实践(18)的更多相关文章

  1. 吴裕雄 python深度学习与实践(17)

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import time # 声明输 ...

  2. 吴裕雄 python深度学习与实践(16)

    import struct import numpy as np import matplotlib.pyplot as plt dateMat = np.ones((7,7)) kernel = n ...

  3. 吴裕雄 python深度学习与实践(15)

    import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data mnist = ...

  4. 吴裕雄 python深度学习与实践(14)

    import numpy as np import tensorflow as tf import matplotlib.pyplot as plt threshold = 1.0e-2 x1_dat ...

  5. 吴裕雄 python深度学习与实践(13)

    import numpy as np import matplotlib.pyplot as plt x_data = np.random.randn(10) print(x_data) y_data ...

  6. 吴裕雄 python深度学习与实践(12)

    import tensorflow as tf q = tf.FIFOQueue(,"float32") counter = tf.Variable(0.0) add_op = t ...

  7. 吴裕雄 python深度学习与实践(11)

    import numpy as np from matplotlib import pyplot as plt A = np.array([[5],[4]]) C = np.array([[4],[6 ...

  8. 吴裕雄 python深度学习与实践(10)

    import tensorflow as tf input1 = tf.constant(1) print(input1) input2 = tf.Variable(2,tf.int32) print ...

  9. 吴裕雄 python深度学习与实践(9)

    import numpy as np import tensorflow as tf inputX = np.random.rand(100) inputY = np.multiply(3,input ...

随机推荐

  1. Tornado异步非阻塞的使用以及原理

    Tornado 和现在的主流 Web 服务器框架(包括大多数 Python 的框架)有着明显的区别:它是非阻塞式服务器,而且速度相当快.得利于其 非阻塞的方式和对 epoll 的运用,Tornado ...

  2. 闲话Pipeline In Maya

    在整个行业都在高呼“农业学大寨,流程学xx”的大背景下,你想推出一个新的更好的流程有着极大的难度. 在2014年的时候行业内大部分公司就有了资产的概念,会成立资产部门去专门创建资产,供后续环节多次重用 ...

  3. spring使用注解通过子类注入父类的私有变量

    方法一 通过 super.setBaseDao方法设置父类私有变量 父类 public class BaseServiceImpl {    private BaseDao baseDao; publ ...

  4. python 打印到控制台变颜色

    1 格式:\033[显示方式;前景色;背景色m 2 3 说明: 4 前景色 背景色 颜色 5 --------------------------------------- 6 30 40 黑色 7 ...

  5. 批处理判断是BIOS还是UEFI启动

    https://files.cnblogs.com/files/liuzhaoyzz/detectefi.rar @echo offpushd %~dp0reg add "HKEY_CURR ...

  6. 你云我云•兄弟夜谈会 第二季 5G

    0. 概况 时间:2019年1月29日 21:30~23:15 兄弟团:金孝(主持人).肖力.楼炜.张亮.孙杰.熊.世民 主题:5G 1. 5G超简单科普 金孝首先对大家做了超简单5G科普.5G 是第 ...

  7. # 20175311 2018-2019-2 《Java程序设计》第2周学习总结

    ## 教材学习内容总结 第二周我对如何运行java程序已经比较熟悉了,第二周更多的是注重程序内部的原理了. ## 教材学习中的问题和解决过程 - 问题1:看书时看到的一个例子,不是很懂它是怎么得出结果 ...

  8. GoLand、Pycharm注册码

    GoLand.Pycharm注册码 K71U8DBPNE-eyJsaWNlbnNlSWQiOiJLNzFVOERCUE5FIiwibGljZW5zZWVOYW1lIjoibGFuIHl1IiwiYXN ...

  9. 初次使用BAT,请检查Chrome浏览器和ChromeDriver兼容性

    ChromeDriver可以理解为Chrome驱动,它是架在BAT程序和Chrome之间的桥梁.但是ChromeDriver的问题是,每个版本的兼容范围很窄,通常只能兼容3个Chrome版本. 因此, ...

  10. centos7 安装远程桌面

    https://www.linuxidc.com/Linux/2017-09/147050.htm https://blog.csdn.net/dazhi_1314/article/details/7 ...