def load_data(): # 加载数据集 with open('D:/浏览器下载/cifar-100-python/cifar-100-python/train', 'rb') as f: data_dict = pickle.load(f, encoding='bytes') x_train = data_dict[b'data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1) y_train = data_dict[b'fine_labels'] with open('D:/浏览器下载/cifar-100-python/cifar-100-python/test', 'rb') as f: data_dict = pickle.load(f, encoding='bytes') x_test = data_dict[b'data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1) y_test = data_dict[b'fine_labels'] # 归一化图像数据 x_train = x_train / 255.0 x_test = x_test / 255.0 # 将标签进行one-hot编码 num_classes = 100 y_train = to_categorical(y_train, num_classes) y_test = to_categorical(y_test, num_classes) return x_train, y_train, x_test, y_test # 加载数据 x_train, y_train, x_test, y_test = load_data() # 数据增强 train_datagen = ImageDataGenerator( rotation_range=20, horizontal_flip=True, zoom_range=0.2, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, fill_mode='nearest') train_datagen.fit(x_train) # 增加回调函数 callbacks = [ EarlyStopping(monitor='val_loss', patience=10, verbose=1), ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, verbose=1) ] 请在此代码基础上使用tensorflow2.0版本创建神经网络,并给出最终代码
时间: 2024-03-30 07:37:15 浏览: 120
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
# 加载数据集
def load_data():
with open('D:/浏览器下载/cifar-100-python/cifar-100-python/train', 'rb') as f:
data_dict = pickle.load(f, encoding='bytes')
x_train = data_dict[b'data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
y_train = data_dict[b'fine_labels']
with open('D:/浏览器下载/cifar-100-python/cifar-100-python/test', 'rb') as f:
data_dict = pickle.load(f, encoding='bytes')
x_test = data_dict[b'data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
y_test = data_dict[b'fine_labels']
# 归一化图像数据
x_train = x_train / 255.0
x_test = x_test / 255.0
# 将标签进行one-hot编码
num_classes = 100
y_train = tf.keras.utils.to_categorical(y_train, num_classes)
y_test = tf.keras.utils.to_categorical(y_test, num_classes)
return x_train, y_train, x_test, y_test
# 创建神经网络
def create_model():
model = Sequential()
# 卷积层
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', padding='same', input_shape=(32, 32, 3)))
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# 全连接层
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
return model
# 加载数据
x_train, y_train, x_test, y_test = load_data()
# 数据增强
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rotation_range=20,
horizontal_flip=True,
zoom_range=0.2,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
fill_mode='nearest'
)
train_datagen.fit(x_train)
# 增加回调函数
callbacks = [
tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=1),
tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, verbose=1)
]
# 创建模型
model = create_model()
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
history = model.fit_generator(train_datagen.flow(x_train, y_train, batch_size=64),
epochs=100,
verbose=1,
validation_data=(x_test, y_test),
callbacks=callbacks)
# 评估模型
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
阅读全文