TensorFlow 图像分类器为每个图像返回相同的标签 [英] TensorFlow Image Classifier Returns the Same Label for each Image

查看:59
本文介绍了TensorFlow 图像分类器为每个图像返回相同的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据 https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e.我已经编写了所有代码,它似乎运行正常,只是在用于标记测试图像时,它使用相同的类标记它们.

I have made an image classifier to classify images of airplanes and rockets based on the tutorial at https://blog.francium.tech/build-your-own-image-classifier-with-tensorflow-and-keras-dc147a15e38e. I've written all of the code and it appears to function normally, except, when used to label testing images, it labels them all with the same class.

我查看了上面网页上的代码,它似乎与我的相符.

I've looked over the code on the webpage above, and it appears to match mine.

这是我的代码.我已经包含了所有内容,因为我不知道问题出在哪里:

Here is my code. I've included all of it because I don't know where the issue is:

import cv2
import numpy as np
import os
from random import shuffle
from tqdm import tqdm
import tensorflow as tf
from PIL import Image
import matplotlib.image as mpimg

from keras.models import Sequential
from keras.layers import *
from keras.optimizers import *
import matplotlib.pyplot as plt
#%matplotlib inline
import cv2

train_data = "C:/Users/Will Downs/image_training/training_data/"
test_data = "C:/Users/Will Downs/image_training/test_data/"

def one_hot_label(img):
  ohl = np.array([0, 0])
  label = img.split('.')[0]
  if label == 'Airplane':
     ohl = np.array([1,0])
  elif label == 'Rocket':
     ohl = np.array([0,1])
  return ohl

#This section loads and prepares the training and testing images:
def train_data_with_label():
  train_images = []
  for i in tqdm(os.listdir(train_data)):
    path = os.path.join(train_data, i)
    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    img = cv2.resize(img, (64,64))
    train_images.append([np.array(img), one_hot_label(i)])
  shuffle(train_images)
  return train_images

def test_data_with_label():
  test_images = []
  for i in tqdm(os.listdir(test_data)):
    path = os.path.join(test_data, i)
    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    img = cv2.resize(img, (64,64))
    test_images.append([np.array(img), one_hot_label(i)])
  shuffle(test_images)
  return test_images

#This section trains the model
training_images = train_data_with_label()
testing_images = test_data_with_label()
tr_img_data = np.array([i[0] for i in training_images]).reshape(-1,64,64,1)
tr_lbl_data = np.array([i[1] for i in training_images])

tst_img_data = np.array([i[0] for i in testing_images]).reshape(-1,64,64,1)
tst_lbl_data = np.array([i[1] for i in testing_images])

model = Sequential()

model.add(InputLayer(input_shape=[64,64,1]))
model.add(Conv2D(filters=32,kernel_size=5,strides=1,padding='same',activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

model.add(Conv2D(filters=50,kernel_size=5,strides=1,padding='same',activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

model.add(Conv2D(filters=80,kernel_size=5,strides=1,padding='same',activation='relu'))
model.add(MaxPool2D(pool_size=5,padding='same'))

model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512,activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(2,activation='softmax'))
optimizer = Adam(lr=1e-3)

model.compile(optimizer=optimizer,loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(x=tr_img_data, y=tr_lbl_data, epochs=50,batch_size=100)
model.summary()

#This section plots and labels the images
fig = plt.figure(figsize=(14,14))

for cnt, data in enumerate(testing_images[2:4]):

    y = fig.add_subplot(6,5, cnt+1)
    img = data[0]
    data = img.reshape(1,64,64,1)
    model_out = model.predict([data])

    if np.argmax(model_out == 1):
        str_label = "Airplane"
    else:
        str_label = "Rocket"

    y.imshow(img, cmap="gray")
    plt.title(str_label)
    y.axes.get_xaxis().set_visible(False)
    y.axes.get_yaxis().set_visible(False)

我希望程序将测试文件夹中的每个图像与预测标签一起绘制,但相反,它为所有图像绘制了具有相同标签的每个图像,无论是飞机"还是火箭".

I expected the program to plot each image in the testing folder along with a predicted label, but instead, it plotted each image with the same label for all of them, either "Airplane" or "Rocket."

推荐答案

bug 是由这一行引起的,if np.argmax(model_out == 1):.请将其更改为 if np.argmax(model_out) == 1:.在您发布的博客中,它们是第二个.

The bug is caused by this line, if np.argmax(model_out == 1):. Please change it to if np.argmax(model_out) == 1:. In the blog you post, they are the second one.

这篇关于TensorFlow 图像分类器为每个图像返回相同的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆