请给出基于卷积神经网络的二分类识别玫瑰花和向日葵的python代码必须使得最终模型的评估得分不低于095并使之能输出accuracy和val_accuracy。使用如下如下代码进行数据划分:import numpy as npimport tensorflow as tffrom keraspreprocessingimage import ImageDataGeneratorimport osf
import numpy as np import tensorflow as tf from keras.preprocessing.image import ImageDataGenerator import os from PIL import Image from keras.utils import to_categorical from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
img_x = 64 img_y = 64
对读取图片进行预处理
def read_image(imageName): img = Image.open(imageName) img = img.resize((img_x, img_y), Image.ANTIALIAS) number_data = img.getdata() number_data_array = np.array(number_data) number_data_array = number_data_array.astype(float) number_data_normalize = number_data_array / 255
return number_data_normalize
images = [] labels = []
path = os.listdir("./mgh")
for textPath in path: for fn in os.listdir(os.path.join('mgh', textPath)): if fn.endswith('.jpg'): fd = os.path.join('./mgh', textPath, fn) images.append(read_image(fd)) labels.append(textPath) X = np.array(images) y = np.array(labels)
label_mapping = {label: i for i, label in enumerate(np.unique(y))} y = np.array([label_mapping[label] for label in y])
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=30)
Reshape the data to fit the model
x_train = x_train.reshape(x_train.shape[0], img_x, img_y, 1) x_test = x_test.reshape(x_test.shape[0], img_x, img_y, 1)
Convert labels to categorical
y_train = to_categorical(y_train) y_test = to_categorical(y_test)
Create the model
model = Sequential() model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(img_x, img_y, 1))) model.add(MaxPooling2D((2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2))) model.add(Flatten()) model.add(Dense(64, activation='relu')) model.add(Dense(2, activation='softmax'))
Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Train the model
model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))
Evaluate the model
_, accuracy = model.evaluate(x_test, y_test) print('Accuracy: %.2f' % (accuracy100)) _, val_accuracy = model.evaluate(x_test, y_test) print('Validation Accuracy: %.2f' % (val_accuracy100)
原文地址: https://www.cveoy.top/t/topic/h31n 著作权归作者所有。请勿转载和采集!