下載數(shù)據(jù)集Cifar10數(shù)據(jù)集總共有6萬張32*32像素點(diǎn)的彩色圖片和標(biāo)簽,,涵蓋十個(gè)分類:飛機(jī)、汽車、鳥、貓,、鹿、狗、青蛙,、馬、船,、卡車,。 其中5萬張用于訓(xùn)練,1萬張用于測(cè)試,。
import tensorflow as tf from tensorflow import keras from matplotlib import pyplot as plt import numpy as np from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense,Dropout cifar10 = keras.datasets.cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0
搭建網(wǎng)絡(luò)結(jié)構(gòu)model = keras.models.Sequential([ Conv2D(128, (3, 3), activation='relu',padding='same'), keras.layers.BatchNormalization(), MaxPool2D((2, 2)), Dropout(0.3), Conv2D(256, (3, 3), activation='relu',padding='same'), keras.layers.BatchNormalization(), MaxPool2D((2, 2)), Dropout(0.3), Conv2D(512, (3, 3), activation='relu',padding='same'), keras.layers.BatchNormalization(), MaxPool2D((2, 2)), Flatten(), Dropout(0.5), Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l2(0.1)), Dropout(0.5), Dense(10, activation='softmax') ])
編譯模型model.compile(optimizer=keras.optimizers.Adam(lr=0.0001), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['accuracy'])
訓(xùn)練模型history = model.fit(x_train, y_train, epochs=100, batch_size=16,verbose=1,validation_data=(x_test, y_test),validation_freq=1)
可視化acc/loss曲線#顯示訓(xùn)練集和測(cè)試集的acc和loss曲線 plt.rcParams['font.sans-serif']=['SimHei'] acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] plt.subplot(1, 2, 1) plt.plot(acc, label='訓(xùn)練Acc') plt.plot(val_acc, label='測(cè)試Acc') plt.title('Acc曲線') plt.legend() plt.subplot(1, 2, 2) plt.plot(loss, label='訓(xùn)練Loss') plt.plot(val_loss, label='測(cè)試Loss') plt.title('Loss曲線') plt.legend() plt.show()
|
|