Kaggle competition: Expedia Hotel Recommendations
cohen_kappa_score(true_labels, pred_labels )<compute_train_metric>
train = pd.read_csv('.. /input/train.csv',
dtype={'is_booking':bool,'srch_destination_id':np.int32, 'hotel_cluster':np.int32},
usecols=['srch_destination_id','is_booking','hotel_cluster'],
chunksize=1000000)
 aggs = []
print('-'*38)
 for chunk in train:
agg = chunk.groupby(['srch_destination_id',
'hotel_cluster'])['is_booking'].agg(['sum','count'])
 agg.reset_index(inplace=True)
 aggs.append(agg)
 print('.',end='')
 print('')
 aggs = pd.concat(aggs, axis=0)
 aggs.head()
class Metrics(Callback):
def on_train_begin(self, logs={}):
self.val_kappas = []
def on_epoch_end(self, epoch, logs={}):
X_val, y_val = self.validation_data[:2]
y_val = y_val.sum(axis=1)- 1
y_pred = self.model.predict(X_val)> 0.5
y_pred = y_pred.astype(int ).sum(axis=1)- 1
_val_kappa = cohen_kappa_score(
 y_val,
y_pred,
weights='quadratic' 
)
 self.val_kappas.append(_val_kappa)
 print(f"val_kappa: {_val_kappa:.4f}")
 if _val_kappa == max(self.val_kappas):
print("Validation Kappa has improved.Saving model.")
 self.model.save('model.h5')
 return<choose_model_class>
def most_popular(group, n_max=5):
relevance = group['relevance'].values
hotel_cluster = group['hotel_cluster'].values
most_popular = hotel_cluster[np.argsort(relevance)[::-1]][:n_max]
return np.array_str(most_popular)[1:-1]
densenet = DenseNet121(
 weights='.. /input/densenet-keras/DenseNet-BC-121-32-no-top.h5',
include_top=False,
input_shape=(224,224,3)
 )<choose_model_class>
most_pop = agg.groupby(['srch_destination_id'] ).apply(most_popular)
 most_pop = pd.DataFrame(most_pop ).rename(columns={0:'hotel_cluster'})
 most_pop.head()
def build_model() :
model = Sequential()
model.add(densenet)
 model.add(layers.GlobalAveragePooling2D())
 model.add(layers.Dropout(0.5))
model.add(layers.Dense(5, activation='sigmoid'))
model.compile(
 loss='binary_crossentropy',
optimizer=Adam(lr=0.00005),
metrics=['accuracy'] 
)
 return model<train_model>
test = pd.read_csv('.. /input/test.csv',
dtype={'srch_destination_id':np.int32},
usecols=['srch_destination_id'], )
kappa_metrics = Metrics()
history = model.fit_generator(
 data_generator,
steps_per_epoch=x_train.shape[0] / BATCH_SIZE,
epochs=15,
validation_data=(x_val, y_val),
callbacks=[kappa_metrics]
)<compute_train_metric>
test = test.merge(most_pop, how='left',left_on='srch_destination_id',right_index=True)
 test.head()
model.load_weights('model.h5')
 y_val_pred = model.predict(x_val)
 def compute_score_inv(threshold):
y1 = y_val_pred > threshold
y1 = y1.astype(int ).sum(axis=1)- 1
y2 = y_val.sum(axis=1)- 1
score = cohen_kappa_score(y1, y2, weights='quadratic')
 return 1 - score
simplex = scipy.optimize.minimize(
 compute_score_inv, 0.5, method='nelder-mead' 
)
 best_threshold = simplex['x'][0]<save_to_csv>
test.hotel_cluster.isnull().sum()
y_test = model.predict(x_test)> 0.5
y_test = y_test.astype(int ).sum(axis=1)- 1
test_df['diagnosis'] = y_test
test_df.to_csv('submission.csv',index=False )<set_options>
most_pop_all = agg.groupby('hotel_cluster')['relevance'].sum().nlargest(5 ).index
most_pop_all = np.array_str(most_pop_all)[1:-1]
most_pop_all
%reload_ext autoreload
%autoreload 2
%matplotlib inline<import_modules>
test.hotel_cluster.fillna(most_pop_all,inplace=True )
<set_options><EOS> 
test.hotel_cluster.to_csv('predicted_with_pandas.csv',header=True, index_label='id' )