用Keras搭建神经网络 简单模版(二)——Classifier分类(手写数字识别)
# -*- 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分类(手写数字识别)的更多相关文章
- 机器学习(二)-kNN手写数字识别
一.kNN算法是机器学习的入门算法,其中不涉及训练,主要思想是计算待测点和参照点的距离,选取距离较近的参照点的类别作为待测点的的类别. 1,距离可以是欧式距离,夹角余弦距离等等. 2,k值不能选择太大 ...
- 用Keras搭建神经网络 简单模版(三)—— CNN 卷积神经网络(手写数字图片识别)
# -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) #for reproducibility再现性 from keras.d ...
- 用Keras搭建神经网络 简单模版(六)——Autoencoder 自编码
import numpy as np np.random.seed(1337) from keras.datasets import mnist from keras.models import Mo ...
- 用Keras搭建神经网络 简单模版(四)—— RNN Classifier 循环神经网络(手写数字图片识别)
# -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) from keras.datasets import mnist fro ...
- 用Keras搭建神经网络 简单模版(一)——Regressor 回归
首先需要下载Keras,可以看到我用的是TensorFlow 的backend 自己构建虚拟数据,x是-1到1之间的数,y为0.5*x+2,可视化出来 # -*- coding: utf-8 -*- ...
- 用Keras搭建神经网络 简单模版(五)——RNN LSTM Regressor 循环神经网络
# -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) import matplotlib.pyplot as plt from ...
- 吴裕雄 python 神经网络TensorFlow实现LeNet模型处理手写数字识别MNIST数据集
import tensorflow as tf tf.reset_default_graph() # 配置神经网络的参数 INPUT_NODE = 784 OUTPUT_NODE = 10 IMAGE ...
- 吴裕雄 python 神经网络——TensorFlow实现AlexNet模型处理手写数字识别MNIST数据集
import tensorflow as tf # 输入数据 from tensorflow.examples.tutorials.mnist import input_data mnist = in ...
- 【问题解决方案】Keras手写数字识别-ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接
参考:台大李宏毅老师视频课程-Keras-Demo 在载入数据阶段报错: ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接 Google之 ...
随机推荐
- 微信分享自定义标题和图片的js
<script> document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() { window.sh ...
- re 正则
如果直接给出字符,就是精确匹配.对于特殊字符- ,在正则表达式中要用转义字符\转义. \d 一个数字, \w 任意单个字符,空白符除外(例 字母.数字或下划线 . 英 ...
- 判断当前应用程序处于前台还是后台 ANDROID
/** *判断当前应用程序处于前台还是后台 * * @param context * @return */ public static boolean ...
- 踢掉某个li
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- L241
Parents, try to get enough sleep to role model good habits to children. Bessesen notes that some med ...
- IP addresses in C#
在.Net网络库里面最大的优点就是IP地址和端口被成对处理,相比于UNIX中用的方法真是一个巨大的令人欢迎的进步..NET定义了两个类来处理关于IP地址的问题. One of the biggest ...
- react 学习日记
1.本地配置代理服务: create-react-app 创建的react项目 package.jsoin 中 加入: "proxy": "http://localh ...
- tomcat版本号的修改
我的是8.5.0我将其改为8.0.0 其他版本改也是一样 我改这个版本号就是因为eclipse上没有tomcat8.5.0的配置 所以将其改为8.0.0 在配置web服务器时 ...
- I.MX6 make menuconfig OTG to slave only mode
/****************************************************************************** * I.MX6 make menucon ...
- 【opencv基础】detectMultiScale-output detection score
前言 使用FDDB数据库评估人脸检测的效果时,需要计算人脸区域的得分,具体问题请参考FDDB-FAQ. 实现过程 根据here和here的描述,可以使用cascade.detectMultiScale ...