Kaggle competition: University of Liverpool - Ion Switching
<SOS> metric: MacroFScore Kaggle data source: university-of-liverpool-ion-switching<prepare_output>
sns.set_style("whitegrid")
 ROW_PER_BATCH = 500000
submissions = np.zeros(( len(preds),2),dtype=int)
 for ix in range(preds.shape[0]):
submissions[ix][0] = test_index[ix]
submissions[ix][1] = np.argmax(preds[ix])
 print(submissions )<save_to_csv>
train = pd.read_csv('/kaggle/input/liverpool-ion-switching/train.csv')
 test = pd.read_csv('/kaggle/input/liverpool-ion-switching/test.csv')
 print('Shape of train is ',train.shape)
 print('Shape of test is ',test.shape )
submissions_pd = pd.DataFrame(data=submissions,columns=["id","label"])
 submissions_pd.head()
submissions_pd.to_csv("submissions.csv",index=False )<set_options>
train['batch'] = 0
for i in range(0, train.shape[0]//ROW_PER_BATCH):
train.iloc[i * ROW_PER_BATCH:(i+1)* ROW_PER_BATCH,3] = i
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.keras.backend.set_session(tf.Session(config=config)) 
<import_modules>
test['batch'] = 0
for i in range(0, test.shape[0]//ROW_PER_BATCH):
test.iloc[i * ROW_PER_BATCH:(i+1)* ROW_PER_BATCH,2] = i
from keras.layers import LeakyReLU
from keras.layers.normalization import BatchNormalization<load_from_csv>
train['type'] = 0
for i in range(train['batch'].nunique()):
median = train.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH].signal.median()
if(median < 0):
train.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH, train.columns.get_loc('type')] = 0
else:
train.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH, train.columns.get_loc('type')] = 1
test['type'] = 0
ROW_PER_BATCH = 100000
for i in range(test['batch'].nunique()):
median = test.iloc[i*ROW_PER_BATCH :(i+1)*ROW_PER_BATCH].signal.median()
if(median < 0):
test.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH, test.columns.get_loc('type')] = 0
else:
test.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH, test.columns.get_loc('type')] = 1
train = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv')
 test = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')
 sample_sub = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')
 dig = pd.read_csv('/kaggle/input/Kannada-MNIST/Dig-MNIST.csv' )<split>
a = 500000; b = a *2
print('Before: mean: {} std: {} median: {}'.format(train.signal[a:b].mean() , train.signal[a:b].std() ,train.signal[a:b].median()))
a=500000; b=600000
train['signal_undrifted'] = train.signal
train.loc[train.index[a:b],'signal_undrifted'] = train.signal[a:b].values - 3*(train.time.values[a:b] - 50)/10.
 a = 500000; b = a *2
print('After: mean: {} std: {} median: {}'.format(train.signal_undrifted[a:b].mean() , train.signal_undrifted[a:b].std() ,train.signal_undrifted[a:b].median()))
x_train = train.values[:,1:].reshape(train.shape[0], 28, 28, 1)
 x_train = x_train.astype('float32')
 x_train = x_train / 255.0
y_train = train.values[:,0]
x_train, x_valid, y_train, y_valid = train_test_split(x_train, y_train, test_size = 0.1, random_state=2019)
 x_test = test.values[:,1:].reshape(test.shape[0], 28, 28, 1)
 x_test = x_test.astype('float32')
 x_test = x_test / 255.0<categorify>
def f(x,low,high,mid): return -(( -low+high)/625)*(x-mid)**2+high -low
batch = 7; a = 500000*(batch-1); b = 500000*batch
train.loc[train.index[a:b],'signal_undrifted'] = train.signal.values[a:b] - f(train.time[a:b].values,-1.817,3.186,325)
 batch = 8; a = 500000*(batch-1); b = 500000*batch
train.loc[train.index[a:b],'signal_undrifted'] = train.signal.values[a:b] - f(train.time[a:b].values,-0.094,4.936,375)
 batch = 9; a = 500000*(batch-1); b = 500000*batch
train.loc[train.index[a:b],'signal_undrifted'] = train.signal.values[a:b] - f(train.time[a:b].values,1.715,6.689,425)
 batch = 10; a = 500000*(batch-1); b = 500000*batch
train.loc[train.index[a:b],'signal_undrifted'] = train.signal.values[a:b] - f(train.time[a:b].values,3.361,8.45,475 )
lb = preprocessing.LabelBinarizer()
y_train = lb.fit_transform(y_train)
 y_valid = lb.fit_transform(y_valid )<choose_model_class>
test['signal_undrifted'] = test.signal
start=500
a = 0; b = 100000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=510
a = 100000; b = 200000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=540
a = 400000; b = 500000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=560
a = 600000; b = 700000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=570
a = 700000; b = 800000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=580
a = 800000; b = 900000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 def f(x):
return -(0.00788)*(x-625)**2+2.345 +2.58
a = 1000000; b = 1500000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - f(test.time[a:b].values )
modelo = Sequential()
modelo.add(Conv2D(64,(3,3), padding='same', input_shape=(28, 28, 1)))
 modelo.add(BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform"))
modelo.add(LeakyReLU(alpha=0.1))
modelo.add(MaxPooling2D(2, 2))
modelo.add(Dropout(0.2))
modelo.add(Conv2D(128,(3,3), padding='same'))
modelo.add(BatchNormalization(momentum=0.2, epsilon=1e-5, gamma_initializer="uniform"))
modelo.add(LeakyReLU(alpha=0.1))
modelo.add(Conv2D(128,(3,3), padding='same'))
modelo.add(BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform"))
modelo.add(LeakyReLU(alpha=0.1))
modelo.add(MaxPooling2D(2,2))
modelo.add(Dropout(0.2))
modelo.add(Conv2D(256,(3,3), padding='same'))
modelo.add(BatchNormalization(momentum=0.2, epsilon=1e-5, gamma_initializer="uniform"))
modelo.add(LeakyReLU(alpha=0.1))
modelo.add(Conv2D(256,(3,3), padding='same'))
modelo.add(BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform"))
modelo.add(LeakyReLU(alpha=0.1))
modelo.add(MaxPooling2D(2,2))
modelo.add(Dropout(0.2))
modelo.add(Flatten())
 modelo.add(Dense(256))
modelo.add(LeakyReLU(alpha=0.1))
modelo.add(BatchNormalization())
 modelo.add(Dense(10, activation='softmax'))<train_model>
%%time
def features(df):
df = df.sort_values(by=['time'] ).reset_index(drop=True)
 df.index =(( df.time * 10_000)- 1 ).values
df['batch'] = df.index // 50_000
df['batch_index'] = df.index -(df.batch * 50_000)
 df['batch_slices'] = df['batch_index'] // 5_000
df['batch_slices2'] = df.apply(lambda r: '_'.join([str(r['batch'] ).zfill(3), str(r['batch_slices'] ).zfill(3)]), axis=1)
 for c in ['batch','batch_slices2']:
d = {}
d['mean'+c] = df.groupby([c])['signal_undrifted'].mean()
d['median'+c] = df.groupby([c])['signal_undrifted'].median()
d['max'+c] = df.groupby([c])['signal_undrifted'].max()
d['min'+c] = df.groupby([c])['signal_undrifted'].min()
d['std'+c] = df.groupby([c])['signal_undrifted'].std()
d['mean_abs_chg'+c] = df.groupby([c])['signal_undrifted'].apply(lambda x: np.mean(np.abs(np.diff(x))))
d['abs_max'+c] = df.groupby([c])['signal_undrifted'].apply(lambda x: np.max(np.abs(x)))
 d['abs_min'+c] = df.groupby([c])['signal_undrifted'].apply(lambda x: np.min(np.abs(x)))
 for v in d:
df[v] = df[c].map(d[v].to_dict())
 df['range'+c] = df['max'+c] - df['min'+c]
df['maxtomin'+c] = df['max'+c] / df['min'+c]
df['abs_avg'+c] =(df['abs_min'+c] + df['abs_max'+c])/ 2
df['signal_shift_+1'] = [0,] + list(df['signal_undrifted'].values[:-1])
 df['signal_shift_-1'] = list(df['signal_undrifted'].values[1:])+ [0]
for i in df[df['batch_index']==0].index:
df['signal_shift_+1'][i] = np.nan
for i in df[df['batch_index']==49999].index:
df['signal_shift_-1'][i] = np.nan
for c in [c1 for c1 in df.columns if c1 not in ['time', 'signal_undrifted', 'open_channels', 'batch', 'batch_index', 'batch_slices', 'batch_slices2']]:
df[c+'_msignal'] = df[c] - df['signal_undrifted']
return df
train = features(train)
 test = features(test )
epochs=100
batch_size=200
history = modelo.fit(x_train, y_train,
epochs=epochs,
batch_size= batch_size,
callbacks=[LearningRateScheduler(lr_decay)],
validation_data=(x_valid, y_valid))<predict_on_test>
def f1_score_calc(y_true, y_pred):
return f1_score(y_true, y_pred, average="macro")
 def lgb_Metric(preds, dtrain):
labels = dtrain.get_label()
preds = np.round(np.clip(preds, 0, 10)).astype(int)
 score = f1_score(labels, preds, average="macro")
 return('KaggleMetric', score, True)
 def train_model_classification(X, X_test, y, params, model_type='lgb', eval_metric='f1score',
columns=None, plot_feature_importance=False, model=None,
verbose=50, early_stopping_rounds=200, n_estimators=2000):
columns = X.columns if columns == None else columns
X_test = X_test[columns]
metrics_dict = {
'f1score': {'lgb_metric_name': lgb_Metric,}
}
result_dict = {}
oof = np.zeros(len(X))
prediction = np.zeros(( len(X_test)))
 scores = []
feature_importance = pd.DataFrame()

 if True:
X_train, X_valid, y_train, y_valid = model_selection.train_test_split(X, y, test_size=0.3, random_state=7)
 if model_type == 'lgb':
model = lgb.train(params, lgb.Dataset(X_train, y_train),
n_estimators, lgb.Dataset(X_valid, y_valid),
verbose_eval=verbose, early_stopping_rounds=early_stopping_rounds, feval=lgb_Metric)
 preds = model.predict(X_valid, num_iteration=model.best_iteration)
 y_pred_valid = np.round(np.clip(preds, 0, 10)).astype(int)
 y_pred = model.predict(X_test, num_iteration=model.best_iteration)
 y_pred = np.round(np.clip(y_pred, 0, 10)).astype(int)
 scores.append(f1_score_calc(y_valid, y_pred_valid))
prediction += y_pred
if model_type == 'lgb' and plot_feature_importance:
fold_importance = pd.DataFrame()
fold_importance["feature"] = columns
fold_importance["importance"] = model.feature_importances_
fold_importance["fold"] = fold_n + 1
feature_importance = pd.concat([feature_importance, fold_importance], axis=0)
 print('FINAL score: {0:.4f}, std: {1:.4f}.'.format(np.mean(scores), np.std(scores)))
 result_dict['oof'] = oof
result_dict['prediction'] = prediction
result_dict['scores'] = scores
result_dict['model'] = model
if model_type == 'lgb':
if plot_feature_importance:
feature_importance["importance"] /= folds.n_splits
cols = feature_importance[["feature", "importance"]].groupby("feature" ).mean().sort_values(
 by="importance", ascending=False)[:50].index
best_features = feature_importance.loc[feature_importance.feature.isin(cols)]
plt.figure(figsize=(16, 12)) ;
sns.barplot(x="importance", y="feature", data=best_features.sort_values(by="importance", ascending=False)) ;
plt.title('LGB Features(avg over folds)');
result_dict['feature_importance'] = feature_importance
return result_dict
scores = modelo.predict(x_test)
 score_classes = np.argmax(scores, axis = 1)
 x_dig=dig.drop('label',axis=1 ).iloc[:,:].values
print(x_dig.shape)
 x_dig = x_dig.reshape(x_dig.shape[0], 28, 28,1)
 print(x_dig.shape)
 y_dig=dig.label
print(y_dig.shape)
 preds_dig=modelo.predict_classes(x_dig/255)
 metrics.accuracy_score(preds_dig, y_dig )<prepare_output>
good_columns = [c for c in train.columns if c not in ['time', 'signal','open_channels', 'batch', 'batch_index', 'batch_slices', 'batch_slices2']]
X = train[good_columns].copy()
y = train['open_channels']
X_test = test[good_columns].copy()
output = pd.DataFrame({'id': sample_sub['id'],
'label': score_classes})
 output.head()<save_to_csv>
del train, test
output.to_csv('submission.csv', index=False )<import_modules>
params = {'learning_rate': 0.1, 'max_depth': 7, 'num_leaves':2**7+1, 'metric': 'rmse', 'random_state': 7, 'n_jobs':-1}
result_dict_lgb = train_model_classification(X=X[0:500000*8-1], X_test=X_test, y=y[0:500000*8-1], params=params, model_type='lgb', eval_metric='f1score', plot_feature_importance=False,
verbose=50, early_stopping_rounds=150, n_estimators=3000 )
<load_from_csv><EOS> 
sub = pd.read_csv('/kaggle/input/liverpool-ion-switching/sample_submission.csv')
 sub['open_channels'] = np.array(np.round(result_dict_lgb['prediction'],0), np.int)
 sub.to_csv('submission_unshifted_70p.csv', index=False, float_format='%.4f')
 sub.head(10 )