热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

keras怎么改变维度_基于keras的手写数字识别及cifar10CNN图像分类实验讲解

基于keras和mnist的手写数字识别(X_train,y_train),(X_test,y_test)mnist.load_data()print(X_trainshape:

基于keras和mnist的手写数字识别

395ded247f1ec66e8fb0af4a23258fef.png

(X_train, y_train), (X_test, y_test) = mnist.load_data()
print('X_train shape:', X_train.shape)
print('X_test shape: ', X_test.shape)
print('y_train shape:',y_train.shape)
print('y_test shape: ', y_test.shape)

全部代码:

# Import Numpy, keras and MNIST data
import numpy as np
import matplotlib.pyplot as pltfrom keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.utils import np_utils# Retrieve the training and test data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print('X_train shape:', X_train.shape)
print('X_test shape: ', X_test.shape)
print('y_train shape:',y_train.shape)
print('y_test shape: ', y_test.shape)# Visualizing the data
import matplotlib.pyplot as plt
%matplotlib inline# Function for displaying a training image by it's index in the MNIST set
def display_digit(index):label = y_train[index].argmax(axis=0)image = X_train[index]plt.title('Training data, index: %d, Label: %d' % (index, label))plt.imshow(image, cmap='gray_r')plt.show()# Display the first (index 0) training image
display_digit(0)X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print("Training matrix shape", X_train.shape)
print("Testing matrix shape", X_test.shape)#One Hot encoding of labels.
from keras.utils.np_utils import to_categorical
print(y_train.shape)
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
print(y_train.shape)# Define the neural network
def build_model():model = Sequential()model.add(Dense(512, input_shape=(784,)))model.add(Activation('relu')) # An "activation" is just a non-linear function applied to the output# of the layer above. Here, with a "rectified linear unit",# we clamp all values below 0 to 0.model.add(Dropout(0.2)) # Dropout helps protect the model from memorizing or "overfitting" the training datamodel.add(Dense(512))model.add(Activation('relu'))model.add(Dropout(0.2))model.add(Dense(10))model.add(Activation('softmax')) # This special "softmax" activation among other things,# ensures the output is a valid probaility distribution, that is# that its values are all non-negative and sum to 1.return model# Build the model
model = build_model()model.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])# Training
model.fit(X_train, y_train, batch_size=128, nb_epoch=4, verbose=1,validation_data=(X_test, y_test))# Compare the labels that our model predicts with the actual labelsscore = model.evaluate(X_test, y_test, batch_size=32, verbose=1,sample_weight=None)
# Print out the result
print('Test score:', score[0])
print('Test accuracy:', score[1])

Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz 11493376/11490434 [==============================] - 1s 0us/step X_train shape: (60000, 28, 28)
X_test shape: (10000, 28, 28) y_train shape: (60000,) y_test shape: (10000,)

97840da940e32f32ed54b50924f02208.png

Training matrix shape (60000, 784)
Testing matrix shape (10000, 784)
(60000,)
(60000, 10)

eb286ab3d391e7b168c863ec0e6191b2.png

图像分类

①卷积神经网络中,卷积层有助于检测图像中的区域分布。最大池化层位于卷积层之后,有助于减小维数。下面是一个图像分类的例子。在图像分类之前,先将所有图像转成标准大小。之后实验中我们将训练一个CNN,然后对CIFAR-10图像分类。(60000幅32*32彩色图像数据集,10个类别,每类6000幅图像。

②训练CNN时我们不希望根据图像大小、角度和位置改变模型的预测结果。为了使模型对图像大小、反向不敏感,可以将不同大小、不同角度的图像加入数据集。这个过程较图像数据增强,有助于过拟合。但这样可能还不够,因为增强的图像仍然是相关的。keras提供了一个图像增强类imageDataGenerator,它定义了图像数据增强的相关配置和其他属性如:
● sample--wise和 feature--wise标准化
● 图像的随机旋转、移位、剪切和缩放。
● 水平和垂直翻转。
●维度重排。
● 将变化存储至磁盘。

如下创建一个图像增强生成器:
datagen_train = ImageDataGenerator()

f6b649e74e2360db7e7749d8123bb9b7.png

③关于dropout、卷积层、池化层的详解,见本文末图片~(超简明直白哒!)

import keras
from keras.datasets import cifar10# load the pre-shuffled train and test data
# link to dataset: https://www.cs.toronto.edu/~kriz/cifar.html
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inlinefig = plt.figure(figsize=(20,5))
for i in range(36):ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])ax.imshow(np.squeeze(x_train[i]))

bd63d267599d4aa24a85ca8674d45a06.png

# rescale [0,255] --> [0,1]
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255
x_train[0]

d73121f113ff07c1b4d261b97dd20901.png

y_train[0]

array([6], dtype=uint8)

from keras.utils import np_utils# break training set into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]# one-hot encode the labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
y_valid = keras.utils.to_categorical(y_valid, num_classes)# print shape of training set
print('x_train shape:', x_train.shape)# print number of training, validation, and test images
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print(x_valid.shape[0], 'validation samples')

211a13844fc6194f068c3d797e4cc3a2.png

from keras.preprocessing.image import ImageDataGenerator# create and configure augmented image generator
datagen_train = ImageDataGenerator(width_shift_range=0.1, # randomly shift images horizontally (10% of total width)height_shift_range=0.1, # randomly shift images vertically (10% of total height)horizontal_flip=True) # randomly flip images horizontally# fit augmented image generator on data
datagen_train.fit(x_train)#在这里我们可以看到增强的图像。我们从训练数据中获取10张图像,并查看原始数据和增强数据。尝试将原始图像与增强后的图像进行匹配。
#哪些是水平翻转的?
#哪些是水平和垂直shiffted的?import matplotlib.pyplot as pltnum_to_view = 10# take subset of training data
x_train_subset = x_train[:num_to_view]# visualize subset of training data
fig = plt.figure(figsize=(20,2))
for i in range(0, len(x_train_subset)):ax = fig.add_subplot(1, num_to_view, i+1)ax.imshow(x_train_subset[i])
fig.suptitle('Subset of Original Training Images', fontsize=20)
plt.show()# visualize augmented images
fig = plt.figure(figsize=(20,2))
for x_batch in datagen_train.flow(x_train_subset, batch_size=12):for i in range(0, num_to_view):ax = fig.add_subplot(1, num_to_view, i+1)ax.imshow(x_batch[i])fig.suptitle('Augmented Images', fontsize=20)plt.show()break;

2c6118ea6046ac2e9648e331e7c5bd12.png
acfa5e61f21ccde4a265926ec4ebc0e5.png

一旦我们有了增强的图像,我们现在可以定义我们的架构,它将应用于增强的图像。

from keras import backend as K
K.clear_session()from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropoutmodel = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(10, activation='softmax'))model.summary()

cf6b573f7568ef94daa3c077c5dedb93.png

# compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

datagren.flow生成批量的增强图像。您可以为它提供训练图像和标签,以及希望批量生成的图像数量。

from keras.callbacks import ModelCheckpoint batch_size = 32
epochs = 10# train the model
checkpointer = ModelCheckpoint(filepath='aug_model.weights.best.hdf5', verbose=1, save_best_only=True)# datagren.flow makes batches of augmented images. You provide it with the
# training images and labels along with the number of images you want to be
# generated in a batch.
model.fit_generator(datagen_train.flow(x_train, y_train, batch_size=batch_size),steps_per_epoch=x_train.shape[0] // batch_size,epochs=epochs, verbose=2, callbacks=[checkpointer],validation_data=(x_valid, y_valid),validation_steps=x_valid.shape[0] // batch_size)

66326f14b1df1c57a9462a7d8bf9bf62.png

# load the weights that yielded the best validation accuracy
model.load_weights('aug_model.weights.best.hdf5')

# evaluate and print test accuracy
score = model.evaluate(x_test, y_test, verbose=0)
print('n', 'Test accuracy:', score[1])

Test accuracy: 0.6191

# get predictions on the test set
y_hat = model.predict(x_test)# define text labels (source: https://www.cs.toronto.edu/~kriz/cifar.html)
cifar10_labels = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

# plot a random sample of test images, their predicted labels, and ground truth
fig = plt.figure(figsize=(20, 8))
for i, idx in enumerate(np.random.choice(x_test.shape[0], size=32, replace=False)):ax = fig.add_subplot(4, 8, i + 1, xticks=[], yticks=[])ax.imshow(np.squeeze(x_test[idx]))pred_idx = np.argmax(y_hat[idx])true_idx = np.argmax(y_test[idx])ax.set_title("{} ({})".format(cifar10_labels[pred_idx], cifar10_labels[true_idx]),color=("green" if pred_idx == true_idx else "red"))

d1a589364eabf0ced09f78d1c0bfa02b.png
我个人喜欢手动扩展数据。我使用 aleju/imgaug
## 这里有一个方便的Keras备忘单:https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Keras_Cheat_Sheet_Python.pdf
## CIFAR-10获奖者访谈:
CIFAR-10 Competition Winners: Interviews with Dr. Ben Graham, Phil Culliton, & Zygmunt Zając
##著名的CNN架构,通常用于工业和学术研究:http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdfhttps://arxiv.org/pdf/1409.1556.pdf

参考资料:

Practical Convolutional Neural Networks: Implement advanced deep learning models using Python Paperback》https://github.com/huanghanchi/Practical-Convolutional-Neural-Networks/blob/master/Chapter02/CNN_3.pyhttps://colab.research.google.com/drive/1hn284Jk4KDlHbgU1b9sQLJPp5fpyA9G5#scrollTo=J9AiuBpgt6HS

附录

关于dropout、卷积层、池化层的详解

680b2b76ae538866273bb929fcdb1a46.png
8d39c7c4115a11a277d1cf1a0584756b.png
bf74a42208491d4e7d672445eaec6844.png
a4f958823d711835c9c3080b1467c9ce.png
20930c6b60484e8aa7a9e539bfab3b3d.png



推荐阅读
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • CF:3D City Model(小思维)问题解析和代码实现
    本文通过解析CF:3D City Model问题,介绍了问题的背景和要求,并给出了相应的代码实现。该问题涉及到在一个矩形的网格上建造城市的情景,每个网格单元可以作为建筑的基础,建筑由多个立方体叠加而成。文章详细讲解了问题的解决思路,并给出了相应的代码实现供读者参考。 ... [详细]
  • 也就是|小窗_卷积的特征提取与参数计算
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了卷积的特征提取与参数计算相关的知识,希望对你有一定的参考价值。Dense和Conv2D根本区别在于,Den ... [详细]
  • 统一知识图谱学习和建议:更好地理解用户偏好
    本文介绍了一种将知识图谱纳入推荐系统的方法,以提高推荐的准确性和可解释性。与现有方法不同的是,本方法考虑了知识图谱的不完整性,并在知识图谱中传输关系信息,以更好地理解用户的偏好。通过大量实验,验证了本方法在推荐任务和知识图谱完成任务上的优势。 ... [详细]
  • CentOS7.8下编译muduo库找不到Boost库报错的解决方法
    本文介绍了在CentOS7.8下编译muduo库时出现找不到Boost库报错的问题,并提供了解决方法。文章详细介绍了从Github上下载muduo和muduo-tutorial源代码的步骤,并指导如何编译muduo库。最后,作者提供了陈硕老师的Github链接和muduo库的简介。 ... [详细]
  • keras归一化激活函数dropout
    激活函数:1.softmax函数在多分类中常用的激活函数,是基于逻辑回归的,常用在输出一层,将输出压缩在0~1之间,且保证所有元素和为1,表示输入值属于每个输出值的概率大小2、Si ... [详细]
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
  • 3.223.28周学习总结中的贪心作业收获及困惑
    本文是对3.223.28周学习总结中的贪心作业进行总结,作者在解题过程中参考了他人的代码,但前提是要先理解题目并有解题思路。作者分享了自己在贪心作业中的收获,同时提到了一道让他困惑的题目,即input details部分引发的疑惑。 ... [详细]
  • 【shell】网络处理:判断IP是否在网段、两个ip是否同网段、IP地址范围、网段包含关系
    本文介绍了使用shell脚本判断IP是否在同一网段、判断IP地址是否在某个范围内、计算IP地址范围、判断网段之间的包含关系的方法和原理。通过对IP和掩码进行与计算,可以判断两个IP是否在同一网段。同时,还提供了一段用于验证IP地址的正则表达式和判断特殊IP地址的方法。 ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • 网址:https:vue.docschina.orgv2guideforms.html表单input绑定基础用法可以通过使用v-model指令,在 ... [详细]
  • 本文介绍了使用Spark实现低配版高斯朴素贝叶斯模型的原因和原理。随着数据量的增大,单机上运行高斯朴素贝叶斯模型会变得很慢,因此考虑使用Spark来加速运行。然而,Spark的MLlib并没有实现高斯朴素贝叶斯模型,因此需要自己动手实现。文章还介绍了朴素贝叶斯的原理和公式,并对具有多个特征和类别的模型进行了讨论。最后,作者总结了实现低配版高斯朴素贝叶斯模型的步骤。 ... [详细]
author-avatar
mobiledu2502925453
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有