import keras
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense,Activation,Flatten,Dropout,Convolution2D,MaxPooling2D
from keras.utils import np_utils
from keras.optimizers import RMSprop
from skimage import io

nb_classes=10
batch_size=128
####因为是卷积神经网络,输入数据的格式是图像格式,所以要进行reshape
train_X = io.imread("E:\\WaySign\\0_0_colorrgb0.ppm")
train_x=np.reshape(train_X,(train_X.shape[0],32,32,1))
# test_x=np.reshape(test_X,(test_X.shape[0],28,28,1))
# train_y=np_utils.to_categorical(train_Y,nb_classes)
# test_y=np_utils.to_categorical(test_Y,nb_classes)

print(train_y.shape,'\n',test_y.shape)

print(train_x.shape,'\n',test_x.shape)

train_x[:,:,:,0].shape

###reshape后的数据显示
import matplotlib.pyplot as plt
%matplotlib inline
f,a=plt.subplots(1,10,figsize=(10,5))
for i in range(10):
a[i].imshow(train_x[i,:,:,0],cmap='gray')
print(train_Y[i])

####establish a convolution nerual network
model=Sequential()

####Convolution layer 1
model.add(Convolution2D(filters=32,kernel_size=(3,3),input_shape=(28,28,1),strides=(1,1),\
padding='same',activation='relu'))

#####pooling layer with dropout
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))
model.add(Dropout(0.2))

####Convolution layer 2
model.add(Convolution2D(filters=64,kernel_size=(3,3),strides=(1,1),padding='same',\
activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))
model.add(Dropout(0.2))

####Convolution layer 3
model.add(Convolution2D(filters=128,kernel_size=(3,3),strides=(1,1),padding='same',\
activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))
model.add(Flatten())###理解扁平化
model.add(Dropout(0.2))

#model.add(Flatten())?

####fully connected layer 1 (fc layer)
model.add(Dense(output_dim=625,activation='relu'))
model.add(Dropout(0.5))

####fully connected layer 2 (fc layer)
model.add(Dense(output_dim=10,activation='softmax'))
model.summary()

model.compile(optimizer=RMSprop(lr=0.001,rho=0.9),loss="categorical_crossentropy",\
metrics=['accuracy'])
import time
start_time=time.time()
model.fit(train_x,train_y,epochs=30,batch_size=128,verbose=1)
end_time=time.time()
print("running time:%.2f"%(end_time-start_time))

evaluation=model.evaluate(test_x,test_y,batch_size=128,verbose=1)
print("model loss:%.4f"%(evaluation[0]),"model accuracy:%.4f"%(evaluation[1]))

# https://github.com/fchollet/keras/issues/431
def get_activations(model, model_inputs, print_shape_only=True, layer_name=None):
import keras.backend as K
print('----- activations -----')
activations = []
inp = model.input

model_multi_inputs_cond = True
if not isinstance(inp, list):
# only one input! let's wrap it in a list.
inp = [inp]
model_multi_inputs_cond = False

outputs = [layer.output for layer in model.layers if
layer.name == layer_name or layer_name is None] # all layer outputs

funcs = [K.function(inp + [K.learning_phase()], [out]) for out in outputs] # evaluation functions

if model_multi_inputs_cond:
list_inputs = []
list_inputs.extend(model_inputs)
list_inputs.append(1.)
else:
list_inputs = [model_inputs, 1.]

# Learning phase. 1 = Test mode (no dropout or batch normalization)
# layer_outputs = [func([model_inputs, 1.])[0] for func in funcs]
layer_outputs = [func(list_inputs)[0] for func in funcs]
for layer_activations in layer_outputs:
activations.append(layer_activations)
if print_shape_only:
print(layer_activations.shape)
else:
print(layer_activations)
return activations

# https://github.com/philipperemy/keras-visualize-activations/blob/master/read_activations.py
def display_activations(activation_maps):
import numpy as np
import matplotlib.pyplot as plt
"""
(1, 28, 28, 32)
(1, 14, 14, 32)
(1, 14, 14, 32)
(1, 14, 14, 64)
(1, 7, 7, 64)
(1, 7, 7, 64)
(1, 7, 7, 128)
(1, 3, 3, 128)
(1, 1152)
(1, 1152)
(1, 625)
(1, 625)
(1, 10)
"""
batch_size = activation_maps[0].shape[0]
assert batch_size == 1, 'One image at a time to visualize.'
for i, activation_map in enumerate(activation_maps):
print('Displaying activation map {}'.format(i))
shape = activation_map.shape
if len(shape) == 4:
activations = np.hstack(np.transpose(activation_map[0], (2, 0, 1)))
elif len(shape) == 2:
# try to make it square as much as possible. we can skip some activations.
activations = activation_map[0]
num_activations = len(activations)
if num_activations > 1024: # too hard to display it on the screen.
square_param = int(np.floor(np.sqrt(num_activations)))
activations = activations[0: square_param * square_param]
activations = np.reshape(activations, (square_param, square_param))
else:
activations = np.expand_dims(activations, axis=0)
else:
raise Exception('len(shape) = 3 has not been implemented.')
#plt.imshow(activations, interpolation='None', cmap='binary')
fig, ax = plt.subplots(figsize=(18, 12))
ax.imshow(activations, interpolation='None', cmap='binary')
plt.show()

###One image at a time to visualize.
activations = get_activations(model, (test_x[0,:,:,:])[np.newaxis,:])

(test_x[0,:,:,:])[np.newaxis,:].shape

display_activations(activations)

plt.imshow(test_x[0,:,:,0],cmap='gray')
pred_value=model.predict_classes((test_x[0,:,:,:])[np.newaxis,:],batch_size=1)
print(pred_value)

吴裕雄 python神经网络 手写数字图片识别(5)的更多相关文章

  1. 吴裕雄 python 神经网络——TensorFlow 卷积神经网络手写数字图片识别

    import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_N ...

  2. 用Keras搭建神经网络 简单模版(三)—— CNN 卷积神经网络(手写数字图片识别)

    # -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) #for reproducibility再现性 from keras.d ...

  3. 深度学习(一):Python神经网络——手写数字识别

    声明:本文章为阅读书籍<Python神经网络编程>而来,代码与书中略有差异,书籍封面: 源码 若要本地运行,请更改源码中图片与数据集的位置,环境为 Python3.6x. 1 import ...

  4. 用Keras搭建神经网络 简单模版(四)—— RNN Classifier 循环神经网络(手写数字图片识别)

    # -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) from keras.datasets import mnist fro ...

  5. caffe+opencv3.3dnn模块 完成手写数字图片识别

    最近由于项目需要用到caffe,学习了下caffe的用法,在使用过程中也是遇到了些问题,通过上网搜索和问老师的方法解决了,在此记录下过程,方便以后查看,也希望能为和我一样的新手们提供帮助. 顺带附上老 ...

  6. 基于Numpy的神经网络+手写数字识别

    基于Numpy的神经网络+手写数字识别 本文代码来自Tariq Rashid所著<Python神经网络编程> 代码分为三个部分,框架如下所示: # neural network class ...

  7. TensorFlow 卷积神经网络手写数字识别数据集介绍

    欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 手写数字识别 接下来将会以 MNIST 数据集为例,使用卷积层和池 ...

  8. 一文全解:利用谷歌深度学习框架Tensorflow识别手写数字图片(初学者篇)

    笔记整理者:王小草 笔记整理时间2017年2月24日 原文地址 http://blog.csdn.net/sinat_33761963/article/details/56837466?fps=1&a ...

  9. Tensorflow学习教程------模型参数和网络结构保存且载入,输入一张手写数字图片判断是几

    首先是模型参数和网络结构的保存 #coding:utf-8 import tensorflow as tf from tensorflow.examples.tutorials.mnist impor ...

随机推荐

  1. visual studio 2017调试时闪退。

    解决方案: 在工程上右键--->属性--->配置属性--->连接器--->系统--->子系统(在窗口右边)--->下拉框选择控制台(/SUBSYSTEM:CONSO ...

  2. Android:真机调试遇到的问题(INSTALL_FAILED_CANCELLED_BY_USER和INSTALL_FAILED_INSUFFICIENT_STORAGE)

    Android:真机调试遇到的问题(INSTALL_FAILED_CANCELLED_BY_USER和INSTALL_FAILED_INSUFFICIENT_STORAGE) 刚开始做Android开 ...

  3. HBase的Shell命令和JavaAPI

    HBase的shell操作和JavaAPI的使用: Shell 表操作 创建表 create 'student','info' #表名 列族 插入表 put 'student','1001','inf ...

  4. Linux性能优化 第三章 性能工具:系统内存

    3.1内存性能统计信息 3.1.1 内存子系统和性能 和CPU相比,内存的读写速度都大大落后于CPU.为了弥补这个差距,通常CPU会采用高速缓存的机制(高cache). 3.1.2 内存子系统(虚拟存 ...

  5. jQuery对象的操作

    参考一篇不错的文章:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object 1. ...

  6. crawlspider 多分页处理

    提问:如果想要通过爬虫程序去爬取”糗百“全站数据新闻数据的话,有几种实现方法? 方法一:基于Scrapy框架中的Spider的递归爬取进行实现(Request模块递归回调parse方法). 方法二:基 ...

  7. 安全测试1_Web知识简介

    接下去所有的安全测试都是本人学习安全测试的过程,随笔中会截取云课堂视频中的图片(比较生动和形象,便于理解),主要目的是方便自己以后复习和巩固! 1.Web发展阶段概述: 2.web安全我能提发展形势: ...

  8. SVG 学习<三>渐变

    目录 SVG 学习<一>基础图形及线段 SVG 学习<二>进阶 SVG世界,视野,视窗 stroke属性 svg分组 SVG 学习<三>渐变 SVG 学习<四 ...

  9. gentoo samba 密码错误

    参考 Samba Share Password Refused https://social.technet.microsoft.com/Forums/windows/en-US/8249ad4c-6 ...

  10. pyqt 8行内就可以跑一个浏览器

    pyqt 8行内就可以跑一个浏览器 from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * ...