Deep Learning: Keras + MNIST

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DreamHome_S/article/details/82953960

Data representations for neural networks

# -*- coding: utf-8 -*-

"""
@Date: 2018/9/28

@Author: dreamhomes

@Summary:
"""

from keras.utils import to_categorical
from keras import models
from keras import layers

import numpy as np


# (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
path = "./mnist.npz"
f = np.load(path)
# N=60000
train_images, train_labels = f['x_train'], f['y_train']
print(len(train_labels))

#import matplotlib.pyplot as plt
# digit = train_images[0]
# plt.imshow(digit, cmap=plt.cm.binary)
# plt.show()


test_images, test_labels = f['x_test'], f['y_test']

network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(512, activation='relu'))
network.add(layers.Dense(10, activation='softmax'))

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

train_images = train_images.reshape((60000, 28 * 28))
# print(train_images[1])

train_images = train_images.astype('float32') / 255

test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

history = network.fit(train_images, train_labels, epochs=5, batch_size=128)

# print(history.history.keys())

test_loss, test_acc = network.evaluate(test_images, test_labels)

print('test_acc:', test_acc)

猜你喜欢

转载自blog.csdn.net/DreamHome_S/article/details/82953960