Kaggle competition: ASHRAE - Great Energy Predictor III
tr['WHERE'] = 'train'
chunk['WHERE'] = 'val'
sub['WHERE'] = 'test'
data = tr.append([chunk, sub] )<count_unique_values>
sub_path = ".. /input/ashrae-ensembling-1"
all_files = os.listdir(sub_path)
 all_files
print(tr.shape, chunk.shape, sub.shape, data.shape)
 print(tr.Patient.nunique() , chunk.Patient.nunique() , sub.Patient.nunique() ,
data.Patient.nunique() )<feature_engineering>
concat_sub['m_max'] = concat_sub.iloc[:, 1:].max(axis=1)
 concat_sub['m_min'] = concat_sub.iloc[:, 1:].min(axis=1)
 concat_sub['m_median'] = concat_sub.iloc[:, 1:].median(axis=1 )
data['min_week'] = data['Weeks']
data.loc[data.WHERE=='test','min_week'] = np.nan
data['min_week'] = data.groupby('Patient')['min_week'].transform('min' )<categorify>
cutoff_lo = 0.8
cutoff_hi = 0.2
base = data.loc[data.Weeks == data.min_week]
base = base[['Patient','FVC']].copy()
base.columns = ['Patient','min_FVC']
base['nb'] = 1
base['nb'] = base.groupby('Patient')['nb'].transform('cumsum')
 base = base[base.nb==1]
base.drop('nb', axis=1, inplace=True )<merge>
rank = np.tril(concat_sub.iloc[:,1:ncol].corr().values,-1)
 m_gmean = 0
n = 8
while rank.max() >0:
mx = np.unravel_index(rank.argmax() , rank.shape)
 m_gmean += n*(np.log(concat_sub.iloc[:, mx[0]+1])+ np.log(concat_sub.iloc[:, mx[1]+1])) /2
rank[mx] = 0
n += 1
data = data.merge(base, on='Patient', how='left')
 data['base_week'] = data['Weeks'] - data['min_week']
del base<data_type_conversions>
concat_sub['m_mean'] = np.exp(m_gmean/(n-1)**2 )
COLS = ['Sex','SmokingStatus']
FE = []
for col in COLS:
for mod in data[col].unique() :
FE.append(mod)
 data[mod] =(data[col] == mod ).astype(int )<feature_engineering>
concat_sub['meter_reading'] = concat_sub['m_mean']
concat_sub[['row_id', 'meter_reading']].to_csv('stack_mean.csv',
index=False, float_format='%.6f' )
data['age'] =(data['Age'] - data['Age'].min())/(data['Age'].max() - data['Age'].min())
 data['BASE'] =(data['min_FVC'] - data['min_FVC'].min())/(data['min_FVC'].max() - data['min_FVC'].min())
 data['week'] =(data['base_week'] - data['base_week'].min())/(data['base_week'].max() - data['base_week'].min())
 data['percent'] =(data['Percent'] - data['Percent'].min())/(data['Percent'].max() - data['Percent'].min())
 FE += ['age','percent','week','BASE']<filter>
concat_sub['meter_reading'] = concat_sub['m_median']
concat_sub[['row_id', 'meter_reading']].to_csv('stack_median.csv',
index=False, float_format='%.6f' )
tr = data.loc[data.WHERE=='train']
chunk = data.loc[data.WHERE=='val']
sub = data.loc[data.WHERE=='test']
del data<compute_test_metric>
concat_sub['meter_reading'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1), 1,
np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1),
0, concat_sub['m_median']))
concat_sub[['row_id', 'meter_reading']].to_csv('stack_pushout_median.csv',
index=False, float_format='%.6f' )
C1, C2 = tf.constant(70, dtype='float32'), tf.constant(1000, dtype="float32")
 def score(y_true, y_pred):
tf.dtypes.cast(y_true, tf.float32)
 tf.dtypes.cast(y_pred, tf.float32)
 sigma = y_pred[:, 2] - y_pred[:, 0]
fvc_pred = y_pred[:, 1]
sigma_clip = tf.maximum(sigma, C1)
 delta = tf.abs(y_true[:, 0] - fvc_pred)
 delta = tf.minimum(delta, C2)
 sq2 = tf.sqrt(tf.dtypes.cast(2, dtype=tf.float32))
metric =(delta / sigma_clip)*sq2 + tf.math.log(sigma_clip* sq2)
 return K.mean(metric)
 def qloss(y_true, y_pred):
qs = [0.2, 0.50, 0.8]
q = tf.constant(np.array([qs]), dtype=tf.float32)
 e = y_true - y_pred
v = tf.maximum(q*e,(q-1)*e)
 return K.mean(v)
 def mloss(_lambda):
def loss(y_true, y_pred):
return _lambda * qloss(y_true, y_pred)+(1 - _lambda)*score(y_true, y_pred)
 return loss
def make_model(nh):
z = L.Input(( nh,), name="Patient")
 x = L.Dense(100, activation="relu", name="d1" )(z)
 x = L.Dense(100, activation="relu", name="d2" )(x)
 p1 = L.Dense(3, activation="linear", name="p1" )(x)
 p2 = L.Dense(3, activation="relu", name="p2" )(x)
 preds = L.Lambda(lambda x: x[0] + tf.cumsum(x[1], axis=1),
name="preds" )([p1, p2])
 model = M.Model(z, preds, name="CNN")
 model.compile(loss=mloss(0.65), optimizer=tf.keras.optimizers.Adam(lr=0.1, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.01, amsgrad=False), metrics=[score])
 return model<prepare_x_and_y>
concat_sub['meter_reading'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1),
concat_sub['m_max'],
np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1),
concat_sub['m_min'],
concat_sub['m_mean']))
concat_sub[['row_id', 'meter_reading']].to_csv('stack_minmax_mean.csv',
index=False, float_format='%.6f' )
y = tr['FVC'].values
z = tr[FE].values
ze = sub[FE].values
nh = z.shape[1]
pe = np.zeros(( ze.shape[0], 3))
pred = np.zeros(( z.shape[0], 3))<choose_model_class>
concat_sub['meter_reading'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1),
concat_sub['m_max'],
np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1),
concat_sub['m_min'],
concat_sub['m_median']))
concat_sub[['row_id', 'meter_reading']].to_csv('stack_minmax_median.csv',
index=False, float_format='%.6f' )
<predict_on_test><EOS> 
concat_sub['meter_reading'] = concat_sub['mol0'].rank(method ='min')+ concat_sub['mol1'].rank(method ='min')+ concat_sub['mol2'].rank(method ='min')
 concat_sub['meter_reading'] =(concat_sub['meter_reading']-concat_sub['meter_reading'].min())/(concat_sub['meter_reading'].max() - concat_sub['meter_reading'].min())
 concat_sub.describe()
concat_sub[['row_id', 'meter_reading']].to_csv('stack_rank.csv', index=False, float_format='%.8f' )