keras数字图像识别

aistudio地址:
https://aistudio.baidu.com/aistudio/projectdetail/1484526

keras的数字图像识别

一、加载数据

MNIST数据集预加载到Keras库中,包括4个Numpy数组。
然后使用pyplot显示其中一个数组的图片

因为每次都需要重新下载,可以先手动下载到本地,然后加载文件
wget https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz

from keras.datasets import mnist
import numpy as np

# 使用mnist加载数据
# (train_images, train_labels), (test_images, test_labels) = mnist.load_data()


# 使用本地文件加载数据
train_images = np.load("/home/aistudio/work/mnist/x_train.npy", allow_pickle=True)
train_labels = np.load("/home/aistudio/work/mnist/y_train.npy", allow_pickle=True)
test_images = np.load("/home/aistudio/work/mnist/x_test.npy", allow_pickle=True)
test_labels = np.load("/home/aistudio/work/mnist/y_test.npy", allow_pickle=True)

1.1 查看数据

  • 图像是28x28 NumPy数组,像素值介于0到255之间。
  • 标签是一个整数数组,范围从0到9.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg


print(train_images.shape)
print(train_labels)
print(test_images.shape)
print(test_labels)

# 25 * 25的grid显示125张图片
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(train_labels[i])
plt.show()
(60000, 28, 28)
[5 0 4 ... 5 6 8]
(10000, 28, 28)
[7 2 1 ... 4 5 6]
output_3_1.png

二、数据预处理

2.1 图片数据三维转二维

# 三维转二维train_images

train_images_re = train_images.reshape((60000, 28 * 28))
test_images_re = test_images.reshape((10000, 28 * 28))
print(train_images_re.shape)

train_images_re = train_images_re.astype('float32') / 255
test_images_re = test_images_re.astype('float32') / 255

(60000, 784)

2.2 标签分类编码

改成one hot编码。
一个二维数组,数字5转成0. 0. 0. 0. 0. 1. 0. 0. 0. 0.,第五个元素为1.

from keras.utils import to_categorical

train_labels_re = to_categorical(train_labels)
test_labels_re = to_categorical(test_labels)

print('原始: ', train_labels)
print('转化后 - one hot: ')
for i in range(10):
    print(train_labels_re[i])



原始:  [5 0 4 ... 5 6 8]
转化后 - one hot: 
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]

三、构建网络

3.1添加层

from keras import models
from keras import layers

network = models.Sequential()
# 第一层定义
# 输出,第一维大小:512
# 输入,第一维大小:28 * 28
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28, )))

# 第二层定义
network.add(layers.Dense(10, activation='softmax'))

3.1 编译

添加损失函数、优化器、监控指标

network.compile(
    optimizer='rmsprop',
    loss='categorical_crossentropy',
    metrics=['accuracy']
)

四、拟合模型

network.fit(
    train_images_re,
    train_labels_re,
    epochs=5,
    batch_size=128
)
Epoch 1/5
469/469 [==============================] - 16s 33ms/step - loss: 0.4357 - accuracy: 0.87
Epoch 2/5
469/469 [==============================] - 14s 30ms/step - loss: 0.1135 - accuracy: 0.96
Epoch 3/5
469/469 [==============================] - 15s 31ms/step - loss: 0.0691 - accuracy: 0.97
Epoch 4/5
469/469 [==============================] - 15s 33ms/step - loss: 0.0452 - accuracy: 0.98
Epoch 5/5
469/469 [==============================] - 14s 29ms/step - loss: 0.0352 - accuracy: 0.98





<tensorflow.python.keras.callbacks.History at 0x7f8c27af7190>

五、验证模型

精确度:accuracy
损失度:loss

test_loss, test_acc = network.evaluate(test_images_re, test_labels_re)
print('test_loss', test_loss)
print('test_acc', test_acc)
313/313 [==============================] - 1s 2ms/step - loss: 0.0707 - accuracy: 0.97
test_loss 0.07070968300104141
test_acc 0.9790999889373779

六、预测模型

  • 使用predict()方法进行预测,返回样本属于每一个类别的概率
  • 使用numpy.argmax()方法找到样本以最大概率所属的类别作为样本的预测标签。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

predictions = network.predict(test_images_re)

# 显示预测结果 
plt.figure(figsize=(10,10))
for i in range(25):
    pre_label = np.argmax(predictions[i])
    pre_percent = round(predictions[i][np.argmax(predictions[i])] * 100, 2)
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(test_images[i], cmap=plt.cm.binary)
    plt.xlabel(str(pre_percent) + '%: ' + str(pre_label))
plt.show()

output_17_0.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354

推荐阅读更多精彩内容