TensorFlow笔记六:基于cifar10数据库的AlexNet识别
准确率只有70%,cpu版本的TF居然跑了两天才跑完,其他方法将继续尝试。
生成数据目录:
import numpy as np
import os train_label = {} for i in range(10):
search_path = './data/train/{}'.format(i)
file_list = os.listdir(search_path)
for file in file_list:
train_label[os.path.join(search_path, file)] = i np.save('label.npy', train_label) test_label = {} for i in range(10):
search_path = './data/test/{}'.format(i)
file_list = os.listdir(search_path)
for file in file_list:
test_label[os.path.join(search_path, file)] = i np.save('test-label.npy', test_label)
训练:
import tensorflow as tf
import numpy as np
import random
import cv2 # 将传入的label转换成one hot的形式。
def getOneHotLabel(label, depth):
m = np.zeros([len(label), depth])
for i in range(len(label)):
m[i][label[i]] = 1
return m # 建立神经网络。
def alexnet(image, keepprob=0.5): # 定义卷积层1,卷积核大小,偏置量等各项参数参考下面的程序代码,下同。
with tf.name_scope("conv1") as scope:
kernel = tf.Variable(tf.truncated_normal([11, 11, 3, 64], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(image, kernel, [1, 4, 4, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[64]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(bias, name=scope) pass # LRN层
lrn1 = tf.nn.lrn(conv1, 4, bias=1.0, alpha=0.001/9, beta=0.75, name="lrn1") # 最大池化层
pool1 = tf.nn.max_pool(lrn1, ksize=[1,3,3,1], strides=[1,2,2,1],padding="VALID", name="pool1") # 定义卷积层2
with tf.name_scope("conv2") as scope:
kernel = tf.Variable(tf.truncated_normal([5,5,64,192], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(pool1, kernel, [1, 1, 1, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[192]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv2 = tf.nn.relu(bias, name=scope)
pass # LRN层
lrn2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9, beta=0.75, name="lrn2") # 最大池化层
pool2 = tf.nn.max_pool(lrn2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding="VALID", name="pool2") # 定义卷积层3
with tf.name_scope("conv3") as scope:
kernel = tf.Variable(tf.truncated_normal([3,3,192,384], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(pool2, kernel, [1, 1, 1, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[384]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv3 = tf.nn.relu(bias, name=scope)
pass # 定义卷积层4
with tf.name_scope("conv4") as scope:
kernel = tf.Variable(tf.truncated_normal([3,3,384,256], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(conv3, kernel, [1, 1, 1, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[256]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv4 = tf.nn.relu(bias, name=scope)
pass # 定义卷积层5
with tf.name_scope("conv5") as scope:
kernel = tf.Variable(tf.truncated_normal([3,3,256,256], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(conv4, kernel, [1, 1, 1, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[256]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv5 = tf.nn.relu(bias, name=scope)
pass # 最大池化层
pool5 = tf.nn.max_pool(conv5, ksize=[1,3,3,1], strides=[1,2,2,1], padding="VALID", name="pool5") # 全连接层
flatten = tf.reshape(pool5, [-1, 6*6*256]) weight1 = tf.Variable(tf.truncated_normal([6*6*256, 4096], mean=0, stddev=0.01)) fc1 = tf.nn.sigmoid(tf.matmul(flatten, weight1)) dropout1 = tf.nn.dropout(fc1, keepprob) weight2 = tf.Variable(tf.truncated_normal([4096, 4096], mean=0, stddev=0.01)) fc2 = tf.nn.sigmoid(tf.matmul(dropout1, weight2)) dropout2 = tf.nn.dropout(fc2, keepprob) weight3 = tf.Variable(tf.truncated_normal([4096, 10], mean=0, stddev=0.01)) fc3 = tf.nn.sigmoid(tf.matmul(dropout2, weight3)) return fc3 def alexnet_main():
# 加载使用的训练集文件名和标签。
files = np.load("label.npy", allow_pickle=True , encoding='bytes')[()] # 提取文件名。
keys = [i for i in files] print(len(keys)) myinput = tf.placeholder(dtype=tf.float32, shape=[None, 224, 224, 3], name='input')
mylabel = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='label') # 建立网络,keepprob为0.6。
myoutput = alexnet(myinput, 0.6) # 定义训练的loss函数。
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=myoutput, labels=mylabel)) # 定义优化器,学习率设置为0.09,学习率可以设置为其他的数值。
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.09).minimize(loss) # 定义准确率
valaccuracy = tf.reduce_mean(
tf.cast(
tf.equal(
tf.argmax(myoutput, 1),
tf.argmax(mylabel, 1)),
tf.float32)) # tensorflow的saver,可以用于保存模型。
saver = tf.train.Saver()
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# 40个epoch
for loop in range(40): # 生成并打乱训练集的顺序。
indices = np.arange(50000)
random.shuffle(indices) # batch size此处定义为200。
# 训练集一共50000张图片,前40000张用于训练,后10000张用于验证集。
for i in range(0, 0+40000, 200):
photo = []
label = []
for j in range(0, 200):
# print(keys[indices[i + j]])
photo.append(cv2.resize(cv2.imread(keys[indices[i + j]]), (224, 224))/225)
label.append(files[keys[indices[i + j]]])
m = getOneHotLabel(label, depth=10)
a, b = sess.run([optimizer, loss], feed_dict={myinput: photo, mylabel: m})
print("\r%lf"%b, end='') acc = 0
# 每次取验证集的200张图片进行验证,返回这200张图片的正确率。
for i in range(40000, 40000+10000, 200):
photo = []
label = []
for j in range(i, i + 200):
photo.append(cv2.resize(cv2.imread(keys[indices[j]]), (224, 224))/225)
label.append(files[keys[indices[j]]])
m = getOneHotLabel(label, depth=10)
acc += sess.run(valaccuracy, feed_dict={myinput: photo, mylabel: m})
# 输出,一共有50次验证集数据相加,所以需要除以50。
print("Epoch ", loop, ': validation rate: ', acc/50)
# 保存模型。
saver.save(sess, "model/model.ckpt") if __name__ == '__main__':
alexnet_main()
测试:
import tensorflow as tf
import numpy as np
import random
import cv2 def getOneHotLabel(label, depth):
m = np.zeros([len(label), depth])
for i in range(len(label)):
m[i][label[i]] = 1
return m # 建立神经网络
def alexnet(image, keepprob=0.5): # 定义卷积层1,卷积核大小,偏置量等各项参数参考下面的程序代码,下同
with tf.name_scope("conv1") as scope:
kernel = tf.Variable(tf.truncated_normal([11, 11, 3, 64], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(image, kernel, [1, 4, 4, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[64]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv1 = tf.nn.relu(bias, name=scope) pass # LRN层
lrn1 = tf.nn.lrn(conv1, 4, bias=1.0, alpha=0.001/9, beta=0.75, name="lrn1") # 最大池化层
pool1 = tf.nn.max_pool(lrn1, ksize=[1,3,3,1], strides=[1,2,2,1],padding="VALID", name="pool1") # 定义卷积层2
with tf.name_scope("conv2") as scope:
kernel = tf.Variable(tf.truncated_normal([5,5,64,192], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(pool1, kernel, [1, 1, 1, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[192]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv2 = tf.nn.relu(bias, name=scope)
pass # LRN层
lrn2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9, beta=0.75, name="lrn2") # 最大池化层
pool2 = tf.nn.max_pool(lrn2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding="VALID", name="pool2") # 定义卷积层3
with tf.name_scope("conv3") as scope:
kernel = tf.Variable(tf.truncated_normal([3,3,192,384], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(pool2, kernel, [1, 1, 1, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[384]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv3 = tf.nn.relu(bias, name=scope)
pass # 定义卷积层4
with tf.name_scope("conv4") as scope:
kernel = tf.Variable(tf.truncated_normal([3,3,384,256], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(conv3, kernel, [1, 1, 1, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[256]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv4 = tf.nn.relu(bias, name=scope)
pass # 定义卷积层5
with tf.name_scope("conv5") as scope:
kernel = tf.Variable(tf.truncated_normal([3,3,256,256], dtype=tf.float32, stddev=1e-1, name="weights"))
conv = tf.nn.conv2d(conv4, kernel, [1, 1, 1, 1], padding="SAME")
biases = tf.Variable(tf.constant(0.0, dtype=tf.float32, shape=[256]), trainable=True, name="biases")
bias = tf.nn.bias_add(conv, biases)
conv5 = tf.nn.relu(bias, name=scope)
pass # 最大池化层
pool5 = tf.nn.max_pool(conv5, ksize=[1,3,3,1], strides=[1,2,2,1], padding="VALID", name="pool5") # 全连接层
flatten = tf.reshape(pool5, [-1, 6*6*256]) weight1 = tf.Variable(tf.truncated_normal([6*6*256, 4096], mean=0, stddev=0.01)) fc1 = tf.nn.sigmoid(tf.matmul(flatten, weight1)) dropout1 = tf.nn.dropout(fc1, keepprob) weight2 = tf.Variable(tf.truncated_normal([4096, 4096], mean=0, stddev=0.01)) fc2 = tf.nn.sigmoid(tf.matmul(dropout1, weight2)) dropout2 = tf.nn.dropout(fc2, keepprob) weight3 = tf.Variable(tf.truncated_normal([4096, 10], mean=0, stddev=0.01)) fc3 = tf.nn.sigmoid(tf.matmul(dropout2, weight3)) return fc3 def alexnet_main():
# 加载测试集的文件名和标签。
files = np.load("test-label.npy", encoding='bytes')[()]
keys = [i for i in files]
print(len(keys)) myinput = tf.placeholder(dtype=tf.float32, shape=[None, 224, 224, 3], name='input')
mylabel = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='label')
myoutput = alexnet(myinput, 0.6) prediction = tf.argmax(myoutput, 1)
truth = tf.argmax(mylabel, 1)
valaccuracy = tf.reduce_mean(
tf.cast(
tf.equal(
prediction,
truth),
tf.float32)) saver = tf.train.Saver() with tf.Session() as sess:
# 加载训练好的模型,路径根据自己的实际情况调整
saver.restore(sess, r"model/model.ckpt") cnt = 0
for i in range(10000):
photo = []
label = [] photo.append(cv2.resize(cv2.imread(keys[i]), (224, 224))/225)
label.append(files[keys[i]])
m = getOneHotLabel(label, depth=10)
a, b= sess.run([prediction, truth], feed_dict={myinput: photo, mylabel: m})
print(a, ' ', b)
if a[0] == b[0]:
cnt += 1 print("Epoch ", 1, ': prediction rate: ', cnt / 10000) if __name__ == '__main__':
alexnet_main()
TensorFlow笔记六:基于cifar10数据库的AlexNet识别的更多相关文章
- EF Core使用笔记(基于MySql数据库)
一.什么是EF Entity Framework 是适用于.NET 的对象关系映射程序 (O/RM). 二.比较 EF Core 和 EF6 1.Entity Framework 6 Entity F ...
- java之jvm学习笔记六-十二(实践写自己的安全管理器)(jar包的代码认证和签名) (实践对jar包的代码签名) (策略文件)(策略和保护域) (访问控制器) (访问控制器的栈校验机制) (jvm基本结构)
java之jvm学习笔记六(实践写自己的安全管理器) 安全管理器SecurityManager里设计的内容实在是非常的庞大,它的核心方法就是checkPerssiom这个方法里又调用 AccessCo ...
- tensorflow笔记:使用tf来实现word2vec
(一) tensorflow笔记:流程,概念和简单代码注释 (二) tensorflow笔记:多层CNN代码分析 (三) tensorflow笔记:多层LSTM代码分析 (四) tensorflow笔 ...
- tensorflow笔记(一)之基础知识
tensorflow笔记(一)之基础知识 版权声明:本文为博主原创文章,转载请指明转载地址 http://www.cnblogs.com/fydeblog/p/7399701.html 前言 这篇no ...
- Python学习笔记六
Python课堂笔记六 常用模块已经可以在单位实际项目中使用,可以实现运维自动化.无需手工备份文件,数据库,拷贝,压缩. 常用模块 time模块 time.time time.localtime ti ...
- tensorflow笔记:多层LSTM代码分析
tensorflow笔记:多层LSTM代码分析 标签(空格分隔): tensorflow笔记 tensorflow笔记系列: (一) tensorflow笔记:流程,概念和简单代码注释 (二) ten ...
- TensorFlow笔记-08-过拟合,正则化,matplotlib 区分红蓝点
TensorFlow笔记-08-过拟合,正则化,matplotlib 区分红蓝点 首先提醒一下,第7讲的最后滑动平均的代码已经更新了,代码要比理论重要 今天是过拟合,和正则化,本篇后面可能或更有兴趣, ...
- TensorFlow笔记-06-神经网络优化-损失函数,自定义损失函数,交叉熵
TensorFlow笔记-06-神经网络优化-损失函数,自定义损失函数,交叉熵 神经元模型:用数学公式比表示为:f(Σi xi*wi + b), f为激活函数 神经网络 是以神经元为基本单位构成的 激 ...
- TensorFlow笔记-05-反向传播,搭建神经网络的八股
TensorFlow笔记-05-反向传播,搭建神经网络的八股 反向传播 反向传播: 训练模型参数,在所有参数上用梯度下降,使用神经网络模型在训练数据上的损失函数最小 损失函数:(loss) 计算得到的 ...
随机推荐
- dijkstra 堆优化
#include <iostream> #include <vector> #include <cstring> #include <queue> us ...
- hnust CZJ-Superman
问题 B: CZJ-Superman 时间限制: 1 Sec 内存限制: 128 MB提交: 636 解决: 87[提交][状态][讨论版] 题目描述 “那是只鸟?那是飞机?那是——超人!” 程序 ...
- [转载]用等高线图(Contour maps)可视化多变量函数
https://blog.csdn.net/xlinsist/article/details/50920479 Overview 由于我们用手来画三维图像很困难,我们可以用等高线图来描述图像会更加简单 ...
- JavaWeb笔记(二)Servlet
Tomcat目录简介 bin--可执行文件 conf--配置文件 lib--依赖jar包 logs--日志文件 temp--临时文件 webapps--默认项目部署路径 work--存放运行时的数据 ...
- CI在nginx环境下去掉url中的index.php
在nginx环境下CI框架默认URL规则访问不了,出现500错误,如: http://blog.php230.com/index.php/keywords 今天在服务器配置CI框架环境时,去除URL中 ...
- Android jni 编程入门
本文将介绍如何使用eclipse和ndk-build来编写一个基于Android4.4版本的包含有.so动态库的安卓程序. 前提是已经安装和配置好了诸如SDK,NDK等编译环境.下面开始编程! 1 程 ...
- Java EE 学习(5):IDEA + maven + spring 搭建 web(1)
参考:http://www.cnblogs.com/lonelyxmas/p/5397422.html http://www.ctolib.com/docs-IntelliJ-IDEA-c--1590 ...
- 【16】vuex2.0 之 getter
有的组件中获取到 store 中的state, 需要对进行加工才能使用,computed 属性中就需要写操作函数,如果有多个组件中都需要进行这个操作,那么在各个组件中都写相同的函数,那就非常麻烦,这 ...
- Cannot map 'XXXController.Create' bean method
[转 :http://www.fanfanyu.cn/news/staticpagefile/2351.html] 最近在开发项目的过程中SpringMVC抛了个"Ambiguous map ...
- 利用GridView控件导出其他文件(导出Excel,导出Word文件)
原文发布时间为:2008-10-16 -- 来源于本人的百度文章 [由搬家工具导入] // 注意,在Visual Studio2005平台下,如果使用GridView导出文件, //就必须重 ...