import tensorflow
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.text import text_to_word_sequence
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from keras.layers import Input
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Embedding, LSTM, Concatenate
from keras.models import Model
import os
from google.colab import drive
drive.mount('/content/drive')
!unzip /content/drive/MyDrive/DATACOLAB/ImagesPart1.zip
!unzip -q /content/drive/MyDrive/DATACOLAB/ImagesPart2.zip -d ImagesPart1
!mkdir AKRAPO7
!unzip -q /content/drive/MyDrive/DATACOLAB/train_gt_t13.zip -d AKRAPO7
if os.path.exists(dossier_source):
for fichier in os.listdir(dossier_source):
chemin_source = os.path.join(dossier_source, fichier)
chemin_destination = os.path.join(dossier_destination, fichier)
try:
shutil.move(chemin_source, chemin_destination)
except FileNotFoundError:
print(f"Le fichier {chemin_source} n'a pas été trouvé.")
except shutil.Error as e:
print(f"Erreur lors du déplacement du fichier {chemin_source} : {str(e)}")
except Exception as e:
print(f"Une erreur inattendue s'est produite lors du déplacement du fichier {chemin_source} : {str(e)}")
try:
os.rmdir(dossier_source)
except OSError as e:
print(f"Erreur lors de la suppression du dossier {dossier_source} : {str(e)}")
except Exception as e:
print(f"Une erreur inattendue s'est produite lors de la suppression du dossier {dossier_source} : {str(e)}")
# Extensions de fichiers d'images prises en charge
image_extensions = (".jpg", ".jpeg", ".png", ".gif",".txt")
# Parcourir les fichiers dans le dossier source
for filename in os.listdir(source_folder):
if filename.lower().endswith(image_extensions):
# Extraire le numéro d'index de l'image à partir du nom de fichier
index = int(filename.split("_")[2].split(".")[0])
# Trouver le dossier de destination correspondant à l'index
for range_, folder_name in language_ranges.items():
if range_[0] <= index <= range_[1]:
destination_folder = os.path.join(source_folder, folder_name)
break
# Créer le dossier de destination s'il n'existe pas
os.makedirs(destination_folder, exist_ok=True)
# Déplacer l'image vers le dossier de destination
source_path = os.path.join(source_folder, filename)
destination_path = os.path.join(destination_folder, filename)
shutil.move(source_path, destination_path)
Assistant
Exemple d'utilisation
source_folder = "ImagesPart1"
separate_images_by_language(source_folder)
source_folder = "AKRAPO7"
separate_images_by_language(source_folder)
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
import os
Définition de la taille du batch
batch_size = 32
Chargement des données d'images
train_datagen = ImageDataGenerator(rescale=1./255)
x_train = train_datagen.flow_from_directory(
"/content/ImagesPart1/French",
target_size=(224, 224),
batch_size=batch_size,
class_mode=None,
shuffle=False # Ajout de shuffle=False pour garder l'ordre des fichiers
)
Chargement des données de texte
y_train = []
for root, dirs, files in os.walk("/content/AKRAPO7/French/"):
for file in sorted(files): # Tri des fichiers pour correspondre à l'ordre des images
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
text = f.read()
y_train.append(text)
Tokenisation et encodage des textes de sortie
tokenizer = Tokenizer()
tokenizer.fit_on_texts(y_train)
y_train_sequences = tokenizer.texts_to_sequences(y_train)
y_train_padded = pad_sequences(y_train_sequences)
y_train_categorical = to_categorical(y_train_padded, num_classes=len(tokenizer.word_index) + 1)
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
import os
Définition de la taille du batch
batch_size = 32
Langue sélectionnée
language = "French"
Chargement des données d'images
image_dir = f"/content/ImagesPart1/{language}"
if not os.path.exists(image_dir):
print(f"Le dossier d'images pour la langue {language} n'existe pas : {image_dir}")
exit()
train_datagen = ImageDataGenerator(rescale=1./255)
x_train = train_datagen.flow_from_directory(
image_dir,
target_size=(224, 224),
batch_size=batch_size,
class_mode=None,
shuffle=False # Ajout de shuffle=False pour garder l'ordre des fichiers
)
Chargement des données de texte
text_dir = f"/content/AKRAPO7/{language}/"
if not os.path.exists(text_dir):
print(f"Le dossier de textes pour la langue {language} n'existe pas : {text_dir}")
exit()
y_train = []
for root, dirs, files in os.walk(text_dir):
for file in sorted(files): # Tri des fichiers pour correspondre à l'ordre des images
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
text = f.read()
y_train.append(text)
def load_text_data(directory):
text_data = []
for root, dirs, files in os.walk(directory):
for file in sorted(files):
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
text = f.read()
text_data.append(text)
return text_data
text_data = load_text_data('/content/AKRAPO7')
Tokeniser et encoder les textes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(text_data)
sequences = tokenizer.texts_to_sequences(text_data)
max_length = max([len(seq) for seq in sequences])
padded_sequences = pad_sequences(sequences, maxlen=max_length, padding='post')
x = Conv2D(32, (3, 3), activation='relu')(image_input)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = Flatten()(x)
x = Dense(64, activation='relu')(x)
Branche du modèle de texte
y = Embedding(len(tokenizer.word_index) + 1, 128)(text_input)
y = LSTM(64)(y)
1 frames
/usr/local/lib/python3.10/dist-packages/keras/src/utils/traceback_utils.py in error_handler(*args, **kwargs)
68 # To get the full stack trace, call:
69 # tf.debugging.disable_traceback_filtering()
---> 70 raise e.with_traceback(filtered_tb) from None
71 finally:
72 del filtered_tb
/usr/local/lib/python3.10/dist-packages/keras/src/engine/data_adapter.py in select_data_adapter(x, y)
1103 if not adapter_cls:
1104 # TODO(scottzhu): This should be a less implementation-specific error.
-> 1105 raise ValueError(
1106 "Failed to find data adapter that can handle input: {}, {}".format(
1107 _type_name(x), _type_name(y)
ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'numpy.ndarray'>", "<class 'keras.src.preprocessing.image.DirectoryIterator'>"}), <class 'numpy.ndarray'>
The error you're encountering stems from an attempt to pass a combination of data types that TensorFlow's model.fit() method doesn't recognize how to handle directly, specifically mixing a DirectoryIterator object for the image data and a NumPy array for the padded sequences (text data).
The primary issue is the attempt to jointly train the model using both image data generated on-the-fly by ImageDataGenerator.flow_from_directory() and preprocessed padded sequences from text data. While you correctly processed both data types, the way they are fed into the model for training needs a bit of adjustment.
To resolve this error and proceed with training, consider the following approach:
Synchronize Data: Ensure the images and text data are synchronized correctly. This means each image should have a corresponding textual input.
Custom Data Generator: The easiest way to handle this situation is by creating a custom generator that yields batches of image data and text data simultaneously. This way, the model receives inputs in the format it expects.
Here's an illustrative approach for creating a custom generator:
import numpy as np
def custom_data_generator(image_data_generator, text_sequences, batch_size):
num_samples = len(text_sequences)
while True:
for offset in range(0, num_samples, batch_size):
batch_images = next(image_data_generator) # Generate a batch of images
batch_texts = text_sequences[offset:offset+batch_size] # Get the corresponding batch of text sequences
yield [batch_images, batch_texts], batch_texts # Yield image and text data as input; text sequences as output
# Create the custom generator
batch_size = 32
custom_generator = custom_data_generator(x_train, padded_sequences, batch_size)
# Assuming `model` is properly set up to accept image and text inputs,
# you can now use the custom generator in `model.fit()`:
model.fit(
custom_generator,
epochs=epochs,
steps_per_epoch=len(padded_sequences) // batch_size
)
Few important remarks:
Ensure the synchronization of image and text data, i.e., each image has a corresponding text.
The custom_data_generator is designed to yield batches of image and text data together, making it compatible with the model's expected input format.
This solution presumes that x_train, your image data generator, is yielding images in the correct sequence that corresponds to the textual data in padded_sequences. If your data isn't naturally ordered (e.g., images and texts are shuffled but still correspond correctly), you might need to implement additional logic to ensure alignment between them.
Remember, handling multimodal data (like images and text in your case) often requires careful preprocessing and data feeding strategies to ensure that the data corresponding to different modes is correctly aligned and bundled for model training.