简体   繁体   English

使用 TensorFlow 的二进制图像分类

[英]Binary Image classification using TensorFlow

I am writing a code to classify between dogs and cats in python(Tensorflow) but the code is displaying this error:我正在编写一个代码来在 python(Tensorflow) 中对狗和猫进行分类,但代码显示此错误:

IndexError: index 0 is out of bounds for axis 0 with size 0索引错误:索引 0 超出轴 0 的范围,大小为 0

I am stuck here.我被困在这里。 Any help is appreciated.任何帮助表示赞赏。

Also can you please help me I cant figure out here how OneHotEncoder is working .I didn't understand the logic here.也请您帮帮我我无法弄清楚 OneHotEncoder 是如何工作的。我不明白这里的逻辑。 I spent a lot of time on the same.我花了很多时间在同样的事情上。

def reset_graph(seed=42):
    tf.reset_default_graph()
    tf.set_random_seed(seed)
    np.random.seed(seed)

reset_graph()
img_size = 64
num_channels = 3
img_size_flat = img_size * img_size * num_channels
img_shape = (img_size, img_size)
trainpath='C:\ProgramData\Anaconda3\train'
testpath='C:\ProgramData\Anaconda3\test'
labels = {'cats': 0, 'dogs': 1}
fc_size=32 #size of the output of final FC layer
num_steps=300
tf.logging.set_verbosity(tf.logging.INFO)

def read_images_classes(basepath,imgSize=img_size):
    image_stack = []
    label_stack = []
    for counter, l in enumerate(labels):
        path = os.path.join(basepath, l,'*g')
        for img in glob.glob(path):
            one_hot_vector = np.zeros(len(labels),dtype=np.int16)
            one_hot_vector[counter]=1
            image = cv2.imread(img)
            image_stack.append(im_resize)
            label_stack.append(labels[l])            
    return np.array(image_stack), np.array(label_stack)

X_train, y_train = read_images_classes(trainpath)
X_test, y_test = read_images_classes(testpath)b 
print('length of train image set',len(X_train))
print('X_data shape:', X_train.shape)
print('y_data shape:', y_train.shape)

fig1 = plt.figure() 
ax1 = fig1.add_subplot(2,2,1) 
img = cv2.resize(X_train[0],(64,64), interpolation=cv2.INTER_CUBIC)
ax1.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title(y_train[0])
plt.show()

IndexError: index 0 is out of bounds for axis 0 with size 0索引错误:索引 0 超出轴 0 的范围,大小为 0

It means you don't have the index you are trying to reference.这意味着您没有要引用的索引。

Since this is a binary classification problem, you don't required one_hot encoding for pre-processing labels.由于这是一个二元分类问题,因此预处理标签不需要 one_hot 编码。 if you have more than two labels then you can use one_hot encoding.如果您有两个以上的标签,则可以使用 one_hot 编码。

Please refer binary classification code using Tensorflow for Cats and Dogs Dataset请参考使用 Tensorflow for Cats and Dogs Dataset 的二进制分类代码

import os
import numpy as np
from keras import layers
import pandas as pd
from tensorflow.keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from tensorflow.keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from tensorflow.keras.models import Sequential
from tensorflow.keras import regularizers, optimizers
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator

import keras.backend as K

import keras.backend as K
K.set_image_data_format('channels_last')

from google.colab import drive
drive.mount('/content/drive')

train_dir  = '/content/drive/My Drive/Dogs_Vs_Cats/train'
test_dir = '/content/drive/My Drive/Dogs_Vs_Cats/test'

img_width, img_height = 300, 281
input_shape = img_width, img_height, 3

train_samples = 2000
test_samples = 1000
epochs = 30
batch_size = 32

train_datagen = ImageDataGenerator(
    rescale = 1. /255,
    shear_range = 0.2,
    zoom_range = 0.2,
    horizontal_flip = True)

test_datagen = ImageDataGenerator(
    rescale = 1. /255)

train_data = train_datagen.flow_from_directory(
    train_dir,
    target_size = (img_width, img_height),
    batch_size = batch_size,
    class_mode = 'binary')

test_data = test_datagen.flow_from_directory(
    test_dir,
    target_size = (img_width, img_height),
    batch_size = batch_size,
    class_mode = 'binary')


model = Sequential()

model.add(Conv2D(32, (7, 7), strides = (1, 1), input_shape = input_shape))
model.add(BatchNormalization(axis = 3))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2)))

model.add(Conv2D(64, (7, 7), strides = (1, 1)))
model.add(BatchNormalization(axis = 3))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2)))

model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss = 'binary_crossentropy',
            optimizer = 'rmsprop',
            metrics = ['accuracy'])

model.build(input_shape)
model.summary() 


model.fit_generator(
        train_data,
        steps_per_epoch = train_samples//batch_size,
        epochs = epochs,
        validation_data = test_data,
        verbose = 1,
        validation_steps = test_samples//batch_size)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM