深度学习中cifar10的代码
深度学习中cifar10的代码
#import tensorflow as tf
import numpy as np
import pickle
da = open(‘data_batch_1’, ‘rb’) # 读取文件,以2进制的形式 返回一个对象
data = pickle.load(da, encoding=‘bytes’) # 通过这个方法把读取的对象加载为字典形式
print(data)
x_data = np.array(data[b’data’]/255) # 取出字典中键为b‘data’的数据作为特征值 /255是归1化 对取出的数据进行维度转变要做卷积得转成4维 ,(-1, 3, 32, 32) 是n个对象 3通道 32*32的数据 然后转置为(-1,32,32,3) 方便卷积使用
x_data = x_data.reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
y_da = np.array(data[b’labels’]) # 取出字典中键为b‘labels’的数据作为标签
y_data = np.eye(10)[y_da] # 把标签转变为one_hot类型
print(x_data.shape)
print(y_data)
x = tf.placeholder(tf.float32, [None, 32, 32, 3]) # 定义占位符 是根据特征的维度来定义的
y = tf.placeholder(tf.float32, [None, 10]) # 根据标签转为one_hot类型后的数据来定义的
定义批次方法
def next_batch(size):
global g_b
xs = x_data[g_b:g_b+size]
ys = y_data[g_b:g_b+size]
g_b += size
return xs,ys
卷积第一层
with tf.name_scope(‘conv1’): # with 这行是用来tensorboard 可视化用的 下面的也一样
w1 = tf.Variable(tf.random_normal([3, 3, 3, 16])) # 定义卷积核 tf.random_normal([3, 3, 3, 16] 随机产生符合正态分布的卷积核 3*3大小 输入3个卷积核 输出16个卷积核
l1 = tf.nn.conv2d(x, w1, strides=[1, 1, 1, 1], padding=‘SAME’) # 卷积操作 strides 步长 padding='SAME’填充到和卷积前的数据大小一样
l1 = tf.nn.relu(l1) # 非线性激活函数
l1 = tf.nn.max_pool(l1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=‘SAME’) #池化操作
卷积第二层
with tf.name_scope(‘conv2’):
w2 = tf.Variable(tf.random_normal([3, 3, 16, 32]))
l2 = tf.nn.conv2d(l1, w2, strides=[1, 1, 1, 1], padding=‘SAME’)
l2 = tf.nn.relu(l2)
l2 = tf.nn.max_pool(l2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=‘SAME’)
对数据进行转换维度 要转为2维 进行全连接
dim = l2.shape[1]*l2.shape[2]*l2.shape[3]
l2 = tf.reshape(l2, [-1, dim])
全连接层
with tf.name_scope(‘connect’):
w3 = tf.get_variable(‘w3’, shape=[dim, 10], initializer=tf.contrib.layers.xavier_initializer())
b3 = tf.get_variable(‘b3’, shape=[10], initializer=tf.contrib.layers.xavier_initializer())
h = tf.matmul(l2, w3)+b3
定义代价函数
with tf.name_scope(‘cost’):
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=h, labels=y))
tf.summary.histogram(‘cost’, cost)
定义优化模型
with tf.name_scope(‘optimiter’):
optimiter = tf.train.AdamOptimizer(0.01).minimize(cost)
定义预测类型
pred = tf.argmax(h, 1)
定义精确度
with tf.name_scope(‘accury’):
accury = tf.reduce_mean(tf.cast(tf.equal(pred, tf.argmax(y,1)), tf.float32))
tf.summary.histogram(‘accruy’,accury)
设置批次大小
batch_size = 100
global_step = 0
创建会话
with tf.Session() as se:
# 定义全局变量
se.run(tf.global_variables_initializer())
# 可视化操作
su = tf.summary.merge_all()
# 定义可视化输出对象文件
writer = tf.summary.FileWriter(‘aa’, graph=se.graph)
for epch in range(10):
g_b = 0
avg = 0
# 计算小批量循环次数
total = x_data.shape[0]//batch_size
# 小批量循环
for i in range(total):
# 调用批次方法
xs, ys = next_batch(batch_size)
# 执行会话
cs, s, _ = se.run([cost,su,optimiter], feed_dict={x: xs, y: ys}) # 把要执行的变量写成列表传进去,feed数据
avg += cs/total # 对代价进行取均值
writer.add_summary(s, global_step=global_step) #把可视化数据写进文件
global_step += 1
print(epch, avg)