人工智能Keras的第一个图像分类器(CNN卷积神经网络的图片识别)

日期:2023-02-27 19:05:06 / 人气:107

from keras.optimizers import Adamfrom sklearn.model_selection import train_test_splitfrom keras.preprocessing.image import img_to_arrayfrom keras.utils import to_categoricalfrom lenet import LeNetfrom imutils import pathsimport matplotlib.pyplot as pltimport numpy as npimport randomimport cv2import os初始化参数EPOCHS = 25 #学习的步数INIT_LR = 1e-3# 学习效率BS = 32# 每步学习的个数data = []# 寄存图片数据labels = []# 寄存图片标签imagePaths = sorted(list(paths.list_images("dataset\\")))# 遍历一切的图片random.seed(42)random.shuffle(imagePaths) # 打乱图片顺序初始化参数完成后,需求把一切的图片加载,停止图片数据的整理for imagePath in imagePaths:    # 加载图片    image = cv2.imread(imagePath)    image = cv2.resize(image, (28, 28)) # resize 到28*28 LeNet所需的空间尺寸    image = img_to_array(image) # 图片转换成array    data.append(image) # 保管图片数据    label = imagePath.split(os.path.sep)[-2] #获取图片标签    label = 1 if label == "snowman" else 0    labels.append(label) # 获取图片标签事后处置图片# 把图片数据变为【0.1】data = np.array(data, dtype="float") / 255.0labels = np.array(labels)# 设置测试数据与训练数据#运用75%的数据将数据划分爲训练和测试#用于训练的数据,其他25%用于测试(trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.25, random_state=42)# 标签转换成向量trainY = to_categorical(trainY, num_classes=2)testY = to_categorical(testY, num_classes=2)# 创立一个图像生成器对象,该对象在图像数据集上执行随机旋转,平移,翻转,修剪和剪切。#这使我们可以运用较小的数据集,但依然可以取得较高的后果aug = ImageDataGenerator(rotation_range=30, width_shift_range=0.1,                         height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,                         horizontal_flip=True, fill_mode="nearest")树立神经网络,停止神经网络训练#树立modelmodel = LeNet.build(width=28, height=28, depth=3, classes=2)opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS)model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["accuracy"])# 训练神经网络H = model.fit_generator(aug.flow(trainX, trainY, batch_size=BS),                        validation_data=(testX, testY), steps_per_epoch=len(trainX) // BS,                        epochs=EPOCHS, verbose=1)神经网络训练完成后,对神经网络训练的后果停止保管,以便前期运用预训练模型停止图片辨认保管模型,显示训练后果model.save("lenet.model") # 保管模型# 显示后果plt.style.use("ggplot")plt.figure()N = EPOCHSplt.plot(np.arange(0, N), H.history["loss"], label="train_loss")plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss")plt.plot(np.arange(0, N), H.history["acc"], label="train_acc")plt.plot(np.arange(0, N), H.history["val_acc"], label="val_acc")plt.title("Training Loss and Accuracy on snowman/Notsnowman")plt.xlabel("Epoch #")plt.ylabel("Loss/Accuracy")plt.legend(loc="lower left")plt.savefig("plot1.JPG")从训练后果可以看出,loss越来越小,精度越来越高,标明我们的神经网络模型是完全ok。若想失掉更好的训练数据,当然是运用少量的数据停止训练以上便是我们训练的神经网络模型,下期我们运用预训练模型,对图片停止辨认头条号:人工智能研讨所微@信搜索:启示AI科技,体验不一样的AI工具微信搜索小顺序:AI人工智能工具

作者:比特币分分彩官网




现在致电 5243865 OR 查看更多联系方式 →

比特币分分彩官网 版权所有