本文共 1604 字,大约阅读时间需要 5 分钟。
import tensorflow as tffrom tensorflow import kerasfashion_mnist = keras.datasets.fashion_mnist#导入数据集(train_images,train_labels),(test_images,test_labels) = fashion_mnist.load_data()
print(train_images.shape)#60000张,每张28*28import matplotlib.pyplot as pltplt.imshow(train_images[0])
#全连接网络模型model = keras.Sequential([ keras.layers.Flatten(input_shape = (28,28)), keras.layers.Dense(128,activation=tf.nn.relu), keras.layers.Dense(10,activation = tf.nn.softmax) ])#model = keras.Sequential()#model.add(keras.layers.Flatten(input_shape=(28,28)))#model.add(keras.layer.Dense(128,activation =tf.nn.relu))#model.add(keras.layer.Dense(10,activation= tf.nn.softmax))model.summary()#100480 784像素*128神经元=100352(因为输入层和中间层每层都有一个bias,加上就是100480)#1290 = (128+1)*10
#Adam()一种经常使用的优化办法#train_label[0] = 9,使用sparse_categorical_crossentropy作为损失函数,若[0,0,0,0,0,0,0,0,0,0,0,1](称为ont-hot)则使用categorical_crossentropy作为损失函数model.compile(optimizer = tf.optimizers.Adam(),loss = tf.losses.sparse_categorical_crossentropy,metrics=['accuracy'])model.fit(train_images,train_labels,epochs=5)
#为了提高模型精确度,可以通过对原始数据进行归一化处理再进行模型拟合train_images = train_images/255model.compile(optimizer = tf.optimizers.Adam(),loss = tf.losses.sparse_categorical_crossentropy,metrics=['accuracy'])model.fit(train_images,train_labels,epochs=5)
#评估模型test_images_scaled = test_images/255model.evaluate(test_images_scaled,test_labels)
#预测#教程中没有加reshape,会报错model.predict([[test_images[0].reshape(1,28,28,1)/255]])
神经元网络不是训练越多越好,越多的话会出现过拟合,也就是说对所有训练图片识别很好,但对新图片识别很差,可以通过对测试LOSS和训练LOSS进行对比,出现分叉即过拟合,tensorflow中通过callback类进行判断及时终止训练
转载地址:http://iagwi.baihongyu.com/