Kaggle competition: Kannada MNIST
def run_training(fold_id, seed_id):
seed_everything(seed_id)
 test_ = test
model = Model(num_features, num_targets)
 model.load_state_dict(torch.load(f".. /input/nn-transferlearning-7seeds4248-10folds/SCORED_ONLY_SEED_{seed_id}_FOLD{fold_id}_.pth"))
model.to(DEVICE)
 x_test = test_[feature_cols].values
testdataset = TestDataset(x_test)
 testloader = torch.utils.data.DataLoader(testdataset, batch_size=BATCH_SIZE, shuffle=False)
 predictions = np.zeros(( len(test_), num_targets))
predictions = inference_fn(model, testloader, DEVICE)
 print(f"Pretrained_Model_Loaded_SCORED_ONLYSEED: {seed_id}, FOLD: {fold_id} ")
 return predictions
def run_k_fold(NFOLDS, seed_id):
predictions = np.zeros(( len(test), len(target_cols)))
 for fold_id in range(NFOLDS):
pred_ = run_training(fold_id, seed_id)
 predictions += pred_ / NFOLDS
return predictions<feature_engineering>
print(tf.__version__ )
predictions = np.zeros(( len(test), len(target_cols)))
 time_begin = time()
def Inference_Transfer_learning(predictions,SEEDS,NFOLDS):
for seed_id in SEEDS:
predictions_ = run_k_fold(NFOLDS, seed_id)
 predictions += predictions_ / len(SEEDS)
 return predictions
predictions = Inference_Transfer_learning(predictions,SEEDS,NFOLDS)
 time_diff = time() - time_begin
test[target_cols] = predictions
str(timedelta(seconds=time_diff))<save_to_csv>
train = pd.read_csv("/kaggle/input/Kannada-MNIST/train.csv")
 validation = pd.read_csv("/kaggle/input/Kannada-MNIST/Dig-MNIST.csv")
 train = train.append(validation)
 test = pd.read_csv("/kaggle/input/Kannada-MNIST/test.csv")
 sample_submission = pd.read_csv("/kaggle/input/Kannada-MNIST/sample_submission.csv" )
def to_submission_Transfer_learning(target_cols,test):
data_dir = '.. /input/lish-moa/'
sample_submission = pd.read_csv(data_dir + 'sample_submission.csv')
 sub_nn_transfer = sample_submission.drop(columns=target_cols ).merge(test[['sig_id']+target_cols], on='sig_id', how='left' ).fillna(0)
 sub_nn_transfer.to_csv('submission_nn_transfer.csv', index=False)
 return sub_nn_transfer
sub_nn_transfer = to_submission_Transfer_learning(target_cols,test)
 print(sub_nn_transfer.shape)
 display(sub_nn_transfer.head() )<set_options>
( train_label, train_features)=(train["label"], train.drop(["label"],axis=1)) 
(test_id, test_features)=(test["id"], test.drop(["id"],axis=1)) 
(train_x, train_y)=(train_features.values, train_label.values)
 test_x = test_features.values
%who DataFrame
del test, train
gc.collect()
%who DataFrame<load_from_csv>
train_x, valid_x, train_y, valid_y = train_test_split(train_x, train_y, test_size = 0.05, random_state=42 )
def readin_data_resnet() :
train_features = pd.read_csv('/kaggle/input/lish-moa/train_features.csv')
 train_drug = pd.read_csv('.. /input/lish-moa/train_drug.csv')
 non_ctl_idx = train_features.loc[train_features['cp_type']!='ctl_vehicle'].index.to_list()
train_features = train_features.drop(['sig_id','cp_type','cp_dose','cp_time'],axis=1)
 train_targets_scored = pd.read_csv('/kaggle/input/lish-moa/train_targets_scored.csv')
 targets_drug = train_targets_scored.merge(train_drug, on='sig_id')
 train_targets_scored = train_targets_scored.drop('sig_id',axis=1)
 labels_train = train_targets_scored.values
train_features = train_features.iloc[non_ctl_idx]
labels_train = labels_train[non_ctl_idx]
targets_drug = targets_drug.iloc[non_ctl_idx]
test_features = pd.read_csv('/kaggle/input/lish-moa/test_features.csv')
 test_features = test_features.drop(['sig_id','cp_dose','cp_time'],axis=1)
 json_file_path = '.. /input/ttestpcarfelogisticregression/main_predictors.json'
with open(json_file_path, 'r')as j:
predictors = json.loads(j.read())
 predictors = predictors['start_predictors']
cs = train_features.columns.str.contains('c-')
 gs = train_features.columns.str.contains('g-')
 return train_features,labels_train,test_features,predictors,cs,gs 
<compute_test_metric>
normalized_train_x = reshaped_train_x/255
normalized_valid_x = reshaped_valid_x/255
normalized_test_x = reshaped_test_x/255
train_labels = keras.utils.to_categorical(train_y, 10)
 valid_labels = keras.utils.to_categorical(valid_y, 10 )
def logloss(y_true, y_pred):
y_pred = tf.clip_by_value(y_pred,p_min,p_max)
 return -backend.mean(y_true*backend.log(y_pred)+(1-y_true)*backend.log(1-y_pred))
def resnet_preprocessor(train,test,cs,gs):
n_gs = 2
n_cs = 100
pca_cs = PCA(n_components = n_cs)
 pca_gs = PCA(n_components = n_gs)
 train_pca_gs = pca_gs.fit_transform(train[:,gs])
 train_pca_cs = pca_cs.fit_transform(train[:,cs])
 test_pca_gs = pca_gs.transform(test[:,gs])
 test_pca_cs = pca_cs.transform(test[:,cs])
 train_c_mean = train[:,cs].mean(axis=1)
 test_c_mean = test[:,cs].mean(axis=1)
 train_g_mean = train[:,gs].mean(axis=1)
 test_g_mean = test[:,gs].mean(axis=1)
 train = np.concatenate(( train,train_pca_gs,train_pca_cs,train_c_mean[:,np.newaxis]
,train_g_mean[:,np.newaxis]),axis=1)
 test = np.concatenate(( test,test_pca_gs,test_pca_cs,test_c_mean[:,np.newaxis],
test_g_mean[:,np.newaxis]),axis=1)
 scaler = preprocessing.QuantileTransformer(n_quantiles=100,random_state=0, output_distribution="normal")
 train = scaler.fit_transform(train)
 test = scaler.transform(test)
 return train, test 
<choose_model_class>
datagen_train = ImageDataGenerator(rotation_range=15,
width_shift_range = 0.2,
height_shift_range = 0.2,
shear_range = 25,
zoom_range = 0.4,)
 datagen_valid = ImageDataGenerator()
def resnet_model(n_features, n_features_2, n_labels, label_smoothing = 0.0005):
input_1 = layers.Input(shape =(n_features,), name = 'Input1')
 input_2 = layers.Input(shape =(n_features_2,), name = 'Input2')
 head_1 = Sequential([
layers.BatchNormalization() ,
layers.Dropout(0.25),
layers.Dense(512, activation="elu"),
layers.BatchNormalization() ,
layers.Dense(256, activation = "elu")
 ],name='Head1')
 input_3 = head_1(input_1)
 input_3_concat = layers.Concatenate()([input_2, input_3])
 head_2 = Sequential([
layers.BatchNormalization() ,
layers.Dropout(0.3),
layers.Dense(512, "relu"),
layers.BatchNormalization() ,
layers.Dense(512, "elu"),
layers.BatchNormalization() ,
layers.Dense(256, "relu"),
layers.BatchNormalization() ,
layers.Dense(256, "elu")
 ],name='Head2')
 input_4 = head_2(input_3_concat)
 input_4_avg = layers.Average()([input_3, input_4])
 head_3 = Sequential([
layers.BatchNormalization() ,
layers.Dense(256, kernel_initializer='lecun_normal', activation='selu'),
layers.BatchNormalization() ,
layers.Dense(n_labels, kernel_initializer='lecun_normal', activation='selu'),
layers.BatchNormalization() ,
layers.Dense(n_labels, activation="sigmoid")
 ],name='Head3')
 output = head_3(input_4_avg)
 model = Model(inputs = [input_1, input_2], outputs = output)
 model.compile(optimizer='adam', loss=losses.BinaryCrossentropy(label_smoothing=label_smoothing), metrics=logloss)
 return model<find_best_model_class>
model = Sequential()
model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(28, 28, 1)))
 model.add(BatchNormalization())
 model.add(Conv2D(64, kernel_size=3, activation='relu'))
model.add(BatchNormalization())
 model.add(Conv2D(64, kernel_size=5, padding='same', activation='relu'))
model.add(BatchNormalization())
 model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Dropout(0.2))
model.add(Conv2D(128, kernel_size=3, activation='relu'))
model.add(BatchNormalization())
 model.add(Conv2D(128, kernel_size=3, activation='relu'))
model.add(BatchNormalization())
 model.add(Conv2D(128, kernel_size=5, padding='same', activation='relu'))
model.add(BatchNormalization())
 model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Dropout(0.2))
model.add(Conv2D(256, kernel_size=3, activation='relu'))
model.add(BatchNormalization())
 model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Dropout(0.2))
model.add(Flatten())
 model.add(Dense(256))
model.add(BatchNormalization())
 model.add(Dense(128))
model.add(BatchNormalization())
 model.add(Dense(10, activation='softmax'))
model.summary()
def predict_resnet(train_features,test_features,labels_train, SEEDS, NFOLDS,cs,gs):
n_labels = labels_train.shape[1]
n_train = train_features.shape[0]
n_test = test_features.shape[0]
n_seeds = len(SEEDS)
 n_folds = NFOLDS
y_pred = np.zeros(( n_test,n_labels))
_,data_test = resnet_preprocessor(train_features.values,
test_features.drop('cp_type',axis=1 ).values,cs,gs)
 data_test_2 = test_features[predictors].values
for seed in SEEDS:
for fold in range(NFOLDS):
K.clear_session()
model = keras.models.load_model('/kaggle/input/resent-1841/TwoHeads_seed_'+str(seed)+'_fold_'+str(fold), custom_objects={'logloss':logloss})
 y_pred += model.predict([data_test,data_test_2])/(n_folds*n_seeds)
 print(f"Pretrained_Resnet_Model: {seed}, FOLD: {fold} ")
 return y_pred 
<predict_on_test>
lr = 2e-3
batch_size=128
epochs=50
learning_rate_reduction = ReduceLROnPlateau(monitor='val_loss',
patience=5,
verbose=1,
factor=0.2)
 earlystop = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=8 )
train_features,labels_train,test_features,predictors,cs,gs = readin_data_resnet()
p_min = 0.0005
p_max = 0.9995
DRUG_THRESH = 18
n_seeds = 7
np.random.seed(42)
 SEEDS = np.random.randint(0,100,size=n_seeds)
 NFOLDS = 10
test_pred_rs = predict_resnet(train_features,test_features,labels_train,SEEDS, NFOLDS,cs,gs )<save_to_csv>
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'] )
sub_rs = pd.read_csv('/kaggle/input/lish-moa/sample_submission.csv')
 sub_rs.iloc[:,1:] = np.zeros([test_pred_rs.shape[0],test_pred_rs.shape[1]])
 sub_rs.iloc[:,1:] = test_pred_rs
sub_rs.iloc[test_features['cp_type'] == 'ctl_vehicle',1:] = 0
sub_rs.to_csv('submission_rs.csv', index=False)
<create_dataframe>
history = model.fit(datagen_train.flow(normalized_train_x, train_labels, batch_size=batch_size),
epochs = epochs,
steps_per_epoch=normalized_train_x.shape[0] // batch_size,
validation_data =(normalized_valid_x,valid_labels),
shuffle=True,
callbacks=[learning_rate_reduction, earlystop] )
%who DataFrame
del train_features,labels_train,test_features,predictors,cs,gs
gc.collect()
%who DataFrame<normalization>
prediction = model.predict(normalized_test_x )
<groupby><EOS> 
test['label'] = np.argmax(prediction, axis=1)
 submission = test[['id', 'label']]
submission.to_csv("submission.csv",index=False )