2

hiya ive been making an image classifier and these source codes are from my university but when i use these codes i keep getting an error the source code was for a multiple image classifier i just changed the categorical to binary i think im doing something wrong but idk what

import numpy as np
import keras
from keras.layers import Dense,GlobalAveragePooling2D
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt

train_path=r'C:\Users\Acer\imagerec\Brain\TRAIN'
valid_path=r'C:\Users\Acer\imagerec\Brain\VAL'
test_path=r'C:\Users\Acer\imagerec\Brain\TEST'

class_labels=['yes', 'no']

train_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
valid_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
test_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5, shuffle=False)

base_model=keras.applications.xception.Xception(include_top=False)

x=base_model.output
x=GlobalAveragePooling2D
x=Dense(1,activation='sigmoid')(x)
predictions=Dense(2,activation='Adam')(x)

for layer in base_model.layers:
    layer.trainable=False

    model=Model(inputs=base_model.input,outputs=predictions)

    model.summary()

N=30

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

history=model.fit_generator(train_batches, steps_per_epoch=412,
                            validation_data=valid_batches,
                            validation_steps=35,epochs=N,verbose=1)

i get this error

2019-12-09 13:43:11.107461: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Traceback (most recent call last):
  File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\engine\base_layer.py", line 310, in assert_input_compatibility
    K.is_keras_tensor(x)
  File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\backend\tensorflow_backend.py", line 697, in is_keras_tensor
    str(type(x)) + '`. '
ValueError: Unexpectedly found an instance of type `<class 'type'>`. Expected a symbolic tensor instance.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Acer/PycharmProjects/condas/nyah.py", line 28, in <module>
    x=Dense(1,activation='sigmoid')(x)
  File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\backend\tensorflow_backend.py", line 75, in symbolic_fn_wrapper
    return func(*args, **kwargs)
  File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\engine\base_layer.py", line 446, in __call__
    self.assert_input_compatibility(inputs)
  File "C:\Users\Acer\Anaconda3\envs\condas\lib\site-packages\keras\engine\base_layer.py", line 316, in assert_input_compatibility
    str(inputs) + '. All inputs to the layer '
ValueError: Layer dense_1 was called with an input that isn't a symbolic tensor. Received type: <class 'type'>. Full input: [<class 'keras.layers.pooling.GlobalAveragePooling2D'>]. All inputs to the layer should be tensors.
Kenjie Thio-ac
  • 75
  • 1
  • 10

2 Answers2

2

Couple of things.
1) For a binary classification use sigmoid activation with binary_crossentropy loss.
2) adam is not an activation function. It's an optimizer.
3) You are trying to define the model inside a for loop.

More info, please refer to the Keras Documentation: https://keras.io/

Modified code:

import numpy as np
import keras
from keras.layers import Dense,GlobalAveragePooling2D
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt

train_path=r'C:\Users\Acer\imagerec\Brain\TRAIN'
valid_path=r'C:\Users\Acer\imagerec\Brain\VAL'
test_path=r'C:\Users\Acer\imagerec\Brain\TEST'

class_labels=['yes', 'no']

train_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
valid_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
test_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5, shuffle=False)

base_model=keras.applications.xception.Xception(include_top=False, input_shape=(299,299,3))

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1, activation='sigmoid')(x)
model=Model(inputs=base_model.input, outputs=x)


for layer in base_model.layers:
    layer.trainable=False

N=30

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

history=model.fit_generator(train_batches, steps_per_epoch=412,
                            validation_data=valid_batches,
                            validation_steps=35,epochs=N,verbose=1)
1

As mentioned above, there are several errors in your code.
Firstly, Adam is a optimizer and not an activation function.
Secondly, the model is being defined in a for loop.
Thirdly, the GlobalAveragePooling2D Layer does not have (x) behind so it is not being added to the model.
In addition, you do not need to set the layers to not be trainable in a for loop. You can just write base_model.trainable = False
Finally, it would also be better to use tf.keras with tensorflow 2.0.
See What is the difference between keras and tf.keras?

Below is the corrected code.

import numpy as np
from tensorflow import keras
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt

train_path=r'C:\Users\Acer\imagerec\Brain\TRAIN'
valid_path=r'C:\Users\Acer\imagerec\Brain\VAL'
test_path=r'C:\Users\Acer\imagerec\Brain\TEST'

class_labels=['yes', 'no']

train_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(train_path, target_size=(299,299),classes=class_labels,batch_size=5)
valid_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(valid_path, target_size=(299,299),classes=class_labels,batch_size=5)
test_batches=ImageDataGenerator(preprocessing_function=keras.applications.xception.preprocess_input)\
    .flow_from_directory(test_path, target_size=(299,299),classes=class_labels,batch_size=5, shuffle=False)

base_model=keras.applications.xception.Xception(include_top=False, input_shape=(299,299,3))

x=base_model.output
x=GlobalAveragePooling2D()(x)
x=Dense(1)(x)
x=Dense(2, activation='sigmoid')(x)
model=Model(inputs=base_model.input, outputs=x)


base_model.trainable = False

N=30

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

history=model.fit_generator(train_batches, steps_per_epoch=412,
                            validation_data=valid_batches,
                            validation_steps=35,epochs=N,verbose=1)
Jed Lim
  • 11
  • 2
  • `ValueError: A target array with shape (5, 2) was passed for an output of shape (None, 1) while using as loss `binary_crossentropy`. This loss expects targets to have the same shape as the output. Process finished with exit code 1 ` – Kenjie Thio-ac Dec 11 '19 at 05:27
  • What do the labels look like for each image? I just updated the code to fix what I think is the problem. – Jed Lim Dec 11 '19 at 05:41
  • hiya thanks for the edit i got no errors but it didnt run maybe my code is incomplete ill check in later – Kenjie Thio-ac Dec 11 '19 at 05:53