# -*- 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. <NET CLR via c# 第4版>笔记 第19章 可空值类型

    System.Nullable<T> 是结构. 19.1 C# 对可空值类型的支持 C# 允许用问号表示法来声明可空值类型,如: Int32? x = 5; Int32? y = null ...

  2. jQuery实现按Esc清除信息功能

    1.jQuery实现按Esc清除信息功能 function clearLogs(){    $(".logs").empty(); }   $(document).ready(fu ...

  3. anu - controlledComponent

    /** input, select, textarea这几个元素如果指定了value/checked的**状态属性**,就会包装成受控组件或非受控组件 受控组件是指,用户除了为它指定**状态属性**, ...

  4. require('nw.gui') 失效问题

    // gui = global.window.nwDispatcher.requireNwGui() --original // gui = window.require('nw.gui') gui ...

  5. Iterator、Iteratable与ListIterator

    Iteratable: public interface Iterable<T> { Iterator<T> iterator(); default void forEach( ...

  6. sparksql与hive整合

    参考文献: http://blog.csdn.net/stark_summer/article/details/48443147 hive配置 编辑 $HIVE_HOME/conf/Hive-site ...

  7. SYSTEM\sys\sys.c:33:7: error: expected '(' before 'void' __ASM void MSR_MSP(u32 addr)

    在STM32中的sys.c文件编译报出这个错误时: __ASM void MSR_MSP(u32 addr){ MSR MSP, r0 //set Main Stack value BX r14} 如 ...

  8. CF1096.F. Inversion Expectation(树状数组)

    A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once ...

  9. jboss 5.1 启动问题解决

    在安装好后启动时可能遇到这样的情况: ERROR [AbstractKernelController] Error installing to Instantiated: name=Attachmen ...

  10. 【洛谷P1338】末日的传说

    https://www.luogu.org/problemnew/show/P1338 [题目大意:从1到n的连续自然数,求其逆序对数为m的一个字母序最小的排列.] 最开始的思路是想从逆序对数入手,然 ...