Getting the Error when running a image classification

I am giving my code and the model summary, i have dataset in format ‘…/train(normal, abnormal)’. But each time i am finding the error. how to resolve?
import numpy as np
import matplotlib.pyplot as plt
import glob
import cv2

from keras.models import Model
from keras.layers import Input, Dense, Flatten, Conv2D, MaxPooling2D
from keras.layers import BatchNormalization
import os
basepath = “F:/Research_k/DATASET_WORK/Chest X-Ray Images (Pneumonia)_dataset/”
print(os.listdir(basepath))

SIZE = 128
train_images = []
train_labels = []
for directory_path in glob.glob(basepath+“train/*”):
label = directory_path.split(“\”)[-1]
print(label)

print(directory_path)

for img_path in os.listdir(directory_path):

print(img_path)

    if img_path.split('.')[-1]=='jpeg':
        img = cv2.imread(directory_path+'/'+img_path, cv2.IMREAD_COLOR)       
        img = cv2.resize(img, (SIZE, SIZE))
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        train_images.append(img)
        train_labels.append(label)

train_images = np.array(train_images)
train_labels = np.array(train_labels)

test

test_images = []
test_labels = []
for directory_path in glob.glob(basepath+“val/*”):
fruit_label = directory_path.split(“\”)[-1]
for img_path in os.listdir(directory_path):
if img_path.split(‘.’)[-1]==‘jpeg’:
img = cv2.imread(directory_path+‘/’+img_path, cv2.IMREAD_COLOR)
img = cv2.resize(img, (SIZE, SIZE))
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
test_images.append(img)
test_labels.append(fruit_label)

test_images = np.array(test_images)
test_labels = np.array(test_labels)

#Encode labels from text to integers.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(test_labels)
test_labels_encoded = le.transform(test_labels)
le.fit(train_labels)
train_labels_encoded = le.transform(train_labels)

#Split data into test and train datasets (already split but assigning to meaningful convention)
x_train, y_train, x_test, y_test = train_images, train_labels_encoded, test_images, test_labels_encoded

###################################################################

Normalize pixel values to between 0 and 1

x_train, x_test = x_train / 255.0, x_test / 255.0

#One hot encode y values for neural network.
from keras.utils import to_categorical
y_train_one_hot = to_categorical(y_train)
y_test_one_hot = to_categorical(y_test)
##############################
activation = ‘sigmoid’
input_shape = (SIZE, SIZE, 3)

Define the input layer

inputs = Input(shape=input_shape)

Convolutional layers

x = Conv2D(32, 3, activation=activation, padding=‘same’, kernel_initializer=‘he_uniform’)(inputs)
x = BatchNormalization()(x)
x = Conv2D(32, 3, activation=activation, padding=‘same’, kernel_initializer=‘he_uniform’)(x)
x = BatchNormalization()(x)
x = MaxPooling2D()(x)
x = Conv2D(64, 3, activation=activation, padding=‘same’, kernel_initializer=‘he_uniform’)(x)
x = BatchNormalization()(x)
x = Conv2D(64, 3, activation=activation, padding=‘same’, kernel_initializer=‘he_uniform’)(x)
x = BatchNormalization()(x)
x = MaxPooling2D()(x)
x = Flatten()(x)

Add layers for deep learning prediction

x = Dense(128, activation=activation, kernel_initializer=‘he_uniform’)(x)
predictions = Dense(2, activation=‘softmax’)(x)

Make a new model combining both feature extractor and x

Create the model

model = Model(inputs=inputs, outputs=predictions)

cnn_model = Model(inputs=inputs, outputs=predictions)
cnn_model.compile(optimizer=‘rmsprop’,loss = ‘categorical_crossentropy’, metrics = [‘accuracy’])
print(cnn_model.summary())

Model: “functional_58”
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ Layer (type) ┃ Output Shape ┃ Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
│ input_layer_6 (InputLayer) │ (None, 128, 128, 3) │ 0 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ conv2d_24 (Conv2D) │ (None, 128, 128, 32) │ 896 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ batch_normalization_24 │ (None, 128, 128, 32) │ 128 │
│ (BatchNormalization) │ │ │
├─────────────────────

When i am running .fit i am finding an error, which i had not find anywhere how to resolve it. Please solve, i am attaching the error here also

#Train the CNN model
history = cnn_model.fit(x_train, y_train_one_hot, epochs=2, validation_data = (x_test, y_test_one_hot))

ERROR::: -

Epoch 1/2

AttributeError Traceback (most recent call last)
Input In [24], in
1 ##########################################
2 #Train the CNN model
----> 3 history = cnn_model.fit(x_train, y_train_one_hot, epochs=2, validation_data = (x_test, y_test_one_hot))

File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\src\utils\traceback_utils.py:123, in filter_traceback..error_handler(*args, **kwargs)
120 filtered_tb = _process_traceback_frames(e.traceback)
121 # To get the full stack trace, call:
122 # keras.config.disable_traceback_filtering()
→ 123 raise e.with_traceback(filtered_tb) from None
124 finally:
125 del filtered_tb

File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\src\backend\tensorflow\trainer.py:69, in TensorFlowTrainer.train_step(self, data)
67 if self.trainable_weights:
68 trainable_weights = self.trainable_weights
—> 69 gradients = tape.gradient(loss, trainable_weights)
71 # Update weights
72 self.optimizer.apply_gradients(zip(gradients, trainable_weights))

AttributeError: ‘str’ object has no attribute ‘base_dtype’

Every, time i am running a model for image classification i am getting this error, i have loaded the dataste having …/train(normal, pneumonia) with cv2, i am attaching some portion of my code:
train_images = []
train_labels = []
for directory_path in glob.glob(basepath+“train/*”):
label = directory_path.split(“\”)[-1]
print(label)

print(directory_path)

for img_path in os.listdir(directory_path):

print(img_path)

    if img_path.split('.')[-1]=='jpeg':
        img = cv2.imread(directory_path+'/'+img_path, cv2.IMREAD_COLOR)       
        img = cv2.resize(img, (SIZE, SIZE))
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        train_images.append(img)
        train_labels.append(label)

train_images = np.array(train_images)
train_labels = np.array(train_labels)

test

test_images = []
test_labels = []
for directory_path in glob.glob(basepath+“val/*”):
fruit_label = directory_path.split(“\”)[-1]
for img_path in os.listdir(directory_path):
if img_path.split(‘.’)[-1]==‘jpeg’:
img = cv2.imread(directory_path+‘/’+img_path, cv2.IMREAD_COLOR)
img = cv2.resize(img, (SIZE, SIZE))
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
test_images.append(img)
test_labels.append(fruit_label)

test_images = np.array(test_images)
test_labels = np.array(test_labels)

#Encode labels from text to integers.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(test_labels)
test_labels_encoded = le.transform(test_labels)
le.fit(train_labels)
train_labels_encoded = le.transform(train_labels)
#Split data into test and train datasets (already split but assigning to meaningful convention)
x_train, y_train, x_test, y_test = train_images, train_labels_encoded, test_images, test_labels_encoded

###################################################################

Normalize pixel values to between 0 and 1

x_train, x_test = x_train / 255.0, x_test / 255.0

#One hot encode y values for neural network.
from keras.utils import to_categorical
y_train_one_hot = to_categorical(y_train)
y_test_one_hot = to_categorical(y_test)
##############################
activation = ‘sigmoid’
input_shape = (SIZE, SIZE, 3)

Define the input layer

inputs = Input(shape=input_shape)

Convolutional layers

x = Conv2D(32, 3, activation=activation, padding=‘same’, kernel_initializer=‘he_uniform’)(inputs)
x = BatchNormalization()(x)
x = Conv2D(32, 3, activation=activation, padding=‘same’, kernel_initializer=‘he_uniform’)(x)
x = BatchNormalization()(x)
x = MaxPooling2D()(x)
x = Conv2D(64, 3, activation=activation, padding=‘same’, kernel_initializer=‘he_uniform’)(x)
x = BatchNormalization()(x)
x = Conv2D(64, 3, activation=activation, padding=‘same’, kernel_initializer=‘he_uniform’)(x)
x = BatchNormalization()(x)
x = MaxPooling2D()(x)
x = Flatten()(x)

Add layers for deep learning prediction

x = Dense(128, activation=activation, kernel_initializer=‘he_uniform’)(x)
predictions = Dense(2, activation=‘softmax’)(x)

Make a new model combining both feature extractor and x

Create the model

model = Model(inputs=inputs, outputs=predictions)

cnn_model = Model(inputs=inputs, outputs=predictions)
cnn_model.compile(optimizer=‘rmsprop’,loss = ‘categorical_crossentropy’, metrics = [‘accuracy’])
print(cnn_model.summary())
Model: “functional_58”
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┓
┃ Layer (type) ┃ Output Shape ┃ Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━┩
│ input_layer_6 (InputLayer) │ (None, 128, 128, 3) │ 0 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ conv2d_24 (Conv2D) │ (None, 128, 128, 32) │ 896 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ batch_normalization_24 │ (None, 128, 128, 32) │ 128 │
│ (BatchNormalization) │ │ │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ conv2d_25 (Conv2D) │ (None, 128, 128, 32) │ 9,248 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ batch_normalization_25 │ (None, 128, 128, 32) │ 128 │
│ (BatchNormalization) │ │ │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ max_pooling2d_12 (MaxPooling2D) │ (None, 64, 64, 32) │ 0 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ conv2d_26 (Conv2D) │ (None, 64, 64, 64) │ 18,496 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ batch_normalization_26 │ (None, 64, 64, 64) │ 256 │
│ (BatchNormalization) │ │ │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ conv2d_27 (Conv2D) │ (None, 64, 64, 64) │ 36,928 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ batch_normalization_27 │ (None, 64, 64, 64) │ 256 │
│ (BatchNormalization) │ │ │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ max_pooling2d_13 (MaxPooling2D) │ (None, 32, 32, 64) │ 0 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ flatten_6 (Flatten) │ (None, 65536) │ 0 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ dense_4 (Dense) │ (None, 128) │ 8,388,736 │
├────────────────────────────────────┼───────────────────────────────┼─────────────┤
│ dense_5 (Dense) │ (None, 2) │

Error: Epoch 1/2

AttributeError Traceback (most recent call last)
Input In [24], in
1 ##########################################
2 #Train the CNN model
----> 3 history = cnn_model.fit(x_train, y_train_one_hot, epochs=2, validation_data = (x_test, y_test_one_hot))

File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\src\utils\traceback_utils.py:123, in filter_traceback..error_handler(*args, **kwargs)
120 filtered_tb = _process_traceback_frames(e.traceback)
121 # To get the full stack trace, call:
122 # keras.config.disable_traceback_filtering()
→ 123 raise e.with_traceback(filtered_tb) from None
124 finally:
125 del filtered_tb

File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\keras\src\backend\tensorflow\trainer.py:69, in TensorFlowTrainer.train_step(self, data)
67 if self.trainable_weights:
68 trainable_weights = self.trainable_weights
—> 69 gradients = tape.gradient(loss, trainable_weights)
71 # Update weights
72 self.optimizer.apply_gradients(zip(gradients, trainable_weights))

AttributeError: ‘str’ object has no attribute ‘base_dtype’

Please give suggestions

@vivek_yadav

The error you’re encountering, “AttributeError: ‘str’ object has no attribute ‘base_dtype’,” is likely due to a mismatch in data types when passing the labels to the fit function.

In your case, the issue might be related to the labels (y_train_one_hot and y_test_one_hot) being of type string.

Here are a few suggestions we have for you:

  1. Confirm that the data types of your labels (y_train_one_hot and y_test_one_hot) are appropriate. They should be of numeric types, preferably integers. Use astype to convert the label arrays to integers before passing them to the fit function.
  2. Since you are using one-hot encoding for your labels, make sure the label encoding step is done correctly.

I have tried to modify version of your code to address these points:

# Encode labels from text to integers.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(test_labels)
test_labels_encoded = le.transform(test_labels)
le.fit(train_labels)
train_labels_encoded = le.transform(train_labels)

# Ensure one-hot encoding of labels
from keras.utils import to_categorical
y_train_one_hot = to_categorical(train_labels_encoded)
y_test_one_hot = to_categorical(test_labels_encoded)

# Convert labels to integers
y_train_one_hot = y_train_one_hot.astype(int)
y_test_one_hot = y_test_one_hot.astype(int)

# Train the CNN model
history = cnn_model.fit(x_train, y_train_one_hot, epochs=2, validation_data=(x_test, y_test_one_hot))

I have tried to label correctly as integers and then one-hot encoded. Also, it ensures that the label arrays have the correct data type before passing them to the fit function.

Try running the modified code, and it should resolve the AttributeError you’re facing. If you encounter any further issues, feel free to ask!

@BadarJaffer , Thank you for the suggestion, tried it just. But it gave the same Attribute error.
BTW, I have tried to classify the images using the different style to load the images as suggested in the Keras for loading with directory method ‘tf.keras.utils.image_dataset_from_directory  |  TensorFlow v2.14.0’ and by doing this now I am able to do the classification of the images. Once again thanks.

1 Like

@vivek_yadav I am glad you found the solution. Feel free to reach out if you need any help in the future. @vivek_yadav