链接
第一篇文章是tensorflow的入门,实现一个简单的分类问题。数据集是fashion mnist,没有直接用mnist,mnist手写字识别认为是tensorflow的‘hello world’。fashion mnist是一些灰度图,内容是衣服,鞋子等,有10个类别,一共有样本70000条,60000条作为训练集、1000条作为测试集。

导入需要的库

参考链接开头需要的库

导入fashion mnist数据集

  1. fashion_mnist = keras.datasets.fashion_mnist
  2. /*
  3. train_images.shape = (60000, 28, 28)
  4. len(train_labels) = 60000
  5. test_images.shape = (10000, 28, 28)
  6. len(test_labels) = 10000
  7. */
  8. //todo:这里是否可以用其他的划分方式,比如多分出一个验证集?
  9. (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
  10. //用0-9来表示不同的类别,这里把class_names表示出来是为了后面画图展示
  11. class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
  12. 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

处理输入数据

可以看到训练集的像素取值在[0-255]之间,所以需要把输入参数归一化,训练集和测试集的处理方式需要是一样的。这里可以用原链接中的代码在notebook中演示一下,把图片画出来比较容易理解。

  1. train_images = train_images / 255.0
  2. test_images = test_images / 255.0

构建模型

设置网络结构

  1. model = keras.Sequential([
  2. keras.layers.Flatten(input_shape=(28, 28)), //需要把输入转成一维向量
  3. keras.layers.Dense(128, activation='relu'),
  4. keras.layers.Dense(10, activation='softmax')
  5. ])

编译模型(compile the model)

  • Loss function —This measures how accurate the model is during training. We want to minimize this function to “steer” the model in the right direction.
  • Optimizer —This is how the model is updated based on the data it sees and its loss function.
  • Metrics —Used to monitor the training and testing steps. The following example uses accuracy, the fraction of the images that are correctly classified.
  1. model.compile(optimizer='adam',
  2. loss='sparse_categorical_crossentropy',
  3. metrics=['accuracy'])

训练模型

  1. Feed the training data to the model. In this example, the training data is in the train_images and train_labels arrays.
  2. The model learns to associate images and labels.
  3. We ask the model to make predictions about a test set—in this example, the test_images array. We verify that the predictions match the labels from the test_labels array.
  1. model.fit(train_images, train_labels, epochs=10)

评估准确性

  1. test_loss, test_acc = model.evaluate(test_images, test_labels)
  2. print('\nTest accuracy:', test_acc)

预测

可以结合画图来看预测结果

  1. predictions = model.predict(test_images)