import tensorflow as tf
from tensorflow.keras.datasets import cifar10
#-------------------------------------------------------------------------------------------#
# Load data
(train_images, train_labels), (test_images, test_labels)= cifar10.load_data()
# Normalize data into [0,1]
train_images, test_images= train_images/255, test_images/255
#-------------------------------------------------------------------------------------------#
# Define CNN model
model= tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(32,32,3)), #Coevolution layer 1
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'), #Coevolution layer 2
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'), #Coevolution layer 3
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'), #Full connection layer 1
tf.keras.layers.Dense(10)
])
#-------------------------------------------------------------------------------------------#
# Compile the model defined above
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
#-------------------------------------------------------------------------------------------#
# Train the model compiled above (for 10 epochs)
history= model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels))
#-------------------------------------------------------------------------------------------#
# Evalutate the model we fitted
test_loss, test_acc= model.evaluate(test_images, test_labels, verbose=2) #evaluate the loss and accuracy of fitted model in test data
print('Test accuracy:', test_acc)
#-------------------------------------------------------------------------------------------#
# Model use
predictions= model.predict(test_images) #use the fitted model to discriminate and label pictures
网友评论