我的TensorFlow模型始终以100%的知己来预测同一类。
首先简要说明一下我的设置:任务是对图像进行7类分类并从网络摄像头读取图像。为了训练,验证和测试模型,我使用了带有数据生成器的TensorFlow。
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(32,(3,3), activation='elu',input_shape=(image_heigth,image_width,3)))
model.add(tf.keras.layers.Conv2D(64,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(128,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(256,(3,3), activation='elu'))
model.add(tf.keras.layers.Conv2D(256,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(512,(3,3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512, activation='elu'))
model.add(tf.keras.layers.Dense(7, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.RMSprop(lr=1e-4), metrics=['acc'])
仅供参考,这是我的模型。培训,验证和测试使用以下代码完成:
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, rotation_range=40, shear_range=0.2,zoom_range=0.2, horizontal_flip=True)
validation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(image_heigth,image_width),batch_size=batch_size, class_mode='categorical', shuffle=True)
validation_generator = validation_datagen.flow_from_directory(validation_dir, target_size=(image_heigth,image_width), batch_size=5, class_mode='categorical')
for data_batch, labels_batch in train_generator:
print('Shape des Datenstapels:', data_batch.shape)
print('Shape des Klassenbzeichnungsstabels:', labels_batch.shape)
break
history = model.fit(train_generator,steps_per_epoch=steps_per_epoch, epochs=epochs, validation_data=validation_generator,validation_steps=10, callbacks=callback_list)
# Testing the Model
test_generator = test_datagen.flow_from_directory(test_dir, target_size=(image_heigth,image_width), batch_size=5, class_mode='categorical')
test_loss, test_acc = model.evaluate(test_generator, steps=5)
predictions = model.predict(test_generator)
image_batch, label_batch = next (test_generator)
我的正确分类率高达90%。我的损失函数下降到约0.3。调试测试并观察预测会得到期望值,例如[0.08; 0.06; 0.56; 0.04; 0.10; 0.09; 0.07]。
最后,我使用TensorFlow方法将模型另存为h5。
在另一个python程序中,我正在加载此h5,并希望预测网络摄像头图像。但是现在输出始终为[1.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0]。这是我如何执行此操作的代码:
import numpy as np
import cv2
import tensorflow as tf
model = tf.keras.models.load_model('/home/poppe/Dokumente/Models/Proto2.h5')
classes = ['One', 'two', 'three', 'four', 'five', 'six', 'seven']
model.summary()
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
rezised = cv2.resize(frame, (150, 150))
expandArrayImage = np.expand_dims(rezised, axis=0)
prediction = model.predict(expandArrayImage)
print (np.max(prediction))
print(classes[np.argmax(prediction)])
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
cap.release()
cv2.destroyAllWindows()
如您所见,我正在使用OpenCV从网络摄像头读取内容。
为了解决我的问题,我尝试了以下方法:将模型减少到最小->没有效果
将我的问题简化为二进制分类->无效(总是以100%预测两个类之一)
加载并预测单个图像->没有效果
在测试代码之后直接加载和预测单个图像(不必保存和加载模型)->没有效果,该图像是我的测试图像之一...通过测试该图像是否正确分类,加载它作为一个单一的图像,并使用预测方法,我有与bevor相同的错误。
因此,由于测试按预期运行,因此我认为我的数据或模型没有问题。将网络摄像头图像从OpenCV转换为TensorFlow模型有什么问题吗?
您还有其他想法可以尝试解决吗?
非常感谢!:)
cv2.VideoCapture().read()
将返回一个numpy数组,其值的范围为(0,255),但您的模型希望它们的范围为(0,1)
您可以在预期范围内传递图像,例如:
rezised = cv2.resize(frame, (150, 150)) / 255
expandArrayImage = np.expand_dims(rezised, axis=0)
# rest of the code
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句