# 1. 数据预处理

import keras

from keras import backend as K
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D num_classes = 10
img_rows, img_cols = 28, 28 # 通过Keras封装好的API加载MNIST数据。其中trainX就是一个60000 * 28 * 28的数组,
# trainY是每一张图片对应的数字。
(trainX, trainY), (testX, testY) = mnist.load_data() # 根据对图像编码的格式要求来设置输入层的格式。
if K.image_data_format() == 'channels_first':
trainX = trainX.reshape(trainX.shape[0], 1, img_rows, img_cols)
testX = testX.reshape(testX.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
trainX = trainX.reshape(trainX.shape[0], img_rows, img_cols, 1)
testX = testX.reshape(testX.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1) trainX = trainX.astype('float32')
testX = testX.astype('float32')
trainX /= 255.0
testX /= 255.0 # 将标准答案转化为需要的格式(one-hot编码)。
trainY = keras.utils.to_categorical(trainY, num_classes)
testY = keras.utils.to_categorical(testY, num_classes)

# 2. 通过Keras的API定义卷机神经网络。
# 使用Keras API定义模型。
model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dense(num_classes, activation='softmax')) # 定义损失函数、优化函数和评测方法。
model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.SGD(),metrics=['accuracy'])
# 3. 通过Keras的API训练模型并计算在测试数据上的准确率。
model.fit(trainX, trainY,batch_size=128,epochs=10,validation_data=(testX, testY)) # 在测试数据上计算准确率。
score = model.evaluate(testX, testY)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

吴裕雄--天生自然TensorFlow高层封装:Keras-CNN的更多相关文章

  1. 吴裕雄--天生自然TensorFlow高层封装:Keras-TensorFlow API

    # 1. 模型定义. import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist_ ...

  2. 吴裕雄--天生自然TensorFlow高层封装:Keras-多输入输出

    # 1. 数据预处理. import keras from keras.models import Model from keras.datasets import mnist from keras. ...

  3. 吴裕雄--天生自然TensorFlow高层封装:Keras-返回值

    # 1. 数据预处理. import keras from keras.models import Model from keras.datasets import mnist from keras. ...

  4. 吴裕雄--天生自然TensorFlow高层封装:Estimator-自定义模型

    # 1. 自定义模型并训练. import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist i ...

  5. 吴裕雄--天生自然TensorFlow高层封装:Estimator-DNNClassifier

    # 1. 模型定义. import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist impor ...

  6. 吴裕雄--天生自然TensorFlow高层封装:Keras-RNN

    # 1. 数据预处理. from keras.layers import LSTM from keras.datasets import imdb from keras.models import S ...

  7. 吴裕雄--天生自然TensorFlow高层封装:解决ImportError: cannot import name 'tf_utils'

    将原来版本的keras卸载了,再安装2.1.5版本的keras就可以了.

  8. 吴裕雄--天生自然TensorFlow高层封装:解决ValueError: Invalid backend. Missing required entry : placeholder

    找到对应的keras配置文件keras.json 将里面的内容修改为以下就可以了

  9. 吴裕雄--天生自然TensorFlow高层封装:使用TensorFlow-Slim处理MNIST数据集实现LeNet-5模型

    # 1. 通过TensorFlow-Slim定义卷机神经网络 import numpy as np import tensorflow as tf import tensorflow.contrib. ...

随机推荐

  1. 安卓app测试之Monkey日志分析《转载》

    安卓app测试之Monkey日志分析 链接:https://www.cnblogs.com/wuzm/p/10965762.html

  2. springboot入门学习1

    springboot学习1 SpringBoot对Spring的缺点进行的改善和优化,基于约定优于配置的思想,可以让开发人员不必在配置与逻辑 业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中 ...

  3. web.xml中filter加载顺序出现的问题

    刚刚遇到了一个问题,项目中需要用到characterEncodingFilter和HiddenHttpMethodFilter,但是post请求还是会中文乱码,找了半天原因,后来发现,filter加载 ...

  4. PAT Advanced 1151 LCA in a Binary Tree (30) [树的遍历,LCA算法]

    题目 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both ...

  5. POJ 1149:PIGS 网络流经典题

    PIGS Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 18345   Accepted: 8354 Description ...

  6. settings配置数据库和日志

    数据库的配置: 一.mysql配置 pip下载pymysql,用于mysql和django的连接. 在init.py上配置pymsqy. import pymysql pymysql.install_ ...

  7. Flux转Mono next()

    import java.util.LinkedHashMap; import java.util.Map; import java.util.NoSuchElementException; impor ...

  8. [Security] Web Security Essentials

    In this course, we'll learn how to exploit and then mitigate several common Web Security Vulnerabili ...

  9. RaspBerry--解决无法用 ssh 直接以 root 用户登录

    参考:https://www.cnblogs.com/xwdreamer/p/6604593.html 以普通用户登录,然后切换至 root 用户. 编辑 /etc/ssh/sshd_config 添 ...

  10. MySQL--SQL分类

    SQL语句主要可以划分为以下3个类别: DDL(Data Definition Languages)语句:数据定义语言,这些语句定义了不同的数据段.数据库.表.列.索引等数据库对象. 常用的语句关键字 ...