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’