kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
2,038,144
duplicate=train.comment_text.duplicated() duplicate[duplicate==True]<filter>
myList = list(range(1,50)) neighbors = list(myList) cv_scores = [] for k in neighbors: knn = KNeighborsClassifier(n_neighbors=k) scores = cross_val_score(knn, X_train, y_train, cv=10, scoring='accuracy') cv_scores.append(scores.mean() )
Titanic - Machine Learning from Disaster
2,038,144
toxic=train[train.toxic==1]['comment_text'].values severe_toxic=train[train.severe_toxic==1]['comment_text'].values obscene=train[train.obscene==1]['comment_text'].values threat=train[train.threat==1]['comment_text'].values insult=train[train.insult==1]['comment_text'].values identity_hate=train[train.identity_hate==1]...
X_train = X_train y_train = y_train KNNC = KNeighborsClassifier(n_neighbors=3) KNNC.fit(X_train, y_train) y_pred = KNNC.predict(X_test) print(classification_report(y_test, y_pred, target_names=['0','1'])) print("Models accuracy score: ", accuracy_score(y_test, y_pred))
Titanic - Machine Learning from Disaster
2,038,144
replacement_patterns = [ (r'won't', 'will not'), (r'can't', 'cannot'), (r'i'm', 'i am'), (r'ain't', 'is not'), (r'(\w+)'ll', '\g<1> will'), (r'(\w+)n't', '\g<1> not'), (r'(\w+)'ve', '\g<1> have'), (r'(\w+)'s', '\g<1> is'), (r'(\w+)'re', '\g<1> are'), (r'(\w+)'d', '\g<1> would') ] class RegexpReplacer(object)...
classes = ["will not suvive", "will survive"] visualizer = ClassificationReport(KNNC, classes=classes, support=True) visualizer.fit(X_train, y_train) visualizer.score(X_test, y_test) g = visualizer.poof()
Titanic - Machine Learning from Disaster
2,038,144
lemmer = WordNetLemmatizer() stopwords = nltk.corpus.stopwords.words('english') replacer = RegexpReplacer() tokenizer=TweetTokenizer() def comment_process(category): category_processed=[] for i in range(category.shape[0]): comment_list=tokenizer.tokenize(replacer.replace(category[i])) comment_list_cleaned= [word for w...
titanic_submission = pd.DataFrame({'PassengerId':df_all_knn_hot.loc[test_index,:].index, 'Survived':KNNC.predict(df_all_knn_hot.loc[test_index,:])}) titanic_submission.PassengerId = titanic_submission.PassengerId.astype(int) titanic_submission.Survived = titanic_submission.Survived.astype(int) titanic_submission.gro...
Titanic - Machine Learning from Disaster
2,038,144
warnings.filterwarnings('ignore' )<feature_engineering>
titanic_submission.to_csv("titanic_submission_knn_4.csv", index=False )
Titanic - Machine Learning from Disaster
2,038,144
class_names = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate'] train_text = train['comment_text'] test_text = test['comment_text'] all_text = pd.concat([train_text, test_text]) word_vectorizer = TfidfVectorizer( sublinear_tf=True, strip_accents='unicode', analyzer='word', token_pattern=r'\w{1...
df_all_rf_hot = df_all.copy() df_all_rf_hot = df_all_rf_hot.drop(['Name','Cabin','Fare','Ticket','Lastname'], axis=1) df_all_rf_hot = pd.get_dummies(df_all_rf_hot, columns=['Sex','Salutation','Embarked']) X_train, X_test, y_train, y_test = train_test_split(df_all_rf_hot.loc[train_index,:], Survived, test_size = 0.30,...
Titanic - Machine Learning from Disaster
2,038,144
!pip install tensorflow-gpu==2.0a0<import_modules>
myList = list(range(1,30)) levels = list(myList) cv_scores = [] for l in levels: rfc = RandomForestClassifier(n_estimators=100) scores = cross_val_score(rfc, X_train, y_train, cv=5, scoring='recall') cv_scores.append(scores.mean() )
Titanic - Machine Learning from Disaster
2,038,144
print(tf.__version__ )<set_options>
X_train = X_train y_train = y_train RFCC = RandomForestClassifier(max_depth=14, n_estimators=5000) RFCC.fit(X_train, y_train) y_pred = RFCC.predict(X_test) print(classification_report(y_test, y_pred, target_names=['0','1'])) print("Models accuracy score: ", accuracy_score(y_test, y_pred))
Titanic - Machine Learning from Disaster
2,038,144
tf.test.is_gpu_available( cuda_only=False, min_cuda_compute_capability=None ) <define_variables>
classes = ["will not suvive", "will survive"] visualizer = ClassificationReport(RFCC, classes=classes, support=True) visualizer.fit(X_train, y_train) visualizer.score(X_test, y_test) g = visualizer.poof()
Titanic - Machine Learning from Disaster
2,038,144
tf.random.set_seed(42) datadir = ".. /input/"<choose_model_class>
titanic_submission_rfc = pd.DataFrame({'PassengerId':df_all_rf_hot.loc[test_index,:].index, 'Survived':RFCC.predict(df_all_rf_hot.loc[test_index,:])}) titanic_submission_rfc.PassengerId = titanic_submission_rfc.PassengerId.astype(int) titanic_submission_rfc.Survived = titanic_submission_rfc.Survived.astype(int) tita...
Titanic - Machine Learning from Disaster
2,038,144
class Message_Passer_1(tf.keras.layers.Layer): def __init__(self, intermediate_dim, state_dim): super(Message_Passer_1, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.output_layer = tf.keras.layers.Dens...
titanic_submission_rfc.to_csv("titanic_submission_rfc_5.csv", index=False )
Titanic - Machine Learning from Disaster
2,038,144
class Message_Agg(tf.keras.layers.Layer): def __init__(self): super(Message_Agg, self ).__init__() def call(self, messages): return tf.math.reduce_sum(messages, 2 )<choose_model_class>
import scipy.special
Titanic - Machine Learning from Disaster
2,038,144
class Update_Func_1(tf.keras.layers.Layer): def __init__(self, intermediate_dim, state_dim): super(Update_Func_1, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.output_layer = tf.keras.layers.Dense(unit...
conf_performance_list = []
Titanic - Machine Learning from Disaster
2,038,144
class Adj_Updater_1(tf.keras.layers.Layer): def __init__(self, intermediate_dim, state_dim): super(Adj_Updater_1, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.output_layer = tf.keras.layers.Dense(unit...
input_nodes = 29 hidden_nodes = 3 output_nodes = 2 learningrate = 0.4 nn_epochs = 1000
Titanic - Machine Learning from Disaster
2,038,144
class Edge_Regressor(tf.keras.layers.Layer): def __init__(self, intermediate_dim): super(Edge_Regressor, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.hidden_layer_2 = tf.keras.layers.Dense(units=inter...
titanic_nn = neuralNetwork(input_nodes, hidden_nodes, output_nodes, learningrate )
Titanic - Machine Learning from Disaster
2,038,144
class MP_Layer(tf.keras.layers.Layer): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim): super(MP_Layer, self ).__init__(self) self.state_dim = state_dim self.message_passers = Message_Passer_1(intermediate_dim = mp_int_dim, state_dim = state_dim) self.update_functions = Update_Func_1(intermediate_d...
X_train_nn, X_test_nn, y_train_nn, y_test_nn = train_test_split(df_all_knn_hot.loc[train_index,:], Survived, test_size = 0.15, random_state = 45 )
Titanic - Machine Learning from Disaster
2,038,144
class MP_Layer_edge_only(tf.keras.layers.Layer): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim): super(MP_Layer_edge_only, self ).__init__(self) self.adj_updaters = Adj_Updater_1(intermediate_dim = up_int_dim, state_dim = state_dim) self.message_aggs = Message_Agg() self.state_dim = state_dim def ...
Xy_train_nn = pd.concat([X_train_nn, y_train_nn], axis=1 )
Titanic - Machine Learning from Disaster
2,038,144
adj_input = tf.keras.Input(shape=(None,), name='adj_input') nod_input = tf.keras.Input(shape=(None,), name='nod_input') class MPNN(tf.keras.Model): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim, T): super(MPNN, self ).__init__(self) self.MP = [MP_Layer(mp_int_dim, up_int_dim, out_int_dim, state_d...
epochs = nn_epochs for e in range(epochs): for row in Xy_train_nn.itertuples() : inputs =(np.asfarray(row[1:30])/ 29 * 0.99)+ 0.01 targets = np.zeros(output_nodes)+ 0.01 targets[int(row[30])] = 0.99 titanic_nn.train(inputs, targets) pass pass
Titanic - Machine Learning from Disaster
2,038,144
def log_mae(orig , preds): mask = tf.where(tf.equal(orig, 0), orig, tf.ones_like(orig)) nums = tf.boolean_mask(orig, mask) preds = tf.boolean_mask(preds, mask) reconstruction_error = tf.math.log(tf.reduce_mean(tf.abs(tf.subtract(nums, preds)))) return reconstruction_error<choose_model_class>
Xy_test_nn = pd.concat([X_test_nn, y_test_nn], axis=1 )
Titanic - Machine Learning from Disaster
2,038,144
learning_rate = 0.001 def warmup(epoch): initial_lrate = learning_rate if epoch == 0: lrate = 0.00001 if epoch == 1: lrate = 0.0001 if epoch > 1: lrate = 0.001 if epoch > 20: lrate = 0.0001 if epoch > 25: lrate = 0.00001 tf.print("Learning rate: ", lrate) return lrate lrate = tf.keras.callbacks.LearningRateScheduler(w...
scorecard = [] matrixlist = [] for index,row in Xy_test_nn.iterrows() : inputs = row[0:29].values correct_label = row[29] results = titanic_nn.query(inputs) label = np.argmax(results) print('PassengerID:', index, ' - Networks answer: ', label, ' --> Correct answer: ', correct_label) matrixlist.append([results, label...
Titanic - Machine Learning from Disaster
2,038,144
mpnn = MPNN(mp_int_dim = 512, up_int_dim = 1024, out_int_dim = 512, state_dim = 256, T = 7) mpnn.compile(opt, log_mae )<define_variables>
scorecard_array = np.array(scorecard) nn_accuracy = scorecard_array.sum() / scorecard_array.size conf_performance_list.append([nn_accuracy,learningrate,hidden_nodes,epochs]) print('Accuracy score by "75/15"-network: ', nn_accuracy )
Titanic - Machine Learning from Disaster
2,038,144
batch_size = 64 epochs = 30 <train_model>
epochs = nn_epochs for e in range(epochs): for row in Xy_test_nn.itertuples() : inputs =(np.asfarray(row[1:30])/ 29 * 0.99)+ 0.01 targets = np.zeros(output_nodes)+ 0.01 targets[int(row[30])] = 0.99 titanic_nn.train(inputs, targets) pass pass
Titanic - Machine Learning from Disaster
2,038,144
def train() : nodes_train = np.load(datadir + "internalgraphdata/nodes_train.npz")['arr_0'] in_edges_train = np.load(datadir + "internalgraphdata/in_edges_train.npz")['arr_0'] out_edges_train = np.load(datadir + "internalgraphdata/out_edges_train.npz")['arr_0'] out_labels = out_edges_train.reshape(-1,out_edges_train.sh...
titanic_submission_nn = pd.DataFrame(columns=['PassengerId','Survived']) for index,row in df_all_rf_hot.loc[test_index].iterrows() : inputs = row[0:29].values results = titanic_nn.query(inputs) label = np.argmax(results) titanic_submission_nn = titanic_submission_nn.append({'PassengerId' : index , 'Survived': label}...
Titanic - Machine Learning from Disaster
2,038,144
preds, train_size = train()<load_pretrained>
titanic_submission_nn.PassengerId = titanic_submission_nn.PassengerId.astype(int) titanic_submission_nn.Survived = titanic_submission_nn.Survived.astype(int) titanic_submission_nn.groupby('Survived' ).count()
Titanic - Machine Learning from Disaster
2,038,144
mpnn.save_weights("mymodel.h5" )<load_from_csv>
titanic_submission_nn.to_csv("titanic_submission_nn_6.csv", index=False )
Titanic - Machine Learning from Disaster
2,038,144
train = pd.read_csv(datadir + "champs-scalar-coupling/train.csv") test = pd.read_csv(datadir + "champs-scalar-coupling/test.csv") train_mol_names = train['molecule_name'].unique() val = train[train.molecule_name.isin(train_mol_names[train_size:])] val_group = val.groupby('molecule_name' )<compute_test_metric>
import tensorflow as tf
Titanic - Machine Learning from Disaster
2,038,144
def make_outs(test_group, preds): i = 0 x = np.array([]) for test_gp, preds in zip(test_group, preds): if(not i%1000): print(i) gp = test_gp[1] x = np.append(x,(preds[gp['atom_index_0'].values, gp['atom_index_1'].values] + preds[gp['atom_index_1'].values, gp['atom_index_0'].values])/2.0) i = i+1 return x def group_m...
X_train_tfnn, X_test_tfnn, y_train_tfnn, y_test_tfnn = train_test_split(df_all_knn_hot.loc[train_index,:], Survived, test_size = 0.15, random_state = 45) X_train_tfnn = tf.keras.utils.normalize(np.asfarray(X_train_tfnn),axis= -1) X_test_tfnn = tf.keras.utils.normalize(np.asfarray(X_test_tfnn),axis= -1) y_train_tfnn ...
Titanic - Machine Learning from Disaster
2,038,144
max_size = 29 preds = preds.reshape(( -1,max_size, max_size)) out_unscaled = make_outs(val_group, preds )<feature_engineering>
model = tf.keras.models.Sequential() model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu)) model.add(tf.keras.layers.Dense(2, activation=tf.nn.softmax)) model.compile(optimizer='adam', loss='sparse_categorical_cros...
Titanic - Machine Learning from Disaster
2,038,144
val['pred_scalar_coupling_constant'] = out_unscaled coups_to_isolate = ['1JHC', '1JHN', '2JHC', '2JHH', '2JHN', '3JHC', '3JHH', '3JHN'] for i, coup in enumerate(coups_to_isolate): scale_min = train['scalar_coupling_constant'].loc[train.type == coup].min() scale_max = train['scalar_coupling_constant'].loc[train.type == ...
val_loss, val_acc = model.evaluate(X_test_tfnn, y_test_tfnn )
Titanic - Machine Learning from Disaster
2,038,144
for coup in coups_to_isolate: log_mae = group_mean_log_mae(val['scalar_coupling_constant'], val['pred_scalar_coupling_constant'], val['type'][val.type == coup]) print(coup,"\t", log_mae) total = group_mean_log_mae(val['scalar_coupling_constant'], val['pred_scalar_coupling_constant'], val['type']) print("") print("T...
model.save('titanic_survivor_predictor.model' )
Titanic - Machine Learning from Disaster
2,038,144
nodes_test = np.load(datadir + "internalgraphdata/nodes_test.npz")['arr_0'] in_edges_test = np.load(datadir + "internalgraphdata/in_edges_test.npz")['arr_0'] in_edges_test = in_edges_test.reshape(-1,in_edges_test.shape[1]*in_edges_test.shape[2],in_edges_test.shape[3] )<predict_on_test>
new_model = tf.keras.models.load_model('titanic_survivor_predictor.model' )
Titanic - Machine Learning from Disaster
2,817,480
preds = mpnn.predict({'adj_input' : in_edges_test, 'nod_input': nodes_test}, verbose=1 )<save_model>
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns
Titanic - Machine Learning from Disaster
2,817,480
np.save("preds_kernel.npy" , preds )<groupby>
train = pd.read_csv('.. /input/train.csv') test = pd.read_csv('.. /input/test.csv' )
Titanic - Machine Learning from Disaster
2,817,480
test_group = test.groupby('molecule_name' )<normalization>
train = pd.read_csv('.. /input/train.csv') test = pd.read_csv('.. /input/test.csv' )
Titanic - Machine Learning from Disaster
2,817,480
preds = preds.reshape(( -1,max_size, max_size)) out_unscaled = make_outs(test_group, preds )<feature_engineering>
train.Survived.value_counts()
Titanic - Machine Learning from Disaster
2,817,480
test['scalar_coupling_constant'] = out_unscaled coups_to_isolate = ['1JHC', '1JHN', '2JHC', '2JHH', '2JHN', '3JHC', '3JHH', '3JHN'] for i, coup in enumerate(coups_to_isolate): scale_min = train['scalar_coupling_constant'].loc[train.type == coup].min() scale_max = train['scalar_coupling_constant'].loc[train.type == coup...
train.isna().sum()
Titanic - Machine Learning from Disaster
2,817,480
test[['id','scalar_coupling_constant']].to_csv('submission.csv', index=False )<set_options>
train.loc[train.Age.isna() , 'Age'] = train[~train.Age.isna() ].Age.mean()
Titanic - Machine Learning from Disaster
2,817,480
%matplotlib inline <define_variables>
train.loc[train.Cabin.isna() ,'Cabin'] = "No Cabin"
Titanic - Machine Learning from Disaster
2,817,480
DATA_PATH = '.. /input' SUBMISSIONS_PATH = './' ATOMIC_NUMBERS = { 'H': 1, 'C': 6, 'N': 7, 'O': 8, 'F': 9 }<set_options>
print(train.Embarked.value_counts()) train.loc[train.Embarked.isna() ,'Embarked'] = "S"
Titanic - Machine Learning from Disaster
2,817,480
pd.set_option('display.max_colwidth', -1) pd.set_option('display.max_rows', 120) pd.set_option('display.max_columns', 120 )<load_from_csv>
train.isna().sum()
Titanic - Machine Learning from Disaster
2,817,480
train_csv = pd.read_csv('.. /input/data-of-distance-qm9-giba/fin_train.csv') test_csv = pd.read_csv('.. /input/data-of-distance-qm9-giba/fin_test.csv' )<load_from_csv>
train.loc[train.Fare > 200]
Titanic - Machine Learning from Disaster
2,817,480
train_csv = reduce_mem_usage(train_csv,verbose = True) test_csv = reduce_mem_usage(test_csv,verbose = True )<save_to_csv>
train.Sex.value_counts()
Titanic - Machine Learning from Disaster
2,817,480
train_csv.set_index('id',inplace = True) test_csv.set_index('id',inplace = True )<load_from_csv>
labelencoder = LabelEncoder() train['Sex'] = labelencoder.fit_transform(train['Sex']) train.Sex.value_counts()
Titanic - Machine Learning from Disaster
2,817,480
structures_csv = pd.read_csv(f'{DATA_PATH}/champs-scalar-coupling/structures.csv') structures_csv['molecule_index'] = structures_csv.molecule_name.str.replace('dsgdb9nsd_', '' ).astype('int32') structures_csv = structures_csv[['molecule_index', 'atom_index', 'atom', 'x', 'y', 'z']] structures_csv['atom'] = structures...
def features_engineering(df): df.loc[df.Age.isna() , 'Age'] = df[~df.Age.isna() ].Age.mean() df.loc[df.Cabin.isna() ,'Cabin'] = "No Cabin" df.loc[df.Embarked.isna() ,'Embarked'] = "S" df['persons_abroad_size'] =(df['Parch']+df['SibSp'] ).astype(int) df['alone'] = np.where(df['Parch']==0,1,0) df['Embarked'] = df['Emba...
Titanic - Machine Learning from Disaster
2,817,480
def build_type_dataframes(base, structures, coupling_type): base = base[base['type'] == coupling_type].drop('type', axis=1 ).copy() base = base.reset_index() base['id'] = base['id'].astype('int32') structures = structures[structures['molecule_index'].isin(base['molecule_index'])] return base, structures<merge>
train = pd.read_csv('.. /input/train.csv') test = pd.read_csv('.. /input/test.csv') train,train_id = features_engineering(train) test,test_id = features_engineering(test )
Titanic - Machine Learning from Disaster
2,817,480
def add_coordinates(base, structures, index): df = pd.merge(base, structures, how='inner', left_on=['molecule_index', f'atom_index_{index}'], right_on=['molecule_index', 'atom_index'] ).drop(['atom_index'], axis=1) df = df.rename(columns={ 'atom': f'atom_{index}', 'x': f'x_{index}', 'y': f'y_{index}', 'z': f'z_{index}...
X_train = train.drop('Survived',axis=1 ).select_dtypes(include=['int32','int64','float64']) y_train = train['Survived'] X_test = test.select_dtypes(include=['int32','int64','float64']) xg_boost = xgb.XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=0.65, gamma=2, learning_rate=0.3...
Titanic - Machine Learning from Disaster
2,817,480
def add_atoms(base, atoms): df = pd.merge(base, atoms, how='inner', on=['molecule_index', 'atom_index_0', 'atom_index_1']) return df<merge>
xg_boost.fit(X_train, y_train )
Titanic - Machine Learning from Disaster
2,817,480
def merge_all_atoms(base, structures): df = pd.merge(base, structures, how='left', left_on=['molecule_index'], right_on=['molecule_index']) df = df[(df.atom_index_0 != df.atom_index)&(df.atom_index_1 != df.atom_index)] return df<feature_engineering>
print(xg_boost.score(X_train, y_train)) scores = model_selection.cross_val_score(xg_boost, X_train, y_train, cv=5, scoring='accuracy') print(scores) print("Kfold on XGBClassifier: %0.4f(+/- %0.4f)" %(scores.mean() , scores.std()))
Titanic - Machine Learning from Disaster
2,817,480
def add_center(df): df['x_c'] =(( df['x_1'] + df['x_0'])* np.float32(0.5)) df['y_c'] =(( df['y_1'] + df['y_0'])* np.float32(0.5)) df['z_c'] =(( df['z_1'] + df['z_0'])* np.float32(0.5)) def add_distance_to_center(df): df['d_c'] =(( (df['x_c'] - df['x'])**np.float32(2)+ (df['y_c'] - df['y'])**np.float32(2)+ (df['z_c']...
Y_pred = xg_boost.predict(X_test )
Titanic - Machine Learning from Disaster
2,817,480
def add_distances(df): n_atoms = 1 + max([int(c.split('_')[1])for c in df.columns if c.startswith('x_')]) for i in range(1, n_atoms): for vi in range(min(4, i)) : add_distance_between(df, i, vi )<merge>
submission = pd.DataFrame({ "PassengerId": test_id, "Survived": Y_pred }) submission.head(10 )
Titanic - Machine Learning from Disaster
2,817,480
def add_n_atoms(base, structures): dfs = structures['molecule_index'].value_counts().rename('n_atoms' ).to_frame() return pd.merge(base, dfs, left_on='molecule_index', right_index=True )<drop_column>
submission.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
2,817,480
<define_variables><EOS>
submission.to_csv('submission.csv', index=False )
Titanic - Machine Learning from Disaster
11,531,970
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<init_hyperparams>
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import random from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier from sklearn.model_selection import GridSearchCV from mlxtend.classifier import StackingCVClassifier
Titanic - Machine Learning from Disaster
11,531,970
LGB_PARAMS = { 'objective': 'regression', 'metric': 'mae', 'verbosity': -1, 'boosting_type': 'gbdt', 'learning_rate': 0.1455, 'num_leaves': 129, 'min_child_samples': 78, 'max_depth': 13, 'subsample_freq': 1, 'subsample': 0.88, 'bagging_seed': 15, 'reg_alpha': 0.10107001, 'reg_lambda': 0.300132, 'colsample_bytree': 1.0 ...
train_data = pd.read_csv('/kaggle/input/titanic/train.csv') train_data.head()
Titanic - Machine Learning from Disaster
11,531,970
submission_csv = pd.read_csv(f'{DATA_PATH}/champs-scalar-coupling/sample_submission.csv', index_col='id' )<prepare_x_and_y>
test_data = pd.read_csv('/kaggle/input/titanic/test.csv') test_data.head()
Titanic - Machine Learning from Disaster
11,531,970
def build_x_y_data(some_csv, coupling_type, n_atoms): full = build_couple_dataframe(some_csv, structures_csv, coupling_type, n_atoms=n_atoms) df = take_n_atoms(full, n_atoms) df = df.fillna(0) print(df.columns) if 'scalar_coupling_constant' in df: X_data = df.drop(['scalar_coupling_constant'], axis=1 ).values.astyp...
len(train_data[train_data['Pclass'] == 1]), len(train_data[train_data['Pclass'] == 2]), len(train_data[train_data['Pclass'] == 3] )
Titanic - Machine Learning from Disaster
11,531,970
def train_and_predict_for_one_coupling_type(coupling_type, submission, n_atoms, n_folds=5, n_splits=5, random_state=128): print(f'*** Training Model for {coupling_type} ***') X_data, y_data = build_x_y_data(train_csv, coupling_type, n_atoms) X_test, _ = build_x_y_data(test_csv, coupling_type, n_atoms) y_pred = np.ze...
precentages = [] first = 136/216 seconds = 87/184 third = 119/491 precentages.append(first) precentages.append(seconds) precentages.append(third )
Titanic - Machine Learning from Disaster
11,531,970
model_params = { '1JHN': 7, '1JHC': 10, '2JHH': 9, '2JHN': 9, '2JHC': 9, '3JHH': 9, '3JHC': 10, '3JHN': 10 } N_FOLDS = 5 submission = submission_csv.copy() cv_scores = {} for coupling_type in model_params.keys() : cv_score = train_and_predict_for_one_coupling_type( coupling_type, submission, n_atoms=model_params[coupl...
percents = pd.DataFrame(precentages) percents.index += 1
Titanic - Machine Learning from Disaster
11,531,970
pd.DataFrame({'type': list(cv_scores.keys()), 'cv_score': list(cv_scores.values())} )<save_to_csv>
train_data.isna().sum()
Titanic - Machine Learning from Disaster
11,531,970
submission.to_csv(f'{SUBMISSIONS_PATH}/submission.csv' )<save_to_csv>
test_data.isna().sum()
Titanic - Machine Learning from Disaster
11,531,970
pd.read_csv('.. /input/sample_submission.csv', converters = {'EncodedPixels': lambda p: None} ).to_csv('submission_paulorzp.csv', index=False )<save_to_csv>
df = [train_data,test_data] for d in df: d['Age'].fillna(d['Age'].median() ,inplace=True )
Titanic - Machine Learning from Disaster
11,531,970
test_files = [f for f in os.listdir(".. /input/test/")] df = pd.read_csv(".. /input/test_ship_segmentations.csv") df = df[df['ImageId'].isin(test_files)].drop_duplicates(subset="ImageId") df.to_csv("submission.csv", index=False) len(df )<import_modules>
train_data['Cabin'].value_counts()
Titanic - Machine Learning from Disaster
11,531,970
from fastai.conv_learner import * from fastai.dataset import * import pandas as pd import numpy as np import os from PIL import Image from sklearn.model_selection import train_test_split from tqdm import tnrange, tqdm_notebook from scipy import ndimage<define_variables>
for d in df: d['Cabin'].fillna('C',inplace=True )
Titanic - Machine Learning from Disaster
11,531,970
PATH = './' TRAIN = '.. /input/airbus-ship-detection/train/' TEST = '.. /input/airbus-ship-detection/test/' SEGMENTATION = '.. /input/airbus-ship-detection/train_ship_segmentations.csv' PRETRAINED_DETECTION_PATH = '.. /input/fine-tuning-resnet34-on-ship-detection/models/' PRETRAINED_SEGMENTATION_PATH = '.. /input/unet3...
train_data['Cabin'].isna().sum()
Titanic - Machine Learning from Disaster
11,531,970
nw = 2 arch = resnet34<load_from_csv>
cabins = [] for i in train_data['Cabin']: cabins.append(str(i))
Titanic - Machine Learning from Disaster
11,531,970
train_names = [f for f in os.listdir(TRAIN)] test_names = [f for f in os.listdir(TEST)] for el in exclude_list: if(el in train_names): train_names.remove(el) if(el in test_names): test_names.remove(el) tr_n, val_n = train_test_split(train_names, test_size=0.05, random_state=42) segmentation_df = pd.read_csv(os.path....
words = [] for i in cabins: word = i[0] words.append(word )
Titanic - Machine Learning from Disaster
11,531,970
def cut_empty(names): return [name for name in names if(type(segmentation_df.loc[name]['EncodedPixels'])!= float)] tr_n_cut = cut_empty(tr_n) val_n_cut = cut_empty(val_n )<categorify>
train_data['Cabin'] = words
Titanic - Machine Learning from Disaster
11,531,970
def get_mask(img_id, df): shape =(768,768) img = np.zeros(shape[0]*shape[1], dtype=np.uint8) masks = df.loc[img_id]['EncodedPixels'] if(type(masks)== float): return img.reshape(shape) if(type(masks)== str): masks = [masks] for mask in masks: s = mask.split() for i in range(len(s)//2): start = int(s[2*i])- 1 length =...
train_data['Cabin'].value_counts()
Titanic - Machine Learning from Disaster
11,531,970
class pdFilesDataset(FilesDataset): def __init__(self, fnames, path, transform): self.segmentation_df = pd.read_csv(SEGMENTATION ).set_index('ImageId') super().__init__(fnames, transform, path) def get_x(self, i): img = open_image(os.path.join(self.path, self.fnames[i])) if self.sz == 768: return img else: return cv2...
cabins = [] for i in test_data['Cabin']: cabins.append(str(i))
Titanic - Machine Learning from Disaster
11,531,970
def get_data(sz,bs): tfms = tfms_from_model(arch, sz, crop_type=CropType.NO, tfm_y=TfmType.CLASS) tr_names = tr_n if(len(tr_n_cut)%bs == 0)else tr_n[:-(len(tr_n_cut)%bs)] ds = ImageData.get_ds(pdFilesDataset,(tr_names,TRAIN), (val_n_cut,TRAIN), tfms, test=(test_names,TEST)) md = ImageData(PATH, ds, bs, num_workers=nw...
words = [] for i in cabins: word = i[0] words.append(word )
Titanic - Machine Learning from Disaster
11,531,970
cut,lr_cut = model_meta[arch]<choose_model_class>
test_data['Cabin'] = words
Titanic - Machine Learning from Disaster
11,531,970
def get_base() : layers = cut_model(arch(True), cut) return nn.Sequential(*layers )<concatenate>
test_data['Cabin'].value_counts()
Titanic - Machine Learning from Disaster
11,531,970
class UnetBlock(nn.Module): def __init__(self, up_in, x_in, n_out): super().__init__() up_out = x_out = n_out//2 self.x_conv = nn.Conv2d(x_in, x_out, 1) self.tr_conv = nn.ConvTranspose2d(up_in, up_out, 2, stride=2) self.bn = nn.BatchNorm2d(n_out) def forward(self, up_p, x_p): up_p = self.tr_conv(up_p) x_p = self.x_...
train_data['Embarked'].isna().sum()
Titanic - Machine Learning from Disaster
11,531,970
def IoU(pred, targs): pred =(pred > 0.5 ).astype(float) intersection =(pred*targs ).sum() return intersection /(( pred+targs ).sum() - intersection + 1.0 )<compute_test_metric>
train_data['Embarked'].value_counts()
Titanic - Machine Learning from Disaster
11,531,970
def get_score(pred, true): n_th = 10 b = 4 thresholds = [0.5 + 0.05*i for i in range(n_th)] n_masks = len(true) n_pred = len(pred) ious = [] score = 0 for mask in true: buf = [] for p in pred: buf.append(IoU(p,mask)) ious.append(buf) for t in thresholds: tp, fp, fn = 0, 0, 0 for i in range(n_masks): match = False fo...
for d in df: d['Embarked'].fillna('S',inplace=True )
Titanic - Machine Learning from Disaster
11,531,970
def split_mask(mask): threshold = 0.5 threshold_obj = 8 labled,n_objs = ndimage.label(mask > threshold) result = [] for i in range(n_objs): obj =(labled == i + 1 ).astype(int) if(obj.sum() > threshold_obj): result.append(obj) return result<categorify>
train_data.isna().sum()
Titanic - Machine Learning from Disaster
11,531,970
def get_mask_ind(img_id, df, shape =(768,768)) : masks = df.loc[img_id]['EncodedPixels'] if(type(masks)== float): return [] if(type(masks)== str): masks = [masks] result = [] for mask in masks: img = np.zeros(shape[0]*shape[1], dtype=np.uint8) s = mask.split() for i in range(len(s)//2): start = int(s[2*i])- 1 length =...
for d in df: d['Fare'].fillna(d['Fare'].mean() ,inplace = True )
Titanic - Machine Learning from Disaster
11,531,970
class Score_eval() : def __init__(self): self.segmentation_df = pd.read_csv(SEGMENTATION ).set_index('ImageId') self.score, self.count = 0.0, 0 def put(self,pred,name): true = get_mask_ind(name, self.segmentation_df) self.score += get_score(pred,true) self.count += 1 def evaluate(self): return self.score/self.count<...
test_data.isna().sum()
Titanic - Machine Learning from Disaster
11,531,970
m = to_gpu(Unet34(get_base())) models = UnetModel(m )<define_variables>
train_data['Family'] = train_data.apply(lambda x: x['SibSp'] + x['Parch'], axis = 1) test_data['Family'] = test_data.apply(lambda x: x['SibSp'] + x['Parch'], axis = 1 )
Titanic - Machine Learning from Disaster
11,531,970
sz = 768 bs = 8 md = get_data(sz,bs )<choose_model_class>
train_data.drop(['SibSp','Name','Ticket','Parch'], axis = 1,inplace = True) test_data.drop(['SibSp','Name','Ticket','Parch'], axis = 1, inplace = True )
Titanic - Machine Learning from Disaster
11,531,970
learn = ConvLearner(md, models) learn.models_path = PRETRAINED_SEGMENTATION_PATH learn.load('Unet34_768_1') learn.models_path = PATH<find_best_model_class>
train_df = pd.get_dummies(train_data) test_df = pd.get_dummies(test_data )
Titanic - Machine Learning from Disaster
11,531,970
def model_pred(learner, dl, F_save): learner.model.eval() ; name_list = dl.dataset.fnames num_batchs = len(dl) t = tqdm(iter(dl), leave=False, total=num_batchs) count = 0 for x,y in t: py = to_np(F.sigmoid(learn.model(V(x)))) batch_size = len(py) for i in range(batch_size): F_save(py[i],to_np(y[i]),name_list[count])...
train_df.drop('PassengerId', axis = 1, inplace = True )
Titanic - Machine Learning from Disaster
11,531,970
score = Score_eval() process_pred = lambda yp, y, name : score.put(split_mask(yp),name) model_pred(learn, md.val_dl, process_pred) print(' ',score.evaluate() )<load_from_csv>
y = train_df['Survived'] train_df.drop('Survived', axis=1, inplace = True) train_df.drop('Cabin_T', axis=1, inplace = True) test_df.drop('PassengerId',axis=1, inplace=True) X = train_df X_test = test_df
Titanic - Machine Learning from Disaster
11,531,970
ship_detection = pd.read_csv(DETECTION_TEST_PRED) ship_detection.head()<data_type_conversions>
rfc = RandomForestClassifier()
Titanic - Machine Learning from Disaster
11,531,970
test_names = ship_detection.loc[ship_detection['p_ship'] > 0.5, ['id']]['id'].values.tolist() test_names_nothing = ship_detection.loc[ship_detection['p_ship'] <= 0.5, ['id']]['id'].values.tolist() len(test_names), len(test_names_nothing )<set_options>
param_grid = { 'n_estimators':[200,500,1000], 'max_features':['auto'], 'max_depth': [6, 7, 8], 'criterion': ['entropy'] }
Titanic - Machine Learning from Disaster
11,531,970
md = get_data(sz,bs) learn.set_data(md )<categorify>
CV = GridSearchCV(estimator = rfc, param_grid = param_grid, cv=5) CV.fit(X,y) CV.best_estimator_
Titanic - Machine Learning from Disaster
11,531,970
def decode_mask(mask, shape=(768, 768)) : pixels = mask.T.flatten() pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return ' '.join(str(x)for x in runs )<define_variables>
rfc = RandomForestClassifier(criterion='entropy', max_depth=8, n_estimators=200) ada = AdaBoostClassifier() gbc = GradientBoostingClassifier()
Titanic - Machine Learning from Disaster
11,531,970
ship_list_dict = [] for name in test_names_nothing: ship_list_dict.append({'ImageId':name,'EncodedPixels':np.nan} )<categorify>
rfc.fit(X,y) ada.fit(X,y) gbc.fit(X,y )
Titanic - Machine Learning from Disaster
11,531,970
def enc_test(yp, y, name): masks = split_mask(yp) if(len(masks)== 0): ship_list_dict.append({'ImageId':name,'EncodedPixels':np.nan}) for mask in masks: ship_list_dict.append({'ImageId':name,'EncodedPixels':decode_mask(mask)} )<save_to_csv>
model = StackingCVClassifier(classifiers =(rfc,ada,gbc), meta_classifier = rfc, use_features_in_secondary = True )
Titanic - Machine Learning from Disaster
11,531,970
model_pred(learn, md.test_dl, enc_test) pred_df = pd.DataFrame(ship_list_dict) pred_df.to_csv('submission.csv', index=False )<define_search_space>
model.fit(X.values,y )
Titanic - Machine Learning from Disaster
11,531,970
BATCH_SIZE = 32 EDGE_CROP = 16 GAUSSIAN_NOISE = 0.1 UPSAMPLE_MODE = 'SIMPLE' NET_SCALING =(1, 1) IMG_SCALING =(4, 4) VALID_IMG_COUNT = 600 MAX_TRAIN_STEPS = 30 AUGMENT_BRIGHTNESS = False<define_variables>
print(model.score(X, y))
Titanic - Machine Learning from Disaster
11,531,970
montage_rgb = lambda x: np.stack([montage(x[:, :, :, i])for i in range(x.shape[3])], -1) ship_dir = '.. /input' train_image_dir = os.path.join(ship_dir, 'train') test_image_dir = os.path.join(ship_dir, 'test') def multi_rle_encode(img): labels = label(img) if img.ndim > 2: return [rle_encode(np.sum(labels==k, axis=...
prediction = model.predict(X_test.values )
Titanic - Machine Learning from Disaster
11,531,970
<categorify><EOS>
output = pd.DataFrame({'PassengerId' : test_data.PassengerId, 'Survived' : prediction}) output.to_csv('my_submissions.csv', index = False )
Titanic - Machine Learning from Disaster
6,821,394
<SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<feature_engineering>
warnings.filterwarnings("ignore" )
Titanic - Machine Learning from Disaster
6,821,394
masks['ships'] = masks['EncodedPixels'].map(lambda c_row: 1 if isinstance(c_row, str)else 0) unique_img_ids = masks.groupby('ImageId' ).agg({'ships': 'sum'} ).reset_index() unique_img_ids['has_ship'] = unique_img_ids['ships'].map(lambda x: 1.0 if x>0 else 0.0) unique_img_ids['has_ship_vec'] = unique_img_ids['has_ship...
traindf = pd.read_csv('.. /input/titanic/train.csv' ).set_index('PassengerId') testdf = pd.read_csv('.. /input/titanic/test.csv' ).set_index('PassengerId') submission = pd.read_csv('.. /input/titanic/gender_submission.csv' )
Titanic - Machine Learning from Disaster
6,821,394
train_ids, valid_ids = train_test_split(balanced_train_df, test_size = 0.3, stratify = balanced_train_df['ships']) train_df = pd.merge(masks, train_ids) valid_df = pd.merge(masks, valid_ids) print(train_df.shape[0], 'training masks') print(valid_df.shape[0], 'validation masks' )<categorify>
df = pd.concat([traindf, testdf], axis=0, sort=False) df['Title'] = df.Name.str.split(',' ).str[1].str.split('.' ).str[0].str.strip() df['Title'] = df.Name.str.split(',' ).str[1].str.split('.' ).str[0].str.strip() df['IsWomanOrBoy'] =(( df.Title == 'Master')|(df.Sex == 'female')) df['LastName'] = df.Name.str.split(','...
Titanic - Machine Learning from Disaster
6,821,394
def make_image_gen(in_df, batch_size = BATCH_SIZE): all_batches = list(in_df.groupby('ImageId')) out_rgb = [] out_mask = [] while True: np.random.shuffle(all_batches) for c_img_id, c_masks in all_batches: rgb_path = os.path.join(train_image_dir, c_img_id) c_img = imread(rgb_path) c_mask = np.expand_dims(masks_as_ima...
pd.set_option('max_columns',100 )
Titanic - Machine Learning from Disaster
6,821,394
train_gen = make_image_gen(train_df) train_x, train_y = next(train_gen) print('x', train_x.shape, train_x.min() , train_x.max()) print('y', train_y.shape, train_y.min() , train_y.max() )<train_model>
numerics = ['int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64'] categorical_columns = [] features = train.columns.values.tolist() for col in features: if train[col].dtype in numerics: continue categorical_columns.append(col) for col in categorical_columns: if col in train.columns: le = LabelEncoder() l...
Titanic - Machine Learning from Disaster
6,821,394
%%time valid_x, valid_y = next(make_image_gen(valid_df, VALID_IMG_COUNT)) print(valid_x.shape, valid_y.shape )<set_options>
train = reduce_mem_usage(train )
Titanic - Machine Learning from Disaster
6,821,394
dg_args = dict(featurewise_center = False, samplewise_center = False, rotation_range = 45, width_shift_range = 0.1, height_shift_range = 0.1, shear_range = 0.01, zoom_range = [0.9, 1.25], horizontal_flip = True, vertical_flip = True, fill_mode = 'reflect', data_format = 'channels_last') if AUGMENT_BRIGHTNESS: dg_args[...
test = reduce_mem_usage(test )
Titanic - Machine Learning from Disaster