修正%%time history = model.fit_generator錯誤

 原程式碼:%%time

history = model.fit_generator( train_generator, steps_per_epoch=100, epochs = 10, # epoch 100 validation_data = validation_generator, validation_steps = 50) 出現錯誤
<timed exec>:1: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.

修正成這樣就好了
import numpy as np from tensorflow.keras.utils import Sequence from tensorflow.keras.preprocessing.image import ImageDataGenerator class MyImageDataGenerator(Sequence): def __init__(self, data_directory, batch_size, target_size, shuffle=True): self.data_directory = data_directory self.batch_size = batch_size self.target_size = target_size self.shuffle = shuffle self.image_datagen = ImageDataGenerator( rescale=1.0 / 255.0, # Normalize pixel values between 0 and 1 shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) # Obtain a list of file names and corresponding labels from your data directory self.file_names, self.labels = self._get_file_names_and_labels() self.on_epoch_end() def __len__(self): return len(self.file_names) // self.batch_size def __getitem__(self, index): batch_indices = self.indices[index * self.batch_size:(index + 1) * self.batch_size] batch_file_names = [self.file_names[i] for i in batch_indices] batch_labels = [self.labels[i] for i in batch_indices] # Load and preprocess the images for the current batch batch_images, batch_labels = self._load_and_preprocess_images(batch_file_names, batch_labels) return batch_images, batch_labels def on_epoch_end(self): self.indices = np.arange(len(self.file_names)) if self.shuffle: np.random.shuffle(self.indices) def _get_file_names_and_labels(self): # Implement a function to retrieve file names and corresponding labels from your data directory # For example, you can use `os.listdir` to get file names and match them to their labels. # Return two lists: file_names and labels # Example: # file_names = [...] # List of file names # labels = [...] # List of corresponding labels # return file_names, labels pass def _load_and_preprocess_images(self, batch_file_names, batch_labels): # Implement a function to load and preprocess the images based on file names and labels # For example, you can use `ImageDataGenerator.flow_from_directory` to load images. # Make sure to preprocess the images (e.g., resizing) using the `target_size`. # Return the batch of preprocessed images and their corresponding labels. # Example: # batch_images = [...] # Numpy array of preprocessed images # batch_labels = [...] # Numpy array of corresponding labels # return batch_images, batch_labels pass

评论

此博客中的热门博文

修正input_img_data = np.random.random((1, 150, 150, 3)) * 20 + 128.

緣起