import keras import tensorflow as tf keras.__version__ from keras import layers from keras import models model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) # 最后一层卷积需要的参数大小为:(3*3*64+1)*64 model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# 将图片摊平,变为一维3*3*64 model.add(layers.Flatten()) # 该层是fully connect 全连接层 # 参数计算为:(1*1*576+1)*64=36928,可以认为全连接层的卷积核大小为1*1。不卷了 model.add(layers.Dense(64, activation='relu')) # 该层也是fully connect,最后输出 # 参数计算为:(1*1*64+1)*10=650 model.add(layers.Dense(10, activation='softmax'))
rom keras.datasets import mnist from keras.utils import to_categorical (train_images, train_labels), (test_images, test_labels) = mnist.load_data() #若无法运行 #昨天遇到的问题cannot import name 'to_categorical' from 'keras.utils' (/usr/local/lib/python3.7/dist-packages/keras/utils/__init__.py) 解决方案 #import tensorflow as tf #to_categorical = tf.keras.utils.to_categorical # 图片需要变为4维张量 train_images = train_images.reshape((60000, 28, 28, 1)) train_images = train_images.astype('float32') / 255 test_images = test_images.reshape((10000, 28, 28, 1)) test_images = test_images.astype('float32') / 255 # one-hot encoding to_categorical相当于one-hot encoding. train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy',#多元交叉熵损失函数 metrics=['accuracy']) model.fit(train_images, train_labels, epochs=5, batch_size=64) #测试集放入模型 test_loss, test_acc = model.evaluate(test_images, test_labels) #正确率 test_acc
过程中需要计算的参数