我正在使用keras和tensorflow学习CNN。我已经完成了图像的所有预处理,例如将图像转换为数组,调整大小并将其转换为灰度图像。之后,我将数据输入到模型中,但精度始终为50%。我做错什么了吗 ?
我还尝试过调整随机种子,批大小,减小数据集大小,并且还与优化程序一起使用,但没有任何帮助
count_dog=0
count_cat=0
#Reading cats and converting them from rgb to black and white
print('-------------------------')
for i in range(5000):
try:
caturl=r"C:/Users/Gowtam/Downloads/Compressed/PetImages/Cat/"""
caturl=caturl+str(i)+'.jpg'
img = cv2.imread(caturl,cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img,(50,50))
imglist.append(img_to_array(img))
except Exception as e:
print(str(e))
count_cat+=1
#Reading dogs and converting them frrom rgb to black and white
for i in range(5000):
try:
caturl=r"C:/Users/Gowtam/Downloads/Compressed/PetImages/Dog/"""
caturl=caturl+str(i)+'.jpg'
img = cv2.imread(caturl,cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img,(50,50))
imglist.append(img_to_array(img))
except Exception as e:
print(str(e))
count_dog+=1
print(count_cat,'',count_dog)
#now we have RGB to GREYSCALE converted images| lets create labels
print(len(imglist))
labels=[]
for i in range(5000-count_cat):
labels.append("cat")
for i in range(5000-count_dog):
labels.append("dog")
#one hot encoding..!
labelencoder = LabelEncoder()
labels50=(labelencoder.fit_transform(labels))
#now lets scramble the data(imgs) and labelencoder in same way
shuffimgs=shuffle(imglist,random_state=20)
shufflabels=shuffle(labels50,random_state=20)
#input shape of image (width,height,depth) depth means how many colors or channels that is 1 as b&W
#now lets normalize the shuffeled and resized imgs
fData=tf.keras.utils.normalize(shuffimgs)
#now lets build the model
#fData = fData[0].reshape(28,28,1)
model = Sequential()
#add model layers
model.add(Conv2D(32, (3,3), activation='relu', input_shape=(50,50,1)))
model.add(MaxPooling2D(2,2))
model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPooling2D(2,2))
model.add(Conv2D(128, (3,3), activation='relu'))
model.add(MaxPooling2D(2,2))
model.add(Flatten())
model.add(Dense(2, activation=tf.nn.softmax))
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(fData,labels50,epochs=5)
答案 0 :(得分:0)
尝试增加纪元数,也可以使用VGG16等预建模型。最后这是keras创作者的教程
https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html
答案 1 :(得分:0)
我给您的第一个建议是,当它是二进制分类时,它使用二进制交叉熵来弥补损失,因为作为Cat Vs Dog,您必须将其分类为一个或另一个,然后仅分类两个。 激活我建议使用S形,因为您需要两个值或0或1。 尝试这种方式。
model = Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(150,150,3)))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(128,(3,3),activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(128,(3,3),activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(512,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.summary()
model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy'])
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_directory,
target_size=(150,150),
batch_size=20,
class_mode='binary'
)
validation_generator = test_datagen.flow_from_directory(
validation_directory,
target_size=(150,150),
batch_size=20,
class_mode='binary'
)