coding=utf-8
“”"
author:lei
function:
“”"
from tensorflow.python.keras.datasets import cifar100
from tensorflow.python import keras
import tensorflow as tf
from tensorflow.python.keras.applications import VGG16
class CNNCifar(object):
# 定义模型
model = keras.Sequential([
# 卷积层1 32个 5*5*3的filter strides=1 padding=same
keras.layers.Conv2D(32, kernel_size=5, strides=1, padding="same", data_format="channels_last", activation=tf.nn.relu, kernel_regularizer=keras.regularizers.l2(0.01)),
# 池化层1
keras.layers.MaxPool2D(pool_size=2, strides=2),
# 卷积层2
keras.layers.Conv2D(64, kernel_size=5, strides=1, padding="same", data_format="channels_last", activation=tf.nn.relu),
keras.layers.MaxPool2D(pool_size=2, strides=2),
# 全连接层 先扁平化
keras.layers.Flatten(),
# 1024个神经网络 全连接层
keras.layers.Dense(1024, activation=tf.nn.relu),
# 加入dropout
keras.layers.Dropout(0.2),
# 100个神经元网络
keras.layers.Dense(100, activation=tf.nn.softmax)
])
def __init__(self):
(self.x_train, self.y_train), (self.x_test, self.y_test) = cifar100.load_data()
# 进行数据归一化
self.x_train = self.x_train / 255
self.x_test = self.x_test / 255
def compile(self):
CNNCifar.model.compile(optimizer=keras.optimizers.Adam(), loss=keras.losses.sparse_categorical_crossentropy, metrics=["accuracy"])
return None
def fit(self):
CNNCifar.model.fit(self.x_train, self.y_train, epochs=1, batch_size=64)
def evaluate(self):
test_loss, test_acc = CNNCifar.model.evaluate(self.x_test, self.y_test)
print("test:", test_loss, test_acc)
if name == ‘main’:
cnn = CNNCifar()
# print(CNNCifar.model.summary())
cnn.compile()
cnn.fit()