Keras#2

使用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)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容