0

I am trying to use inception model to train my AI and i am getting the error

ValueError: Error when checking target: expected concatenate_3 to have 4 dimensions, but got array with shape (1862, 12)

Would you please help me about this? my code:

# example of creating a CNN with an inception module

from keras.models import Model
from keras.layers import Input
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers.merge import concatenate
from keras.utils import plot_model
 
    
model= Sequential()

# function for creating a naive inception block
def naive_inception_module(layer_in, f1, f2, f3):
    # 1x1 conv
    conv1 = Conv2D(f1, (1,1), padding='same', activation='relu')(layer_in)
    # 3x3 conv
    conv3 = Conv2D(f2, (3,3), padding='same', activation='relu')(layer_in)
    # 5x5 conv
    conv5 = Conv2D(f3, (5,5), padding='same', activation='relu')(layer_in)
    # 3x3 max pooling
    pool = MaxPooling2D((3,3), strides=(1,1), padding='same')(layer_in)
    # concatenate filters, assumes filters/channels last
    layer_out = concatenate([conv1, conv3, conv5, pool], axis=-1)
    return layer_out
 
# define model input
visible = Input(shape=(256, 256, 3))
# add inception module
layer = naive_inception_module(visible, 64, 128, 32)
# create model
model = Model(inputs=visible, outputs=layer)


# summarize model
model.summary()
# plot model architecture


optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)
model.compile(optimizer = optimizer, loss = "categorical_crossentropy", metrics = ["accuracy"])

checkpointer = ModelCheckpoint(filepath='saved_models/cnn_model_wo_aug_af.hdf5', 
                               verbose=1, save_best_only=True)
    
history = model.fit(train_tensors, train_targets, epochs = 20, validation_data = `(val_train,val_targets),callbacks=[checkpointer],batch_size = 64)`

[![Model][1]][1]

ValueError: Error when checking target: expected concatenate_3 to have 4 dimensions, but got array with shape (1862, 12)

Processing data for train_target:

import numpy as np
import pandas as pd
from glob import glob
import cv2
import matplotlib.pyplot as plt
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from tqdm import tqdm
import time
%matplotlib inline

from sklearn.datasets import load_files
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns

from keras.utils import np_utils
from keras.preprocessing import image
from keras.models import Sequential, model_from_json
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dropout, Flatten, Dense ,Input

from keras.optimizers import Adam ,RMSprop

def load_dataset(path):
    data=load_files(path)
    plant_files=np.array(data['filenames'])
    plant_targets=np_utils.to_categorical(np.array(data['target']),12)
    return plant_files,plant_targets

print('Loading Train Files and Targets')
train_files, train_targets = load_dataset(r'C:\Users\kaan\Documents\Plant_Seedlings_Classification-master\Plant_Seedlings_Classification-master\data')
print('Loading Complete!')
print('There are %d training plant images.' % len(train_files))

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(256, 256))
    # convert PIL.Image.Image type to 3D tensor with shape (256, 256, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 256, 256, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)
# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255

# do not change seed to reproduce my results
seed = 31
np.random.seed(seed)



# Split the train and the validation set
train_tensors, val_train, train_targets, val_targets = train_test_split(train_tensors,
                                              train_targets, 
                                              test_size=0.15,
                                              random_state=seed
                                             )


print(train_tensors.shape)
print(val_train.shape)
print(train_targets.shape)
print(val_targets.shape)
10
  • 2
    Your error tells you that there is an issue with the shape of your train_targets. Can you show us how you load and process them? Commented Jun 25, 2020 at 9:13
  • When i use different model, it works smoothly without any error. I just cant manage to use inception model. So i think train_targets are correct but I should somehow fix dimension of concatenate_3. Commented Jun 25, 2020 at 9:17
  • 2
    Your other model doesn't have the same output shape, this is why your train_targets work for it and not for the inception model. You can either reshape your train_targets or modify the output of your inception model. Commented Jun 25, 2020 at 9:21
  • So how do i reshape train_target in a way that fixs my problem? (I added the code) Commented Jun 25, 2020 at 9:42
  • 1
    Please include your code and not pictures of it, it makes the process way harder Commented Jun 25, 2020 at 10:58

1 Answer 1

1

You're doing a classification problem but your model doesn't output classes, you want to modify it to something along the lines of:

# ...
# Your model up to your concatenation layer (excluded)
concat = concatenate([conv1, conv3, conv5, pool], axis=-1)
flatten = Flatten()(concat)
# Maybe (surely) add a large Dense layer here to increase accuracy
layer_out = Dense(12, activation='softmax')(flatten)

return layer_out
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.