import tensorflow as tf
(x, y), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib notebook
plt.imshow(x[49999])
x = x/255
x_test = x_test/255
model = tf.keras.Sequential([
tf.keras.Input(shape=(32,32,3)),
tf.keras.layers.Conv2D(filters=32 ,kernel_size=3 , padding='same', activation='relu'),
tf.keras.layers.Dropout(0.25),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),strides=(2,2)),
tf.keras.layers.Conv2D(filters=64 ,kernel_size=3 , padding='same', activation='relu'),
tf.keras.layers.Dropout(0.25),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),strides=(2,2)),
tf.keras.layers.Conv2D(filters=128 ,kernel_size=3 , padding='same', activation='relu'),
tf.keras.layers.Dropout(0.25),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),strides=(2,2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1024, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.summary()
model.compile(
optimizer = tf.keras.optimizers.Adam(learning_rate=0.01),
loss = tf.keras.losses.sparse_categorical_crossentropy,
metrics = ['acc']
batches = 50
batch_size = 20000
data = []
for i in range(batches):
index=np.random.choice(x.shape[0],batch_size,replace=False)
x_batch = x[index]
y_batch = y[index]
history = model.fit(x_batch,y_batch, batch_size=1000, validation_split=0.2)
hist = pd.DataFrame(history.history)
data.append(hist)
df = pd.concat(data).reset_index(drop=True)
def plot_history(hist):
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
plt.xlabel('Epoch')
plt.plot(hist['loss'],
label='loss')
plt.plot( hist['val_loss'],
label='val_loss')
plt.legend()
plt.subplot(1,2,2)
plt.xlabel('Epoch')
plt.plot( hist['acc'],
label = 'acc',color = 'red')
plt.plot( hist['val_acc'],
label = 'val_acc')
plt.legend()
plot_history(df)
model.evaluate(x_test, y_test, verbose=2)
def writePre(pre,class_names):
for i in range(len(class_names)):
if pre == class_names[i]:
return i
def writeTar(tar,class_names):
for i in range(len(class_names)):
if tar == class_names[i]:
return i
prediction = model.predict(x_test)
class_names = ['飞机','汽车','鸟','猫','鹿','狗','青蛙','马','船','卡车']
for x in range(10):
num = 0
n = 0
num_1 = 0
n_1 = 0
sj = class_names[x]
for i in range(10000):
pre = class_names[np.argmax(prediction[i])]
tar = class_names[y_test[i][0]]
if pre == sj:
if tar == sj:
num += 1
else:
n += 1
if tar == sj:
if pre == sj:
num_1 += 1
else:
n_1 += 1
jql = num/(num+n)
zhl = num_1/(num_1+n_1)
f1 = (2*jql*zhl)/(jql+zhl)
print("预测%s 的精确率为: %s" %(sj,jql))
print("预测%s 的召回率为: %s" %(sj,zhl))
print("f1值为: %s" %(f1))
y_true = []
y_pred = []
for i in range(10000):
pre = class_names[np.argmax(prediction[i])]
tar = class_names[y_test[i][0]]
y_pred.append(writePre(pre,class_names))
y_true.append(writeTar(tar,class_names))
from sklearn.metrics import confusion_matrix
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['font.sans-serif'] = ['SimHei']
classes = ['飞机','汽车','鸟','猫','鹿','狗','青蛙','马','船','卡车']
confusion = confusion_matrix(y_pred, y_true)
print(confusion)
plt.figure(figsize=(10,5))
plt.imshow(confusion, cmap=plt.cm.Blues)
indices = range(len(confusion))
plt.xticks(indices, classes)
plt.yticks(indices, classes)
plt.colorbar()
plt.ylabel('Pred')
plt.xlabel('True')
for first_index in range(len(confusion)):
for second_index in range(len(confusion[first_index])):
plt.text(second_index, first_index,confusion[first_index][second_index])
plt.show()
)
|