训练你的第一个神经网络:基本分类

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

导入需要的库

参考链接需要的库
https://www.tensorflow.org/beta/tutorials/keras/basic_classification

导入fashion mnist数据集

fashion_mnist = keras.datasets.fashion_mnist

/*
	train_images.shape = (60000, 28, 28)
	len(train_labels) = 60000
  test_images.shape = (10000, 28, 28)
	len(test_labels) = 10000
*/
//todo:这里是否可以用其他的划分方式,比如多分出一个验证集?
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

//0-9来表示不同的类别,这里把class_names表示出来是为了后面画图展示
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

处理输入数据

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

train_images = train_images / 255.0

test_images = test_images / 255.0

构建模型

设置网络结构

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

编译模型(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.
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              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.
model.fit(train_images, train_labels, epochs=10)

评估准确性

test_loss, test_acc = model.evaluate(test_images, test_labels)

print('\nTest accuracy:', test_acc)

预测

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

predictions = model.predict(test_images)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值