[机器学习读书笔记] - Tensorflow 应用之CNN图片识别

241 阅读1分钟

1. 基本概念

2. Tensorflow 代码示例:

# CNN for classifing Fashion MNIST dataset

import tensorflow as tf

def train_mnist_conv():
    class myCallback(tf.keras.callbacks.Callback):
      def on_epoch_end(self, epoch, logs={}):
        if(logs.get('acc')>0.998):
          print("\nReached 99.8% accuracy so cancelling training!")
          self.model.stop_training = True
    callbacks = myCallback()

    mnist = tf.keras.datasets.mnist
    (training_images, training_labels), (test_images, test_labels) = mnist.load_data(path=path)
    training_images=training_images.reshape(60000, 28, 28, 1)
    training_images=training_images / 255.0 
    test_images = test_images.reshape(10000, 28, 28, 1)
    test_images=test_images/255.0

    model = tf.keras.models.Sequential([
  # The first layer in your network should be the same shape as your data. Right now our data is 28x28x1 images.  
  tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),
  tf.keras.layers.MaxPooling2D(2, 2),
  tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
  tf.keras.layers.MaxPooling2D(2,2),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  # The number of neurons in the last layer should match the number of classes you are classifying for.
  tf.keras.layers.Dense(10, activation='softmax')])

    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    # model fitting
    history = model.fit(training_images, training_labels, epochs=20, callbacks=[callbacks])
    print (history.epoch, history.history['acc'][-1])
    # evaluate
    model.evaluate(test_images, test_labels)
    # predict
    classifications = model.predict(test_images)