# 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. spring事务详解(一)初探事务

    系列目录 spring事务详解(一)初探事务 spring事务详解(二)简单样例 spring事务详解(三)源码详解 spring事务详解(四)测试验证 spring事务详解(五)总结提高 引子 很多 ...

  2. Nginx 配置location root 转自https://blog.csdn.net/rofth/article/details/78581617

    nginx指定文件路径有两种方式root和alias,root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上. 最基本的区别 ...

  3. squid http,https, 代理,默认端口3128

    squid http,https, 代理,默认端口3128 https 代理时出现 403,是因为squid默认允许 192.168.0.0 网段代理 在配置文件中,““acl localnet sr ...

  4. 利用微信支付的订单查询接口可以在APP 中提高支付的可靠性

    最近公司有一个应用,用户可以在微信公众号上面下单,也可以在APP 中下单. 当用户在公共号上面下单时,微信支付成功可以返回微信支付单号,但是在APP 中用户微信支付时,个别时候会出现用户已经付款成功, ...

  5. js通过replace()方法配合正则去除空格

    <script> //去掉全部空格 var str = " 546546 4564 46 46 88 88 "; var str = str.replace(/\s+/ ...

  6. mybatis的plugin

    1.Mybatis-Plugin的设计思路 听起来一个挺神奇的单词,插件.说白了就是使用了Jdk自带的动态代理.在需要的时候进行代理.AOP怎么用,他就怎么用. Plugin类等价于Invocatio ...

  7. 工作中拓展的加密解密传输方式. DES对称加密传输.

    系统间通过xml传输, 不能采用明文, 就加密传输. 秘钥(真正有效的是前8位)存储于配置中. public static string EncryptStr(this string content, ...

  8. Microsoft Speaker Recognition API

    azure说话人识别API 官方文档:https://westus.dev.cognitive.microsoft.com/docs/services/563309b6778daf02acc0a508 ...

  9. adb相关指令 笔记

      adb相关指令 笔记 1.adb devices 查看物理测试设备或模拟器的相关信息,有三个状态: (1)device 设备已连接到adb服务器上,但该状态并不代表设备已启动完毕可以进行操作: ( ...

  10. 数据库事务的四大特性以及事务的隔离级别(mysql)

      本篇讲诉数据库中事务的四大特性(ACID),并且将会详细地说明事务的隔离级别. 如果一个数据库声称支持事务的操作,那么该数据库必须要具备以下四个特性: ⑴ 原子性(Atomicity) 原子性是指 ...