Spaces:
Runtime error

File size: 7,659 Bytes
33f3b1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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')