1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras import layers, optimizers, datasets, Sequential from tensorflow.keras.layers import Dense, Dropout, Activation import numpy as np
import os
from tensorflow.python.keras.optimizer_v2.gradient_descent import SGD from tensorflow.python.keras.utils import np_utils
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
def load_data(path): f = np.load(path) x_train, y_train = f['x_train'], f['y_train'] x_test, y_test = f['x_test'], f['y_test'] f.close() x_train = x_train.reshape(x_train.shape[0], 28 * 28) x_test = x_test.reshape(x_test.shape[0], 28 * 28) x_train = x_train.astype('float32') x_test = x_test.astype('float32') y_train = np_utils.to_categorical(y_train, 10) y_test = np_utils.to_categorical(y_test, 10) x_train = x_train / 255 x_test = x_test / 255 return (x_train, y_train), (x_test, y_test)
(x_train, y_train), (x_test, y_test) = load_data(path='mnist.npz')
model = Sequential() model.add(Dense(input_dim=28 * 28, units=500, activation='sigmoid')) model.add(Dense(units=500, activation='sigmoid')) model.add(Dense(units=500, activation='sigmoid')) model.add(Dense(units=10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.1), metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=100, epochs=20)
result = model.evaluate(x_test, y_test) print('\nTest loss:', result[0]) print('\nTest Accuracy:', result[1])
|