import pandas as pd import tensorflow as tf from tensorflow import keras from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.image import ImageDataGenerator import numpy as np import importlib # these packages are for special losses and augmentation, if not installed and used it's ok to not import them try: import coral_ordinal as coral from training.CornOrdinalLoss import CornOrdinalCrossEntropyWeights import tensorflow_addons as tfa except ImportError: pass # - from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True # + # gpus = tf.config.experimental.list_physical_devices('GPU') # tf.config.experimental.set_memory_growth(gpus[0], True) # - class CNNClassificationModelPredict(): def __init__(self, trained_model_path, requires_preprocessing=False, base_model_type='xception'): # """ # :param trained_model_path: str # path to save model or checkpoint to load from # :param requires_preprocessing: bool # in case the model doesn't have the preprocessing as the first layer choose True # :param base_model_type: str # in case preprocessing is required, the model architecture from which to get the preprocesor # """ self.model = load_model(trained_model_path) if requires_preprocessing: # the older model did not include preprocessing self.preprocessing_function = getattr(importlib.import_module(f"keras.applications.{base_model_type}"), "preprocess_input") else: self.preprocessing_function=None def create_datagenerator(self, df_data, batch_size, subset, seed, validation_split): if subset in ['training', 'validation']: datagen = ImageDataGenerator(validation_split=validation_split) elif subset is None: datagen = ImageDataGenerator(validation_split=0.0) data_generator = datagen.flow_from_dataframe( dataframe=df_data, preprocessing_function=self.preprocessing_function, directory=None, x_col='local_image_path', y_col=None, target_size=list(self.model.layers[0].input.shape[1:3]), class_mode=None, batch_size=batch_size, shuffle=False, seed=seed, interpolation='nearest', validate_filenames=True, subset=subset ) return data_generator def predict_on_dataframe_data(self, df_data, batch_size=128, subset=None, steps=None, seed=400, validation_split=0.2): # """ # :param df_data: pd.DataFrame # a dataframe with the column 'image_local_path' # :param batch_size: int # prediction batch size # :param subset: str # takes training valuation or None. # training - the training subset with given seed and validation_split to examine how the model was fitting on our training data # validation - the validation subset with give seed and validation_split to examine fitting on data we used as valuation # None - all the data in the dataframe to classify new images # :param steps: int # how many batches to predict, None means all the subset # :param seed: int # the same seed used for training, only required if subset is train or val # :param validation_split: 0 < float < 1 # the same validation_split used for training, only required if subset is train or val # :returns results: pd.DataFrame # a dataframe with the image path, label index, and probability # """ data_generator = self.create_datagenerator(df_data, batch_size, subset, seed, validation_split) filenames = data_generator.filenames # get_predictions print('starting prediction') predictions = self.model.predict(data_generator, workers=4, use_multiprocessing=True, steps=steps) print(predictions) print(self.model.layers[-1]) if isinstance(self.model.layers[-1], coral.layer.CornOrdinal): predictions = coral.ordinal_softmax(predictions).numpy() # The coral predictions are ordinal (cumulative) logits, not probabilities or regular logits. predicted_label_idx=np.argmax(predictions,axis=1) predicted_label_prob=np.max(predictions,axis=1) # label2idx_dict = data_generator.class_indices # idx2label_dict = dict((v,k) for k,v in label2idx_dict.items()) results = pd.DataFrame({'local_image_path': filenames[:len(predicted_label_idx)], # 'true_label_idx': true_labels_idx, # 'true_label': [idx2label_dict[idx] for idx in true_labels_idx], 'predicted_label_idx': predicted_label_idx, # 'predicted_label': [idx2label_dict[idx] for idx in predicted_label_idx], 'predicted_label_prob': predicted_label_prob, 'probabilities': list(predictions) }) return results def predict_on_single_image_from_file(self, filename: str): img = keras.utils.load_img(filename, target_size=list(self.model.layers[0].input.shape[1:3])) img = np.array(img) img = np.expand_dims(img, axis=0) class_probabilities = self.model.predict(img) return class_probabilities def predict_on_single_image_array(self, img: np.array): img = tf.image.resize(tf.convert_to_tensor(img), list(self.model.layers[0].input.shape[1:3])) img = np.array(img) img = np.expand_dims(img, axis=0) class_probabilities = self.model.predict(img) return class_probabilities if __name__=="__main__": # interior quality example data_folder = 'image_data/interior_quality_data_clean/' df_data = pd.read_csv(data_folder + 'df_interior_quality_clean_bathroom_0.9_test.csv') df_data['local_image_path'] = data_folder + df_data['local_image_path'] ### predicting trained_model_path = 'training_info_iq_newer/resnet_v2_bathroom_p09_aug_ce/model.1-04-0.80.h5' classifier = CNNClassificationModelPredict(trained_model_path, requires_preprocessing=False) res = classifier.predict_on_dataframe_data(df_data, batch_size=128, subset=None) res.to_csv('training_info_iq_newer/resnet_v2_bathroom_p09_aug_ce/iq_mcmakler.csv') # rooms # df_data = pd.read_csv('image_data/room_mcmakler_testing_images/mcmakler_test_rooms_manual_labels.csv') # df_data = pd.read_csv('training_csvs\df_junk_images_removed_corrupt.csv') # df_data = pd.read_csv('training_csvs/iq_training/df_interior_quality_old_norm_lux_removed_corrupt.csv', low_memory=False) # df_data = pd.read_csv('training_csvs/iq_training/df_interior_quality_clean.csv', low_memory=False) # df_data = pd.read_csv('image_data/room_mcmakler_testing_images/mcmakler_test_rooms_manual_labels.csv', low_memory=False) ### predicting # trained_model_path = 'training_info_rooms_new/resnet_v2_focal_aug_at_end/model.4-07-0.04.h5' # classifier = CNNClassificationModelPredict(trained_model_path, requires_preprocessing=False, base_model_type='densenet') # res = classifier.predict_on_dataframe_data(df_data, batch_size=128, subset=None) # res.to_csv('training_info_rooms_new/resnet_v2_focal_aug_at_end/mcmakler_test_rooms_pred.csv')