使用神图像分类经网络经行

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from time import time
from tensorflow.keras.datasets import mnist

(x_train_image, y_train_label), (x_test_image, y_test_label) = mnist.load_data()

print('x_train:', x_train_image.shape)
print('y_train:', y_train_label.shape)

import matplotlib.pyplot as plt
def plot_image(image):
    fig = plt.gcf()
    fig.set_size_inches(2,2) #设置图形的宽为2英寸,高为2英寸
    plt.imshow(image, cmap='binary') #以黑白灰度显示图形
    plt.show()
plot_image(x_train_image[0])

# 将图像转化为一维向量
x_train = x_train_image.reshape(60000, 784).astype('float32')
x_test = x_test_image.reshape(10000, 784).astype('float32')

# 图像标准化
x_train = x_train / 255
x_test = x_test / 255

print(y_train_label[:5]) #查看原本的前5个标签

from tensorflow.python.keras.utils import np_utils

y_train = np_utils.to_categorical(y_train_label)
y_test = np_utils.to_categorical(y_test_label)

print('one-hot:')
print(y_train[:5]) #查看经过one-hot编码的前5个标签

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense

model = Sequential()
model.add(Dense(units=256,
                input_dim=784,
                kernel_initializer='normal',
                activation='relu'))
model.add(Dense(units=10,
                kernel_initializer='normal',
                activation='softmax'))
print(model.summary())

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

train_history = model.fit(x=x_train,
                          y=y_train,
                          validation_split=0.2,
                          epochs=10,
                          batch_size=200,
                          verbose=2)

def show_train_history(train_history, train, validation):
    plt.plot(train_history.history[train])
    plt.plot(train_history.history[validation])
    plt.title('Train history')
    plt.ylabel(train)
    plt.xlabel('Epoch')
    plt.legend(['train', 'validation'], loc='upper left')
    plt.show()
show_train_history(train_history, 'accuracy', 'val_accuracy')
scores = model.evaluate(x_test, y_test)
print()
print('accuracy=', scores[1])

prediction = model.predict_classes(x_test)
print(prediction)

def plot_images_labels_prediction(images, labels, prediction, idx, num=10):
    fig = plt.gcf()
    fig.set_size_inches(12, 5)
    if num>25: num=25
    for i in range(num):
        ax = plt.subplot(5, 5, i+1)
        ax.imshow(images[idx], cmap='binary')
        title = 'label=' + str(labels[idx])
        if len(prediction) > 0:
            title += '.predict=' + str(prediction[idx])
        ax.set_title(title, fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])
        idx += 1
    plt.show()
plot_images_labels_prediction(x_test_image, y_test_label, prediction, idx=340)


from PIL import Image
import numpy as np

img = Image.open('white_0.jpg').convert('L')
print('img size:', img.size)
img = np.array(img).reshape(1, 784).astype('float32')
img = img / 255
pred_label = model.predict_classes(img)
print('predict my img',pred_label)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值