# -*- coding: utf-8 -*-
import numpy as np
np.random.seed(1337) #for reproducibility再现性
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential#按层
from keras.layers import Dense, Activation#全连接层
import matplotlib.pyplot as plt
from keras.optimizers import RMSprop

从mnist下载手写数字图片数据集,图片为28*28,将每个像素的颜色(0到255)改为(0倒1),将标签y变为10个长度,若为1,则在1处为1,剩下的都标为0。

#dowmload the mnisst the path '~/.keras/datasets/' if it is the first time to be called
#x shape (60000 28*28),y shape(10000,)
(x_train,y_train),(x_test,y_test) = mnist.load_data()#0-9的图片数据集 #data pre-processing
x_train = x_train.reshape(x_train.shape[0],-1)/255 #normalize 到【0,1】
x_test = x_test.reshape(x_test.shape[0],-1)/255
y_train = np_utils.to_categorical(y_train, num_classes=10) #把标签变为10个长度,若为1,则在1处为1,剩下的都标为0
y_test = np_utils.to_categorical(y_test,num_classes=10)

 

搭建神经网络,Activation为激活函数。由于第一个Dense传出32.所以第二个的Dense默认传进32,不用特意设置。

#Another way to build neural net
model = Sequential([
Dense(32,input_dim=784),#传出32
Activation('relu'),
Dense(10),
Activation('softmax')
]) #Another way to define optimizer
rmsprop = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0) # We add metrics to get more results you want to see
model.compile( #编译
optimizer = rmsprop,
loss = 'categorical_crossentropy',
metrics=['accuracy'], #在更新时同时计算一下accuracy
)

 

训练和测试

print("Training~~~~~~~~")
#Another way to train the model
model.fit(x_train,y_train, epochs=2, batch_size=32) #训练2大批,每批32个 print("\nTesting~~~~~~~~~~")
#Evalute the model with the metrics we define earlier
loss,accuracy = model.evaluate(x_test,y_test) print('test loss:',loss)
print('test accuracy:', accuracy)

 

全代码:

# -*- coding: utf-8 -*-
import numpy as np
np.random.seed(1337) #for reproducibility再现性
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential#按层
from keras.layers import Dense, Activation#全连接层
import matplotlib.pyplot as plt
from keras.optimizers import RMSprop #dowmload the mnisst the path '~/.keras/datasets/' if it is the first time to be called
#x shape (60000 28*28),y shape(10000,)
(x_train,y_train),(x_test,y_test) = mnist.load_data()#0-9的图片数据集 #data pre-processing
x_train = x_train.reshape(x_train.shape[0],-1)/255 #normalize 到【0,1】
x_test = x_test.reshape(x_test.shape[0],-1)/255
y_train = np_utils.to_categorical(y_train, num_classes=10) #把标签变为10个长度,若为1,则在1处为1,剩下的都标为0
y_test = np_utils.to_categorical(y_test,num_classes=10) #Another way to build neural net
model = Sequential([
Dense(32,input_dim=784),#传出32
Activation('relu'),
Dense(10),
Activation('softmax')
]) #Another way to define optimizer
rmsprop = RMSprop(lr=0.001,rho=0.9,epsilon=1e-08,decay=0.0) # We add metrics to get more results you want to see
model.compile( #编译
optimizer = rmsprop,
loss = 'categorical_crossentropy',
metrics=['accuracy'], #在更新时同时计算一下accuracy
) print("Training~~~~~~~~")
#Another way to train the model
model.fit(x_train,y_train, epochs=2, batch_size=32) #训练2大批,每批32个 print("\nTesting~~~~~~~~~~")
#Evalute the model with the metrics we define earlier
loss,accuracy = model.evaluate(x_test,y_test) print('test loss:',loss)
print('test accuracy:', accuracy)

结果为:

 

用Keras搭建神经网络 简单模版(二)——Classifier分类(手写数字识别)的更多相关文章

  1. 机器学习(二)-kNN手写数字识别

    一.kNN算法是机器学习的入门算法,其中不涉及训练,主要思想是计算待测点和参照点的距离,选取距离较近的参照点的类别作为待测点的的类别. 1,距离可以是欧式距离,夹角余弦距离等等. 2,k值不能选择太大 ...

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

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

  3. 用Keras搭建神经网络 简单模版(六)——Autoencoder 自编码

    import numpy as np np.random.seed(1337) from keras.datasets import mnist from keras.models import Mo ...

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

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

  5. 用Keras搭建神经网络 简单模版(一)——Regressor 回归

    首先需要下载Keras,可以看到我用的是TensorFlow 的backend 自己构建虚拟数据,x是-1到1之间的数,y为0.5*x+2,可视化出来 # -*- coding: utf-8 -*- ...

  6. 用Keras搭建神经网络 简单模版(五)——RNN LSTM Regressor 循环神经网络

    # -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) import matplotlib.pyplot as plt from ...

  7. 吴裕雄 python 神经网络TensorFlow实现LeNet模型处理手写数字识别MNIST数据集

    import tensorflow as tf tf.reset_default_graph() # 配置神经网络的参数 INPUT_NODE = 784 OUTPUT_NODE = 10 IMAGE ...

  8. 吴裕雄 python 神经网络——TensorFlow实现AlexNet模型处理手写数字识别MNIST数据集

    import tensorflow as tf # 输入数据 from tensorflow.examples.tutorials.mnist import input_data mnist = in ...

  9. 【问题解决方案】Keras手写数字识别-ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接

    参考:台大李宏毅老师视频课程-Keras-Demo 在载入数据阶段报错: ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接 Google之 ...

随机推荐

  1. 做了一个vue的同步tree 的npm组件包

    前言:因为现成的tree组件没有找到.亦或是其依赖的其他东西太多,不太合适引入我们的项目,所以自己做了一个.大概样式: 在线例子: https://hamupp.github.io/t-vue-tre ...

  2. C++设计模式之解释器模式

    2013年07月06日 19:43:00 阅读数:8853 概述: 未来机器智能化已然成为趋势,现在手机都能听懂英语和普通话,那我大中华几万种方言的被智能化也许也是趋势,我们的方言虽然和普通话相似,但 ...

  3. 玩转X-CTR100 | STM32F4 l GPIO位带操作

    更多塔克创新资讯欢迎登陆[塔克社区 www.xtark.cn ][塔克博客 www.cnblogs.com/xtark/ ]       STM32F4位带概念,及位带的GPIO操作实践应用. 原理介 ...

  4. DevExpress v17.2—WinForms篇(六)

    用户界面套包DevExpress v17.2终于正式发布,本站将以连载的形式为大家介绍各版本新增内容.开篇介绍了DevExpress WinForms v17.2 Data Grid Control ...

  5. How to understand three foundanmental faults?

    1.First ,try to understand "Green function and the moment tensor" in Seismology,9.1 2.seco ...

  6. dubbo集群应用

    前面写了一篇dubbo的基础应用篇,单机版 http://www.cnblogs.com/yun965861480/p/6257670.html, 这次将集群的相关配置记录下来. 1.zookeepe ...

  7. (转)git合并多个commit

    原文地址:http://platinhom.github.io/2016/01/02/git-combine_commit/ 有时commit多了看着会不爽.所以想合并掉一些commit. 这里是最简 ...

  8. js之表单记忆功能

    在项目中,我们难免会遇到希望相同用户操作本次打开页面时可以展现或者自动记录上次登录系统点击过的的复选框,单选按钮等操作的状态,也就是表单记忆功能,这时,一个很重要的技术便派上了用场,即cookie. ...

  9. eclipse集成svn后总是弹出 Password Required问题解决方法

    最近在集成svn后,在打开eclipse后总是一遍遍的弹出 Password Required,即使输入正确的用户名以及密码也会弹出,最后发现是eclipse的Network  Connections ...

  10. Apache2.4配置总结(转)

    文章内容转自- ->https://blog.csdn.net/u012291157/article/details/46492137 1.apache开机自启动 [root@csr ~]# c ...