水果图像分类器(Python)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了水果图像分类器(Python)相关的知识,希望对你有一定的参考价值。
我正在尝试使用python编写水果图像分类器,尝试对7种水果进行分类。我的train_set有15077个图像,validation_set有4204个图像。我将代码编译了10个纪元,结果如下:
训练15077个样本,验证4204个样本时代1/1015077/15077 [==============================]-264s 17ms / step-损失:1.0652-精度:0.5325-val_loss :0.3722-val_accuracy:0.8428时代2/1015077/15077 [==============================]-256s 17ms / step-损失:0.4236-精度:0.8405-val_loss :0.2910-val_accuracy:0.9034时代3/1015077/15077 [==============================]-499s 33ms / step-损耗:0.2682-精度:0.9107-val_loss :0.3614-val_accuracy:0.8830时代4/1015077/15077 [==============================]-243s 16ms / step-损耗:0.2022-精度:0.9381-val_loss :0.0985-val_accuracy:0.9724时代5/1015077/15077 [==============================]-245s 16ms / step-损耗:0.1500-精度:0.9548-val_loss :0.1258-val_accuracy:0.9536时代6/1015077/15077 [==============================]-253s 17ms / step-损耗:0.1509-精度:0.9529-val_loss :0.1831-val_accuracy:0.9317时代7/1015077/15077 [==============================]-245s 16ms / step-损耗:0.1020-精度:0.9678-val_loss :0.2164-val_accuracy:0.9391时代8/1015077/15077 [==============================]-255s 17ms / step-损耗:0.0668-精度:0.9816-val_loss :0.3004-val_accuracy:0.9229时代9/1015077/15077 [==============================]-243s 16ms / step-损耗:0.1081-精度:0.9704-val_loss :1.4997-val_accuracy:0.8639时代10/1015077/15077 [==============================]-240s 16ms / step-损耗:0.0765-精度:0.9784-val_loss :0.1763-val_accuracy:0.9424测试损失:0.17632227091173225测试精度:0.9424358010292053我不知道为什么准确性就像罪恶之波一样?我认为它应该增加每个时代。您对修改代码有什么建议吗?感谢您的回复。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import cv2
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.layers import LSTM, Input, TimeDistributed
from keras.models import Model
from keras.optimizers import RMSprop, SGD
# Import the backend
from keras import backend as K
dataDirTrain = "C:/Users/TCSEAKIN/Desktop/Py/AI-hack/AI/Training"
dataDirTest = "C:/Users/TCSEAKIN/Desktop/Py/AI-hack/AI/Test"
categories = ["Armut", "Cilek", "Elma_Kirmizi", "Elma_Yesil", "Mandalina", "Muz","Portakal"]
training_data = []
test_data = []
for category in categories:
path = os.path.join(dataDirTrain, category)
class_num = categories.index(category)
for img in os.listdir(path):
try:
imgTrainArray = cv2.imread(os.path.join(path,img))
newTrainArray = cv2.resize(imgTrainArray, (50, 50))
training_data.append([newTrainArray, class_num])
except Exception as e:
pass
for category in categories:
path = os.path.join(dataDirTest, category)
class_num = categories.index(category)
for img in os.listdir(path):
try:
imgTestArray = cv2.imread(os.path.join(path,img))
newTestArray = cv2.resize(imgTestArray, (50, 50))
test_data.append([newTestArray, class_num])
except Exception as e:
pass
X_train = []
x_test = []
y_train = []
y_test = []
for features, label in training_data:
X_train.append(features)
y_train.append(label)
for features, label in test_data:
x_test.append(features)
y_test.append(label)
X_train = np.array(X_train).reshape(-1, 50, 50, 3)
y_train = np.array(y_train).reshape(-1, 1)
x_test = np.array(x_test).reshape(-1, 50, 50, 3)
y_test = np.array(y_test).reshape(-1, 1)
X_train = X_train/255
x_test = x_test/255
from keras.utils import to_categorical
Y_train_one_hot = to_categorical(y_train)
Y_test_one_hot = to_categorical(y_test)
model_cnn = Sequential()
# First convolutional layer, note the specification of shape
model_cnn.add(Conv2D(64, kernel_size=(3, 3),activation='relu',input_shape=(50, 50, 3)))
model_cnn.add(Conv2D(128, (3, 3), activation='relu'))
model_cnn.add(MaxPooling2D(pool_size=(2, 2)))
model_cnn.add(Conv2D(256, (3, 3), activation='relu'))
model_cnn.add(MaxPooling2D(pool_size=(2, 2)))
model_cnn.add(Dropout(0.5))
model_cnn.add(Flatten())
model_cnn.add(Dense(128, activation='relu'))
model_cnn.add(Dropout(0.5))
model_cnn.add(Dense(64, activation='relu'))
model_cnn.add(Dropout(0.5))
model_cnn.add(Dense(7, activation='softmax'))
model_cnn.compile(loss="categorical_crossentropy",
optimizer="adam",
metrics=['accuracy'])
model_cnn.fit(X_train, Y_train_one_hot,
batch_size=64,
epochs=10,
verbose=1,
validation_data=(x_test, Y_test_one_hot))
score = model_cnn.evaluate(x_test, Y_test_one_hot, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
model_cnn.save("C:/Users/TCSEAKIN/Desktop/Training3.py"
实际上,这是正常行为。您可以降低学习率,以减少两次训练之间的准确性差异(如果需要,还可以尝试其他优化器)
此外,您应该标准化图像,以提高网络泛化知识的能力。在这里,您可以阅读有关规范化的更多信息:https://machinelearningmastery.com/how-to-normalize-center-and-standardize-images-with-the-imagedatagenerator-in-keras/
我认为训练准确性已经不错。您可以做几件事来提高验证准确性和整体性能。
- 使用
ImageDataGenerator
放大图像以获得更好的模型精度 - 使用较低的学习率或自适应学习率。
- 如下所示更新两行。最近发现,模型末尾的
softmax
层引入了数值不稳定性。
替换这两行来自
model_cnn.add(Dense(7, activation='softmax'))
model_cnn.compile(loss="categorical_crossentropy",
optimizer="adam",
metrics=['accuracy'])
to
model_cnn.add(Dense(7))
model_cnn.compile(loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),
optimizer="adam",
metrics=['accuracy'])
- [尝试调整一些超级参数,例如将batch_size从64更改为32,这会增加步骤数,尝试其他优化技术,增加时期数等。
希望有帮助。
以上是关于水果图像分类器(Python)的主要内容,如果未能解决你的问题,请参考以下文章