# 1 引入库
# 2 数据预处理
# 3 建立模型
# 4 loss 设置
# 5 编译
# 6 结果展示与可视化
# 导入库
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
from tensorflow.keras import Model
from tensorflow.keras.layers import MaxPool2D, BatchNormalization,Dropout,Activation,Conv2D,MaxPool2D,Flatten
# 2 导入数据 使用的cifar10
(train_images,train_labels),(test_images,test_labels)=datasets.cifar10.load_data()
Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz
170500096/170498071 [==============================] - 4s 0us/step
# 数据归一化
train_images,test_images=train_images/255.0,test_images/255.0
train_images.shape,train_labels.shape
((50000, 32, 32, 3), (50000, 1))
train_labels[:10]
array([[6],
[9],
[9],
[4],
[1],
[1],
[2],
[7],
[8],
[3]], dtype=uint8)
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer','dog', 'frog', 'horse', 'ship', 'truck']
plt.figure(figsize=(20,10))
for i in range(20):
plt.subplot(5,10,i+1)
plt.grid(False)
plt.xticks=([])
plt.yticks=([])
plt.imshow(train_images[i],cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i][0]])
plt.show()

from tensorflow.keras.layers import MaxPooling2D,Dense
# 使用CNN网络
class model1(Model):
def __init__(self):
super(model1,self).__init__()
self.c1=Conv2D(filters=32,kernel_size=(3, 3),padding='same', activation='relu')
self.m1=MaxPooling2D(pool_size=(2, 2))
self.c2=Conv2D(64, (3, 3),padding='same', activation='relu')
self.m2=MaxPooling2D(pool_size=(2, 2))
self.c3=Conv2D(64, (3, 3),padding='same', activation='relu')
self.f1=Flatten()
self.d1=Dense(64, activation='relu')
self.d2=Dense(10)
def call(self,x):
x=self.c1(x)
x=self.m1(x)
x=self.c2(x)
x=self.m2(x)
x=self.c3(x)
x=self.f1(x)
x=self.d1(x)
y=self.d2(x)
return y
model1=model1()
optimizer=tf.keras.optimizers.SGD(lr=0.1)
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)
metrics= ['sparse_categorical_accuracy']
model1.compile(optimizer=optimizer,loss=loss,metrics=metrics)
history=model1.fit(train_images,train_labels,epochs=10,validation_data=(test_images, test_labels))
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py:375: UserWarning: The `lr` argument is deprecated, use `learning_rate` instead.
"The `lr` argument is deprecated, use `learning_rate` instead.")
Epoch 1/10
1563/1563 [==============================] - 95s 61ms/step - loss: 11.0572 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 2/10
1563/1563 [==============================] - 94s 60ms/step - loss: 11.0572 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 3/10
1563/1563 [==============================] - 95s 61ms/step - loss: 11.0572 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 4/10
1563/1563 [==============================] - 95s 61ms/step - loss: 11.0571 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 5/10
1563/1563 [==============================] - 95s 61ms/step - loss: 11.0572 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 6/10
1563/1563 [==============================] - 95s 61ms/step - loss: 11.0571 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 7/10
1563/1563 [==============================] - 95s 61ms/step - loss: 11.0571 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 8/10
1563/1563 [==============================] - 95s 61ms/step - loss: 11.0572 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 9/10
1563/1563 [==============================] - 95s 60ms/step - loss: 11.0572 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
Epoch 10/10
1563/1563 [==============================] - 94s 60ms/step - loss: 11.0571 - sparse_categorical_accuracy: 0.1000 - val_loss: 11.0572 - val_sparse_categorical_accuracy: 0.1000
model1.summary()
Model: "model1_11"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_18 (Conv2D) multiple 896
_________________________________________________________________
max_pooling2d_8 (MaxPooling2 multiple 0
_________________________________________________________________
conv2d_19 (Conv2D) multiple 18496
_________________________________________________________________
max_pooling2d_9 (MaxPooling2 multiple 0
_________________________________________________________________
conv2d_20 (Conv2D) multiple 36928
_________________________________________________________________
flatten_8 (Flatten) multiple 0
_________________________________________________________________
dense_14 (Dense) multiple 262208
_________________________________________________________________
dense_15 (Dense) multiple 650
=================================================================
Total params: 319,178
Trainable params: 319,178
Non-trainable params: 0
_________________________________________________________________
# 进行预测
import numpy as np
pre = model1.predict(test_images)
print(class_names[np.argmax(pre[1])])
history.history.keys()
dict_keys(['loss', 'sparse_categorical_accuracy', 'val_loss', 'val_sparse_categorical_accuracy'])
history.history['loss']
[11.05714225769043, 11.057150840759277, 11.057130813598633]
history.history['sparse_categorical_accuracy']
[0.10000000149011612, 0.10000000149011612, 0.10000000149011612]
plt.plot(history.history['sparse_categorical_accuracy'], label='accuracy')
plt.plot(history.history['val_sparse_categorical_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.show()

import matplotlib.pyplot as plt
plt.plot(history.history['sparse_categorical_accuracy'], label='accuracy')
plt.plot(history.history['val_sparse_categorical_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.show()
test_loss, test_acc = model1.evaluate(test_images, test_labels, verbose=2)

313/313 - 4s - loss: 11.0572 - sparse_categorical_accuracy: 0.1000
import matplotlib.pyplot as plt
plt.plot(history.history['loss'], label='loss')
plt.plot(history.history['val_loss'], label = 'val_loss')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.show()
test_loss, test_acc = model1.evaluate(test_images, test_labels, verbose=2)

313/313 - 4s - loss: 11.0572 - sparse_categorical_accuracy: 0.1000
#3 模型生成
class Baseline2(Model):
def __init__(self):
super(Baseline2,self).__init__()
self.c1=Conv2D(filters=6,kernel_size=(5,5),padding='same')
self.b1=BatchNormalization()
self.a1=Activation('relu')
self.p1=MaxPool2D(pool_size=(2,2),strides=2,padding='same')
self.d1=Dropout(0.2)
self.flatten=Flatten()
self.f1=Dense(128,activation='relu')
self.d2=Dropout(0.2)
self.f2=Dense(10,activation='softmax')
#call函数调用init函数中搭建好的每层网络结构
def call(self,x):
x=self.c1(x)
x=self.b1(x)
x=self.a1(x)
x=self.p1(x)
x=self.d1(x)
x=self.flatten(x)
x=self.f1(x)
x=self.d2(x)
y=self.f2(x)
return y
# 模型实例化
model2=Baseline2()
optimizer=tf.keras.optimizers.SGD(lr=0.1)
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)
metrics= ['sparse_categorical_accuracy']
model2.compile(optimizer=optimizer,loss=loss,metrics=metrics)
# batch_size=100,
history2=model2.fit(train_images,train_labels,epochs=3,validation_data=(test_images, test_labels))