import os.path
from keras.utils import Sequence
import PIL.Image
import keras.utils
import matplotlib.pyplot as plt
import numpy as np
import tensorflow
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import LabelEncoder
train_img_n = 0
test_img_n = 0
n = 8
batch_size = 24


def get_data(path, n):
global train_img_n
global test_img_n
train_img_path = []
train_label = []
test_img_path = []
test_label = []
All_Path_List = os.listdir(path)
for name in All_Path_List:
if name == ‘Training’:
Path_List_Tr = os.listdir(os.path.join(path, name))
for typ in Path_List_Tr:
typ_img = os.listdir(os.path.join(path, name, typ))[:n]

for i in range(len(typ_img)):
typ_img[i] = os.path.join(path, name, typ, typ_img[i])

train_img_path.extend(typ_img)
for j in range(len(typ_img)):
train_label.append(typ)
train_img_n += len(typ_img)

elif name == ‘Test’:
Path_List_Te = os.listdir(os.path.join(path, name))
for typ in Path_List_Te:
typ_img = os.listdir(os.path.join(path, name, typ))[:n]
for i in range(len(typ_img)):
typ_img[i] = os.path.join(path, name, typ, typ_img[i])
test_img_path.extend(typ_img)
for j in range(len(typ_img)):
test_label.append(typ)
test_img_n += len(typ_img)
train_img = []
for k in range(len(train_img_path)):
img_i = PIL.Image.open(train_img_path[k])

train_img.append(np.array(img_i).astype(float))
train_img = np.array(train_img)

test_img = []
for k in range(len(test_img_path)):
img_i = PIL.Image.open(test_img_path[k])
test_img.append(np.array(img_i).astype(float))
test_img = np.array(test_img)

return train_img, train_label, test_img, test_label
images_, labels_, images_test, labels_test = get_data(r’D:\Download\python.64\python保存地址-64\fruits-360’, n)
def display_no5_img(no5_imgs, labels_no5):
fig = plt.figure(figsize=(15, 15))
for i in range(71):
plt.subplot(11, 7, (i + 1))
plt.title(“{0}”.format(labels_no5[i]))
plt.imshow(no5_imgs[i])
plt.axis(“off”)
plt.show()
def prepare_data(images, labels, n_classes):
label_encoder = LabelEncoder()
label_encoder.fit(labels)
labels = label_encoder.transform(labels)
images = images[0:len(images) // batch_size * batch_size]
labels = labels[0:len(labels) // batch_size * batch_size]

images = np.resize(images, (len(images), 64, 64, 3))
train_x = np.array(images)
train_y = np.array(labels)

‘’‘indx = np.arange(0, train_y.shape[0])
random.shuffle(indx)
train_x = train_x[indx]
train_y = train_y[indx]’‘’
train_y = keras.utils.to_categorical(train_y, 81)
print(train_y.shape)
return train_x, train_y
def gen_batch_data(images, labels, n_classes, batch_size):
i = 0

x, y = prepare_data(images, labels, n_classes)

train_x = x.reshape(-1, batch_size, 64, 64, 3)
train_y = y.reshape(-1, batch_size, 81)
return train_x, train_y
# 数据迭代器类
class MyDataGenerator(Sequence):
def init(self, data, labels, batch_size):
self.data = data
self.labels = labels
self.batch_size = batch_size

def len(self):
# 返回迭代器的总批次数
return len(self.data) // self.batch_size

def getitem(self, index):
# 生成每个批次的数据和标签
batch_data = self.data[index * self.batch_size: (index + 1) * self.batch_size]
batch_labels = self.labels[index * self.batch_size: (index + 1) * self.batch_size]

return batch_data, batch_labels
print(“冉莹莹设计的卷积神经网络进行分类实验设计”)
model = Sequential()
model.add(keras.layers.Conv2D(32, kernel_size=(5, 5), activation=‘relu’, padding=‘same’,
input_shape=(64, 64, 3)))
model.add(keras.layers.MaxPool2D())

model.add(keras.layers.Conv2D(64, kernel_size=(5, 5), activation=‘relu’, padding=‘same’))
model.add(keras.layers.MaxPool2D())

model.add(keras.layers.Flatten())

model.add(Dense(1024, activation=‘relu’))
model.add(Dense(512, activation=‘relu’))
model.add(keras.layers.Dropout(0.5))

model.add(Dense(81, activation=‘softmax’))
model.summary()

model.compile(loss=‘categorical_crossentropy’, metrics=[‘accuracy’])

ckpt = “model.hdf5”
checkpoint = tensorflow.keras.callbacks.ModelCheckpoint(‘./’ + ckpt, monitor=‘val_loss’,
save_weights_only=False,
verbose=1, save_best_only=True)

batch_num = train_img_n // batch_size
x, y = prepare_data(images_, labels_, None)
batch = MyDataGenerator(x, y, batch_size)
# batch_val = gen_batch_data(images_test, labels_test, None, batch_size)
h = model.fit_generator(batch, steps_per_epoch=batch_num, epochs=5, callbacks=[checkpoint], workers=4,
use_multiprocessing=False)
model.save_weights(‘models.hdf5’)写明你是怎么做的，设置了哪些参数，参数值是多少？操作结果见“XXX程序”，程序执行结果“XXX图”，对操作结果的分析等