Keras#2

2019-11-05  本文已影响0人  chakopht

使用keras进行mnist识别

构建一个两层全连接网络

因为全连接输出层为十个输出,所以将标签y进行one-hot encoding对应输出

代码如下

from tensorflow.keras.datasets import mnist

from tensorflow.keras import utils

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Dense

from tensorflow.keras.optimizers import RMSprop

#download the mnist to the path

(X_train, y_train), (X_test, y_test) = mnist.load_data()

#data pre-processing normalization

X_train = X_train.reshape(X_train.shape[0], -1)/255

X_test = X_test.reshape(X_test.shape[0], -1)/255

# one hot

y_train = utils.to_categorical(y_train, num_classes=10)

y_test = utils.to_categorical(y_test, num_classes=10)

model = Sequential([

            Dense(units=32, input_shape=[784], activation="relu"),

            Dense(units=10, activation='softmax')

])

rmsprop = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)

model.compile( optimizer=rmsprop,loss="categorical_crossentropy", metrics = ["accuracy"],)

model.fit(X_train, y_train, nb_epoch=2, batch_size=32)

loss, accuracy = model.evaluate(X_test, y_test)

print("loss:",loss)

print("accuracy:",accuracy)

上一篇下一篇

猜你喜欢

热点阅读