Reputation: 11
I am using CNN to train a dataset of grayscale images (5 classes). The images are of size (100,100) and the pixel value is between 0-1 code :
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
import cv2
train = ImageDataGenerator(rescale=(100,100,1))
validation = ImageDataGenerator(rescale=(100,100,1))
train_dataset = train.flow_from_directory('C:/Users/abdul/OneDrive/Desktop/New folder/FYP/final/images/train',color_mode='grayscale')
validate_dataset = validation.flow_from_directory('C:/Users/abdul/OneDrive/Desktop/New folder/FYP/final/images/validate',color_mode='grayscale')
model = tf.keras.models.Sequential([
#convolutional layer
tf.keras.layers.Conv2D(32,(3,3), activation ="relu", input_shape = (100,100,1)),
# Flatten units
tf.keras.layers.Flatten(),
# Add a hidden layer with dropout
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dropout(0.5),
# Add an output layer with output units for all 10 digits
tf.keras.layers.Dense(4, activation="softmax")
])
# Train neural network
model.compile(
optimizer="adam",
loss="categorical_crossentropy",
metrics=["accuracy"]
)
model.fit(train_dataset, epochs=10,validation_data = validate_dataset)
Upvotes: 1
Views: 370
Reputation: 17239
There is some issue with your data generator. In rescale
you set wrongly the input size (probably) where you should set some factor that will be used to normalize your input. According to the doc:
rescale: rescaling factor. Defaults to None. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (after applying all other transformations).
And, by default, the target_size
is 256 x 256, but your model input is 100 x 100, so you need to specify that otherwise properly otherwise the data loader will generate an image with the shape of by its default value which is 256. According to the doc
target_size: tuple of integers (height, width), default: (256, 256). The dimensions to which all images found will be resized.
With these change, you should do as follows:
train = ImageDataGenerator(rescale=1/255.)
train_dataset = train.flow_from_directory('./train',
color_mode='grayscale',
class_mode='categorical', # one hot or 'sparse' if labels are integer
target_size=(100, 100))
Do the same to the validation part.
Upvotes: 1