这是一个图像分类的比赛CIFAR( CIFAR-10 - Object Recognition in Images )

首先我们需要下载数据文件,地址:

http://www.cs.toronto.edu/~kriz/cifar.html

CIFAR-10数据集包含10个类别的60000个32x32彩色图像,每个类别6000个图像。有50000张训练图像和10000张测试图像。

数据集分为五个训练批次和一个测试批次,每个批次具有10000张图像。测试批次包含每个类别中恰好1000张随机选择的图像。训练批次按随机顺序包含其余图像,但是某些训练批次可能包含比另一类更多的图像。在它们之间,培训批次精确地包含每个班级的5000张图像。

这些类是完全互斥的。汽车和卡车之间没有重叠。“汽车”包括轿车,SUV和类似的东西。“卡车”仅包括大型卡车。都不包括皮卡车。

详细代码:

1.导包

 import numpy as np

 # 序列化和反序列化
import pickle from sklearn.preprocessing import OneHotEncoder import warnings
warnings.filterwarnings('ignore') import tensorflow as tf

2.数据加载

 def unpickle(file):

with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='ISO-8859-1')
return dict # def unpickle(file):
# import pickle
# with open(file, 'rb') as fo:
# dict = pickle.load(fo, encoding='bytes')
# return dict labels = []
X_train = []
for i in range(1,6):
data = unpickle('./cifar-10-batches-py/data_batch_%d'%(i))
labels.append(data['labels'])
X_train.append(data['data']) # 将list类型转换为ndarray
y_train = np.array(labels).reshape(-1)
X_train = np.array(X_train) # reshape
X_train = X_train.reshape(-1,3072) # 目标值概率
one_hot = OneHotEncoder()
y_train =one_hot.fit_transform(y_train.reshape(-1,1)).toarray()
display(X_train.shape,y_train.shape)

3.构建神经网络

 X = tf.placeholder(dtype=tf.float32,shape = [None,3072])
y = tf.placeholder(dtype=tf.float32,shape = [None,10])
kp = tf.placeholder(dtype=tf.float32) def gen_v(shape):
return tf.Variable(tf.truncated_normal(shape = shape)) def conv(input_,filter_,b):
conv = tf.nn.relu(tf.nn.conv2d(input_,filter_,strides=[1,1,1,1],padding='SAME') + b)
return tf.nn.max_pool(conv,[1,3,3,1],[1,2,2,1],'SAME') def net_work(input_,kp): # 形状改变,4维
input_ = tf.reshape(input_,shape = [-1,32,32,3])
# 第一层
filter1 = gen_v(shape = [3,3,3,64])
b1 = gen_v(shape = [64])
conv1 = conv(input_,filter1,b1)
# 归一化
conv1 = tf.layers.batch_normalization(conv1,training=True) # 第二层
filter2 = gen_v([3,3,64,128])
b2 = gen_v(shape = [128])
conv2 = conv(conv1,filter2,b2)
conv2 = tf.layers.batch_normalization(conv2,training=True) # 第三层
filter3 = gen_v([3,3,128,256])
b3 = gen_v([256])
conv3 = conv(conv2,filter3,b3)
conv3 = tf.layers.batch_normalization(conv3,training=True) # 第一层全连接层
dense = tf.reshape(conv3,shape = [-1,4*4*256])
fc1_w = gen_v(shape = [4*4*256,1024])
fc1_b = gen_v([1024])
fc1 = tf.matmul(dense,fc1_w) + fc1_b
fc1 = tf.layers.batch_normalization(fc1,training=True)
fc1 = tf.nn.relu(fc1)
# fc1.shape = [-1,1024] # dropout
dp = tf.nn.dropout(fc1,keep_prob=kp) # 第二层全连接层
fc2_w = gen_v(shape = [1024,1024])
fc2_b = gen_v(shape = [1024])
fc2 = tf.nn.relu(tf.layers.batch_normalization(tf.matmul(dp,fc2_w) + fc2_b,training=True)) # 输出层
out_w = gen_v(shape = [1024,10])
out_b = gen_v(shape = [10])
out = tf.matmul(fc2,out_w) + out_b
return out

4.损失函数准确率

 out = net_work(X,kp)

 loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y,logits=out))

 # 准确率
y_ = tf.nn.softmax(out) # equal 相当于 ==
accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y,axis = -1),tf.argmax(y_,axis = 1)),tf.float16))
accuracy

5.最优化

 opt = tf.train.AdamOptimizer().minimize(loss)
opt

6.开启训练

 epoches = 50000
saver = tf.train.Saver() index = 0
def next_batch(X,y):
global index
batch_X = X[index*128:(index+1)*128]
batch_y = y[index*128:(index+1)*128]
index+=1
if index == 390:
index = 0
return batch_X,batch_y test = unpickle('./cifar-10-batches-py/test_batch')
y_test = test['labels']
y_test = np.array(y_test)
X_test = test['data']
y_test = one_hot.transform(y_test.reshape(-1,1)).toarray()
y_test[:10] with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(epoches):
batch_X,batch_y = next_batch(X_train,y_train)
opt_,loss_ = sess.run([opt,loss],feed_dict = {X:batch_X,y:batch_y,kp:0.5})
print('----------------------------',loss_)
if i % 100 == 0:
score_test = sess.run(accuracy,feed_dict = {X:X_test,y:y_test,kp:1.0})
score_train = sess.run(accuracy,feed_dict = {X:batch_X,y:batch_y,kp:1.0})
print('iter count:%d。mini_batch loss:%0.4f。训练数据上的准确率:%0.4f。测试数据上准确率:%0.4f'%
(i+1,loss_,score_train,score_test))


这个准确率只达到了百分之80

如果想提高准确率,还需要进一步优化,调参

利用卷积神经网络处理cifar图像分类的更多相关文章

  1. TensorFlow系列专题(十四): 手把手带你搭建卷积神经网络实现冰山图像分类

    目录: 冰山图片识别背景 数据介绍 数据预处理 模型搭建 结果分析 总结 一.冰山图片识别背景 这里我们要解决的任务是来自于Kaggle上的一道赛题(https://www.kaggle.com/c/ ...

  2. Neuromation新研究:利用卷积神经网络进行儿童骨龄评估

    近日,Neuromation 团队在 Medium 上撰文介绍其最新研究成果:利用卷积神经网络(CNN)评估儿童骨龄,这一自动骨龄评估系统可以得到与放射科专家相似或更好的结果.该团队评估了手骨不同区域 ...

  3. 【翻译】TensorFlow卷积神经网络识别CIFAR 10Convolutional Neural Network (CNN)| CIFAR 10 TensorFlow

    原网址:https://data-flair.training/blogs/cnn-tensorflow-cifar-10/ by DataFlair Team · Published May 21, ...

  4. 利用卷积神经网络(CNN)构造社区问答系统

    /* 版权声明:能够随意转载,转载时请标明文章原始出处和作者信息 .*/                                                     author: 张俊林 ...

  5. 利用卷积神经网络(VGG19)实现火灾分类(附tensorflow代码及训练集)

    源码地址 https://github.com/stephen-v/tensorflow_vgg_classify 1. VGG介绍 1.1. VGG模型结构 1.2. VGG19架构 2. 用Ten ...

  6. Tensorflow学习教程------利用卷积神经网络对mnist数据集进行分类_利用训练好的模型进行分类

    #coding:utf-8 import tensorflow as tf from PIL import Image,ImageFilter from tensorflow.examples.tut ...

  7. 利用卷积神经网络实现MNIST手写数据识别

    代码: import torch import torch.nn as nn import torch.utils.data as Data import torchvision # 数据库模块 im ...

  8. SIGAI深度学习第八集 卷积神经网络2

    讲授Lenet.Alexnet.VGGNet.GoogLeNet等经典的卷积神经网络.Inception模块.小尺度卷积核.1x1卷积核.使用反卷积实现卷积层可视化等. 大纲: LeNet网络 Ale ...

  9. 直白介绍卷积神经网络(CNN)【转】

    英文地址:https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/ 中文译文:http://mp.weixin.qq.com/s ...

随机推荐

  1. 【概率论】5-7:Gama分布(The Gamma Distributions Part II)

    title: [概率论]5-7:Gama分布(The Gamma Distributions Part II) categories: - Mathematic - Probability keywo ...

  2. LOJ6071. 「2017 山东一轮集训 Day5」字符串 [SAM]

    LOJ 思路 这种计数题显然是要先把每一个合法的串用唯一的方法表示出来.(我连这都没想到真是无可救药了) 如何唯一?容易想到把前缀尽可能多地在第一个串填掉,然后填第二个,第三个-- 如何做到这样?可以 ...

  3. linux 日志写入到指定文件中

    php  /data/xxx/aaa.php > test.log 2>&1 >覆盖, >>追加 2>&1 表示不仅命令行正常的输出保存到test. ...

  4. 一次docker镜像的迁移

    docker 镜像迁移 背景,本地测试环境要切到线上测试,镜像下载或编译都需要时间. 所以直接scp镜像过去来节省时间. save 相对于export会占用更多存储空间 被迁移服务器导出所有镜像 do ...

  5. JSP了解点基础

    了解即可: 1.JSP本质: 是将jsp文件解析为java servlet类! 生成.class文件   存放在工程的work文件夹内! 2.注释  <%--   --%>    html ...

  6. 实现一个简易版webpack

    现实 webpack 的打包产物 大概长这样(只把核心代码留下来): 实现一个简版的webpack 依葫芦画瓢,实现思路分2步: 1. 分析入口文件,把所有的依赖找出来(包括所有后代的依赖) 2. 拼 ...

  7. svn乌龟怎么用

    0601 首先右键SVN-checkout 0602 其他地方可以不用修改,Version处可以修改,表示从指定版本号开始,点击OK. 0603 就会直接下载,如果改变的话,就会由绿色变成红色. 06 ...

  8. Nginx:fastcgi_param详解

    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;#脚本文件请求的路径 fastcgi_param QUERY_STRI ...

  9. 2018-2019-2 《网络对抗技术》Exp9 WebGoat 20165326

    Web安全基础 jar包,密码:9huw 实验问题回答 SQL注入攻击原理,如何防御 原理:恶意用户在提交查询请求的过程中将SQL语句插入到请求内容中,同时程序本身对未对插入的SQL语句进行过滤,导致 ...

  10. arcgis python 异常处理

    import arcpy in_features = "c:/base/transport.gdb/roads" try: # Note: CopyFeatures will al ...