kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
9,251,987 | train_df = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv')
test_df = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv' )<prepare_x_and_y> | raw_models = model_check(X, y, estimators, cv)
display(raw_models.style.background_gradient(cmap='summer_r')) | Titanic - Machine Learning from Disaster |
9,251,987 | X = train_df.loc[:,'text']
y = train_df.loc[:,'target']<define_variables> | def m_roc(estimators, cv, X, y):
fig, axes = plt.subplots(math.ceil(len(estimators)/ 2),
2,
figsize=(25, 50))
axes = axes.flatten()
for ax, estimator in zip(axes, estimators):
tprs = []
aucs = []
mean_fpr = np.linspace(0, 1, 100)
for i,(train, test)in enumerate(cv.split(X, y)) :
estimator.fit(X.loc[train], y.loc[train])
viz = plot_roc_curve(estimator,
X.loc[test],
y.loc[test],
name='ROC fold {}'.format(i),
alpha=0.3,
lw=1,
ax=ax)
interp_tpr = interp(mean_fpr, viz.fpr, viz.tpr)
interp_tpr[0] = 0.0
tprs.append(interp_tpr)
aucs.append(viz.roc_auc)
ax.plot([0, 1], [0, 1],
linestyle='--',
lw=2,
color='r',
label='Chance',
alpha=.8)
mean_tpr = np.mean(tprs, axis=0)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
std_auc = np.std(aucs)
ax.plot(mean_fpr,
mean_tpr,
color='b',
label=r'Mean ROC(AUC = %0.2f $\pm$ %0.2f)' %
(mean_auc, std_auc),
lw=2,
alpha=.8)
std_tpr = np.std(tprs, axis=0)
tprs_upper = np.minimum(mean_tpr + std_tpr, 1)
tprs_lower = np.maximum(mean_tpr - std_tpr, 0)
ax.fill_between(mean_fpr,
tprs_lower,
tprs_upper,
color='grey',
alpha=.2,
label=r'$\pm$ 1 std.dev.')
ax.set(xlim=[-0.02, 1.02],
ylim=[-0.02, 1.02],
title=f'{estimator.__class__.__name__} ROC')
ax.legend(loc='lower right', prop={'size': 18})
plt.show() | Titanic - Machine Learning from Disaster |
9,251,987 | max_len = 0
for text in X:
max_len = max(max_len, len(text))
max_len<prepare_x_and_y> | m_roc(estimators, cv, X, y ) | Titanic - Machine Learning from Disaster |
9,251,987 | class Dataset(torch.utils.data.Dataset):
def __init__(self,df,y=None,max_len=164):
self.df = df
self.y = y
self.max_len= max_len
self.tokenizer = transformers.RobertaTokenizer.from_pretrained('roberta-base')
def __getitem__(self,index):
row = self.df.iloc[index]
ids,masks = self.get_input_data(row)
data = {}
data['ids'] = ids
data['masks'] = masks
if self.y is not None:
data['out'] = torch.tensor(self.y.iloc[index],dtype=torch.float32)
return data
def __len__(self):
return len(self.df)
def get_input_data(self,row):
row = self.tokenizer.encode(row,add_special_tokens=True,add_prefix_space=True)
padded = row + [0]*(max_len - len(row))
padded = torch.tensor(padded,dtype=torch.int64)
mask = torch.where(padded != 0 , torch.tensor(1),torch.tensor(0))
return padded,mask
<split> | f_imp(estimators, X, y, 14 ) | Titanic - Machine Learning from Disaster |
9,251,987 | train_x,val_x,train_y,val_y = train_test_split(X,y,test_size=0.2,stratify=y)
train_loader = torch.utils.data.DataLoader(Dataset(train_x,train_y),batch_size=16,shuffle=True,num_workers=2)
val_loader = torch.utils.data.DataLoader(Dataset(val_x,val_y),batch_size=16,shuffle=False,num_workers=2 )<normalization> | rf.fit(X, y)
estimator = rf.estimators_[0]
export_graphviz(estimator, out_file='tree.dot',
feature_names = X.columns,
class_names = ['Not Survived','Survived'],
rounded = True, proportion = False,
precision = 2, filled = True)
call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600'])
plt.figure(figsize =(40, 20))
plt.imshow(plt.imread('tree.png'))
plt.axis('off');
plt.show() ; | Titanic - Machine Learning from Disaster |
9,251,987 | class Model(nn.Module):
def __init__(self):
super(Model,self ).__init__()
self.distilBert = transformers.RobertaModel.from_pretrained('roberta-base')
self.l0 = nn.Linear(768,512)
self.l1 = nn.Linear(512,256)
self.l2 = nn.Linear(256,1)
self.d0 = nn.Dropout(0.5)
self.d1 = nn.Dropout(0.5)
self.d2 = nn.Dropout(0.5)
nn.init.normal_(self.l0.weight,std=0.2)
nn.init.normal_(self.l1.weight,std=0.2)
nn.init.normal_(self.l2.weight,std=0.2)
def forward(self,ids,masks):
hid = self.distilBert(ids,attention_mask=masks)
hid = hid[0][:,0]
x = self.d0(hid)
x = self.l0(x)
x = F.leaky_relu(x)
x = self.d1(x)
x = self.l1(x)
x = F.leaky_relu(x)
x = self.d2(x)
x = self.l2(x)
return x
<choose_model_class> | def f_selector(X, y, est, features):
X_train, X_valid, y_train, y_valid = train_test_split(X,
y,
test_size=0.4,
random_state=42)
rfe = RFE(estimator=est, n_features_to_select=features, verbose=1)
rfe.fit(X_train, y_train)
print(dict(zip(X.columns, rfe.ranking_)))
print(X.columns[rfe.support_])
acc = accuracy_score(y_valid, rfe.predict(X_valid))
print("{0:.1%} accuracy on test set.".format(acc))
X_red = X[X_train.columns[rfe.support_].to_list() ]
X_te_red = X_test[X_train.columns[rfe.support_].to_list() ]
return X_red, X_te_red | Titanic - Machine Learning from Disaster |
9,251,987 | model = Model().to('cuda')
criterion = nn.BCEWithLogitsLoss(reduction='mean')
optimizer = torch.optim.AdamW(model.parameters() ,lr=3e-5 )<compute_test_metric> | X_sel, X_test_sel = f_selector(X, y, rf, 11 ) | Titanic - Machine Learning from Disaster |
9,251,987 | def accuracy_score(outputs,labels):
outputs = torch.round(torch.sigmoid(outputs))
correct =(outputs == labels ).sum().float()
return correct/labels.size(0 )<import_modules> | pipe = Pipeline([
('scaler', StandardScaler()),
('reducer', PCA(n_components=2)) ,
])
X_sel_red = pipe.fit_transform(X_sel)
X_test_sel_red = pipe.transform(X_test_sel ) | Titanic - Machine Learning from Disaster |
9,251,987 | from tqdm import tqdm<train_on_grid> | def prob_reg(X, y):
figure = plt.figure(figsize=(20, 40))
h =.02
i = 1
X_train, X_test, y_train, y_test = \
train_test_split(X, y, test_size=.4, random_state=42)
x_min, x_max = X_sel_red[:, 0].min() -.5, X_sel_red[:, 0].max() +.5
y_min, y_max = X_sel_red[:, 1].min() -.5, X_sel_red[:, 1].max() +.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
cm = plt.cm.RdYlGn
cm_bright = ListedColormap(['
ax = plt.subplot(5, 2, i)
for clf in estimators:
ax = plt.subplot(math.ceil(len(estimators)/ 2), 2, i)
clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
if hasattr(clf, "decision_function"):
Z = clf.decision_function(np.c_[xx.ravel() , yy.ravel() ])
else:
Z = clf.predict_proba(np.c_[xx.ravel() , yy.ravel() ])[:, 1]
Z = Z.reshape(xx.shape)
ax.contourf(xx, yy, Z, cmap=cm, alpha=.8)
g = ax.scatter(X_train[:, 0],
X_train[:, 1],
c=y_train,
cmap=cm_bright,
edgecolors='k')
ax.scatter(X_test[:, 0],
X_test[:, 1],
c=y_test,
cmap=cm_bright,
edgecolors='k',
alpha=0.6)
ax.set_xlim(xx.min() , xx.max())
ax.set_ylim(yy.min() , yy.max())
ax.set_title(clf.__class__.__name__)
ax.set_xlabel('PCA 1')
ax.set_ylabel('PCA 2')
plt.legend(handles=g.legend_elements() [0],
labels=['Not Survived', 'Survived'],
framealpha=0.3,
scatterpoints=1)
i += 1
plt.tight_layout()
plt.show() | Titanic - Machine Learning from Disaster |
9,251,987 | epochs = 4
for epoch in range(epochs):
epoch_loss = 0.
model.train()
for data in tqdm(train_loader):
ids = data['ids'].cuda()
masks = data['masks'].cuda()
labels = data['out'].cuda()
labels = labels.unsqueeze(1)
optimizer.zero_grad()
outputs = model(ids,masks)
loss = criterion(outputs,labels)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
print(f"Epoch{epoch+1} loss : {epoch_loss/len(train_loader)}")
print(f"Epoch{epoch+1} accuracy : ",accuracy_score(outputs,labels ).item())
val_loss = 0.
model.eval()
for data in tqdm(val_loader):
ids = data['ids'].cuda()
masks = data['masks'].cuda()
labels = data['out'].cuda()
labels = labels.unsqueeze(1)
outputs = model(ids,masks)
loss = criterion(outputs,labels)
val_loss += loss.item()
print(f"Epoch{epoch+1} val loss : {val_loss/len(val_loader)}")
print(f"Epoch{epoch+1} val accuracy : ",accuracy_score(outputs,labels ).item())
<create_dataframe> | dec_regs(X_sel_red, y, estimators ) | Titanic - Machine Learning from Disaster |
9,251,987 | test_loader = torch.utils.data.DataLoader(Dataset(test_df['text'],y=None),batch_size=16,shuffle=False,num_workers=2 )<find_best_params> | prob_reg(X_sel_red, y ) | Titanic - Machine Learning from Disaster |
9,251,987 | preds = []
for data in test_loader:
ids = data['ids'].cuda()
masks = data['masks'].cuda()
model.eval()
outputs = model(ids,masks)
preds += outputs.cpu().detach().numpy().tolist()
<prepare_output> | pca_models = model_check(X_sel_red, y, estimators, cv)
display(pca_models.style.background_gradient(cmap='summer_r')) | Titanic - Machine Learning from Disaster |
9,251,987 | pred = np.round(1/(1 + np.exp(-np.array(preds))))<prepare_output> | rand_model_full_data = rf.fit(X, y)
print(accuracy_score(y, rand_model_full_data.predict(X)))
y_pred = rand_model_full_data.predict(X_test ) | Titanic - Machine Learning from Disaster |
9,251,987 | <load_from_csv><EOS> | test_df = pd.read_csv('/kaggle/input/titanic/test.csv')
submission_df = pd.DataFrame(columns=['PassengerId', 'Survived'])
submission_df['PassengerId'] = test_df['PassengerId']
submission_df['Survived'] = y_pred
submission_df.to_csv('submission.csv', header=True, index=False)
submission_df.head(10 ) | Titanic - Machine Learning from Disaster |
1,373,360 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<prepare_output> | class KaggleMember() :
kaggle_member_count=0
def __init__(self, name, surname, level=None):
self.name=name.capitalize()
self.surname=surname.upper()
self._set_level(level)
KaggleMember.kaggle_member_count+=1
self.kaggle_id=KaggleMember.kaggle_member_count
def display_number_of_member(self):
print("There are {} members in Kaggle community".format(KaggleMember.kaggle_member_count))
def display_member_info(self):
print("Kaggle Member Full Name:{} {}".format(self.name, self.surname))
print("Level:{:15}".format(self.level))
print("Kaggle ID:",self.kaggle_id)
def _set_level(self, level):
if level is None:
self.level='Novice'
else:
self.level=level.title()
myclass_name='Kaggle Member'
| Titanic - Machine Learning from Disaster |
1,373,360 | sub['target'] = pred<save_to_csv> | warnings.filterwarnings('ignore')
print("Warnings were ignored" ) | Titanic - Machine Learning from Disaster |
1,373,360 | sub.to_csv('submission.csv',index=False )<set_options> | class Information() :
def __init__(self):
print("Information object created")
def _get_missing_values(self,data):
missing_values = data.isnull().sum()
missing_values.sort_values(ascending=False, inplace=True)
return missing_values
def info(self,data):
feature_dtypes=data.dtypes
self.missing_values=self._get_missing_values(data)
print("=" * 50)
print("{:16} {:16} {:25} {:16}".format("Feature Name".upper() ,
"Data Format".upper() ,
"
"Samples".upper()))
for feature_name, dtype, missing_value in zip(self.missing_values.index.values,
feature_dtypes[self.missing_values.index.values],
self.missing_values.values):
print("{:18} {:19} {:19} ".format(feature_name, str(dtype), str(missing_value)) , end="")
for v in data[feature_name].values[:10]:
print(v, end=",")
print()
print("="*50)
| Titanic - Machine Learning from Disaster |
1,373,360 | SEED = 42
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False<load_from_csv> | class Preprocess() :
def __init__(self):
print("Preprocess object created")
def fillna(self, data, fill_strategies):
for column, strategy in fill_strategies.items() :
if strategy == 'None':
data[column] = data[column].fillna('None')
elif strategy == 'Zero':
data[column] = data[column].fillna(0)
elif strategy == 'Mode':
data[column] = data[column].fillna(data[column].mode() [0])
elif strategy == 'Mean':
data[column] = data[column].fillna(data[column].mean())
elif strategy == 'Median':
data[column] = data[column].fillna(data[column].median())
else:
print("{}: There is no such thing as preprocess strategy".format(strategy))
return data
def drop(self, data, drop_strategies):
for column, strategy in drop_strategies.items() :
data=data.drop(labels=[column], axis=strategy)
return data
def feature_engineering(self, data, engineering_strategies=1):
if engineering_strategies==1:
return self._feature_engineering1(data)
return data
def _feature_engineering1(self,data):
data=self._base_feature_engineering(data)
data['FareBin'] = pd.qcut(data['Fare'], 4)
data['AgeBin'] = pd.cut(data['Age'].astype(int), 5)
drop_strategy = {'Age': 1,
'Name': 1,
'Fare': 1}
data = self.drop(data, drop_strategy)
return data
def _base_feature_engineering(self,data):
data['FamilySize'] = data['SibSp'] + data['Parch'] + 1
data['IsAlone'] = 1
data.loc[(data['FamilySize'] > 1), 'IsAlone'] = 0
data['Title'] = data['Name'].str.split(", ", expand=True)[1].str.split('.', expand=True)[0]
min_lengtht = 10
title_names =(data['Title'].value_counts() < min_lengtht)
data['Title'] = data['Title'].apply(lambda x: 'Misc' if title_names.loc[x] == True else x)
return data
def _label_encoder(self,data):
labelEncoder=LabelEncoder()
for column in data.columns.values:
if 'int64'==data[column].dtype or 'float64'==data[column].dtype or 'int64'==data[column].dtype:
continue
labelEncoder.fit(data[column])
data[column]=labelEncoder.transform(data[column])
return data
def _get_dummies(self, data, prefered_columns=None):
if prefered_columns is None:
columns=data.columns.values
non_dummies=None
else:
non_dummies=[col for col in data.columns.values if col not in prefered_columns ]
columns=prefered_columns
dummies_data=[pd.get_dummies(data[col],prefix=col)for col in columns]
if non_dummies is not None:
for non_dummy in non_dummies:
dummies_data.append(data[non_dummy])
return pd.concat(dummies_data, axis=1 ) | Titanic - Machine Learning from Disaster |
1,373,360 | train_data = pd.read_csv(".. /input/nlp-getting-started/train.csv")
train_data.info()
train_data.sample(10 )<load_from_csv> | class PreprocessStrategy() :
def __init__(self):
self.data=None
self._preprocessor=Preprocess()
def strategy(self, data, strategy_type="strategy1"):
self.data=data
if strategy_type=='strategy1':
self._strategy1()
elif strategy_type=='strategy2':
self._strategy2()
return self.data
def _base_strategy(self):
drop_strategy = {'PassengerId': 1,
'Cabin': 1,
'Ticket': 1}
self.data = self._preprocessor.drop(self.data, drop_strategy)
fill_strategy = {'Age': 'Median',
'Fare': 'Median',
'Embarked': 'Mode'}
self.data = self._preprocessor.fillna(self.data, fill_strategy)
self.data = self._preprocessor.feature_engineering(self.data, 1)
self.data = self._preprocessor._label_encoder(self.data)
def _strategy1(self):
self._base_strategy()
self.data=self._preprocessor._get_dummies(self.data,
prefered_columns=['Pclass', 'Sex', 'Parch', 'Embarked', 'Title', 'IsAlone'])
def _strategy2(self):
self._base_strategy()
self.data=self._preprocessor._get_dummies(self.data,
prefered_columns=None ) | Titanic - Machine Learning from Disaster |
1,373,360 | test_data = pd.read_csv(".. /input/nlp-getting-started/test.csv")
test_data.info()
test_data.sample(10 )<train_model> | class GridSearchHelper() :
def __init__(self):
print("GridSearchHelper Created")
self.gridSearchCV=None
self.clf_and_params=list()
self._initialize_clf_and_params()
def _initialize_clf_and_params(self):
clf= KNeighborsClassifier()
params={'n_neighbors':[5,7,9,11,13,15],
'leaf_size':[1,2,3,5],
'weights':['uniform', 'distance']
}
self.clf_and_params.append(( clf, params))
clf=LogisticRegression()
params={'penalty':['l1', 'l2'],
'C':np.logspace(0, 4, 10)
}
self.clf_and_params.append(( clf, params))
clf = SVC()
params = [ {'C': [1, 10, 100, 1000], 'kernel': ['linear']},
{'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']}]
self.clf_and_params.append(( clf, params))
clf=DecisionTreeClassifier()
params={'max_features': ['auto', 'sqrt', 'log2'],
'min_samples_split': [2,3,4,5,6,7,8,9,10,11,12,13,14,15],
'min_samples_leaf':[1],
'random_state':[123]}
self.clf_and_params.append(( clf,params))
clf = RandomForestClassifier()
params = {'n_estimators': [4, 6, 9],
'max_features': ['log2', 'sqrt','auto'],
'criterion': ['entropy', 'gini'],
'max_depth': [2, 3, 5, 10],
'min_samples_split': [2, 3, 5],
'min_samples_leaf': [1,5,8]
}
self.clf_and_params.append(( clf, params))
def fit_predict_save(self, X_train, X_test, y_train, submission_id, strategy_type):
self.X_train=X_train
self.X_test=X_test
self.y_train=y_train
self.submission_id=submission_id
self.strategy_type=strategy_type
clf_and_params = self.get_clf_and_params()
models=[]
self.results={}
for clf, params in clf_and_params:
self.current_clf_name = clf.__class__.__name__
grid_search_clf = GridSearchCV(clf, params, cv=5)
grid_search_clf.fit(self.X_train, self.y_train)
self.Y_pred = grid_search_clf.predict(self.X_test)
clf_train_acc = round(grid_search_clf.score(self.X_train, self.y_train)* 100, 2)
print(self.current_clf_name, " trained and used for prediction on test data...")
self.results[self.current_clf_name]=clf_train_acc
models.append(clf)
self.save_result()
print()
def show_result(self):
for clf_name, train_acc in self.results.items() :
print("{} train accuracy is {:.3f}".format(clf_name, train_acc))
def save_result(self):
Submission = pd.DataFrame({'PassengerId': self.submission_id,
'Survived': self.Y_pred})
file_name="{}_{}.csv".format(self.strategy_type,self.current_clf_name.lower())
Submission.to_csv(file_name, index=False)
print("Submission saved file name: ",file_name)
def get_clf_and_params(self):
return self.clf_and_params
def add(self,clf, params):
self.clf_and_params.append(( clf, params)) | Titanic - Machine Learning from Disaster |
1,373,360 | print('Training Set Shape = {}'.format(train_data.shape))
print('Test Set Shape = {}'.format(test_data.shape))<count_unique_values> | class Visualizer:
def __init__(self):
print("Visualizer object created!")
def RandianViz(self, X, y, number_of_features):
if number_of_features is None:
features=X.columns.values
else:
features=X.columns.values[:number_of_features]
fig, ax=plt.subplots(1, figsize=(15,12))
radViz=RadViz(classes=['survived', 'not survived'], features=features)
radViz.fit(X, y)
radViz.transform(X)
radViz.poof()
| Titanic - Machine Learning from Disaster |
1,373,360 | mislabeled_df = train_data.groupby(['text'] ).nunique().sort_values(by='target', ascending=False)
mislabeled_df = mislabeled_df[mislabeled_df['target'] > 1]['target']
mislabeled_list = mislabeled_df.index.tolist()
mislabeled_list<feature_engineering> | class ObjectOrientedTitanic() :
def __init__(self, train, test):
print("ObjectOrientedTitanic object created")
self.testPassengerID=test['PassengerId']
self.number_of_train=train.shape[0]
self.y_train=train['Survived']
self.train=train.drop('Survived', axis=1)
self.test=test
self.all_data=self._get_all_data()
self._info=Information()
self.preprocessStrategy = PreprocessStrategy()
self.visualizer=Visualizer()
self.gridSearchHelper = GridSearchHelper()
def _get_all_data(self):
return pd.concat([self.train, self.test])
def information(self):
self._info.info(self.all_data)
def preprocessing(self, strategy_type):
self.strategy_type=strategy_type
self.all_data = self.preprocessStrategy.strategy(self._get_all_data() , strategy_type)
def visualize(self, visualizer_type, number_of_features=None):
self._get_train_and_test()
if visualizer_type=="RadViz":
self.visualizer.RandianViz(X=self.X_train,
y=self.y_train,
number_of_features=number_of_features)
def machine_learning(self):
self._get_train_and_test()
self.gridSearchHelper.fit_predict_save(self.X_train,
self.X_test,
self.y_train,
self.testPassengerID,
self.strategy_type)
def show_result(self):
self.gridSearchHelper.show_result()
def _get_train_and_test(self):
self.X_train=self.all_data[:self.number_of_train]
self.X_test=self.all_data[self.number_of_train:]
| Titanic - Machine Learning from Disaster |
1,373,360 | train_data['target_relabeled'] = train_data['target'].copy()
train_data.loc[train_data['text'] == 'like for the music video I want some real action shit like burning buildings and police chases not some weak ben winston shit', 'target_relabeled'] = 0
train_data.loc[train_data['text'] == 'Hellfire is surrounded by desires so be careful and donÛªt let your desires control you!
train_data.loc[train_data['text'] == 'To fight bioterrorism sir.', 'target_relabeled'] = 0
train_data.loc[train_data['text'] == '.POTUS
train_data.loc[train_data['text'] == 'CLEARED:incident with injury:I-495 inner loop Exit 31 - MD 97/Georgia Ave Silver Spring', 'target_relabeled'] = 1
train_data.loc[train_data['text'] == '
train_data.loc[train_data['text'] == 'In
train_data.loc[train_data['text'] == 'Who is bringing the tornadoes and floods.Who is bringing the climate change.God is after America He is plaguing her
train_data.loc[train_data['text'] == 'RT NotExplained: The only known image of infamous hijacker D.B.Cooper.http://t.co/JlzK2HdeTG', 'target_relabeled'] = 1
train_data.loc[train_data['text'] == "Mmmmmm I'm burning.... I'm burning buildings I'm building.... Oooooohhhh oooh ooh...", 'target_relabeled'] = 0
train_data.loc[train_data['text'] == "wowo--=== 12000 Nigerian refugees repatriated from Cameroon", 'target_relabeled'] = 0
train_data.loc[train_data['text'] == "He came to a land which was engulfed in tribal war and turned it into a land of peace i.e.Madinah.
train_data.loc[train_data['text'] == "Hellfire! We donÛªt even want to think about it or mention it so letÛªs not do anything that leads to it
train_data.loc[train_data['text'] == "The Prophet(peace be upon him)said 'Save yourself from Hellfire even if it is by giving half a date in charity.'", 'target_relabeled'] = 0
train_data.loc[train_data['text'] == "Caution: breathing may be hazardous to your health.", 'target_relabeled'] = 1
train_data.loc[train_data['text'] == "I Pledge Allegiance To The P.O.P.E.And The Burning Buildings of Epic City.??????", 'target_relabeled'] = 0
train_data.loc[train_data['text'] == "
train_data.loc[train_data['text'] == "that horrible sinking feeling when youÛªve been at home on your phone for a while and you realise its been on 3G this whole time", 'target_relabeled'] = 0<categorify> | train = pd.read_csv(".. /input/train.csv")
test = pd.read_csv(".. /input/test.csv")
objectOrientedTitanic=ObjectOrientedTitanic(train, test)
| Titanic - Machine Learning from Disaster |
1,373,360 | <split><EOS> | objectOrientedTitanic.machine_learning() | Titanic - Machine Learning from Disaster |
2,725,427 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<define_variables> | sns.set(style="darkgrid")
warnings.filterwarnings('ignore')
SEED = 42 | Titanic - Machine Learning from Disaster |
2,725,427 | TEXT = data.Field(tokenize = 'spacy', batch_first=True, include_lengths = True)
LABEL = data.LabelField(dtype = torch.float, batch_first=True )<split> | def concat_df(train_data, test_data):
return pd.concat([train_data, test_data], sort=True ).reset_index(drop=True)
def divide_df(all_data):
return all_data.loc[:890], all_data.loc[891:].drop(['Survived'], axis=1)
df_train = pd.read_csv('.. /input/train.csv')
df_test = pd.read_csv('.. /input/test.csv')
df_all = concat_df(df_train, df_test)
df_train.name = 'Training Set'
df_test.name = 'Test Set'
df_all.name = 'All Set'
dfs = [df_train, df_test]
print('Number of Training Examples = {}'.format(df_train.shape[0]))
print('Number of Test Examples = {}
'.format(df_test.shape[0]))
print('Training X Shape = {}'.format(df_train.shape))
print('Training y Shape = {}
'.format(df_train['Survived'].shape[0]))
print('Test X Shape = {}'.format(df_test.shape))
print('Test y Shape = {}
'.format(df_test.shape[0]))
print(df_train.columns)
print(df_test.columns ) | Titanic - Machine Learning from Disaster |
2,725,427 | class DataFrameDataset(data.Dataset):
def __init__(self, df, fields, is_test=False, **kwargs):
examples = []
for i, row in df.iterrows() :
label = row.target_relabeled if not is_test else None
text = row.text
examples.append(data.Example.fromlist([text, label], fields))
super().__init__(examples, fields, **kwargs)
@staticmethod
def sort_key(ex):
return len(ex.text)
@classmethod
def splits(cls, fields, train_df, val_df=None, test_df=None, **kwargs):
train_data, val_data, test_data =(None, None, None)
data_field = fields
if train_df is not None:
train_data = cls(train_df.copy() , data_field, **kwargs)
if val_df is not None:
val_data = cls(val_df.copy() , data_field, **kwargs)
if test_df is not None:
test_data = cls(test_df.copy() , data_field, False, **kwargs)
return tuple(d for d in(train_data, val_data, test_data)if d is not None )<create_dataframe> | def display_missing(df):
for col in df.columns.tolist() :
print('{} column missing values: {}'.format(col, df[col].isnull().sum()))
print('
')
for df in dfs:
print('{}'.format(df.name))
display_missing(df ) | Titanic - Machine Learning from Disaster |
2,725,427 | fields = [('text',TEXT),('label',LABEL)]
train_ds, val_ds = DataFrameDataset.splits(fields, train_df=train_df, val_df=valid_df )<load_pretrained> | age_by_pclass_sex = df_all.groupby(['Sex', 'Pclass'] ).median() ['Age']
for pclass in range(1, 4):
for sex in ['female', 'male']:
print('Median age of Pclass {} {}s: {}'.format(pclass, sex, age_by_pclass_sex[sex][pclass]))
print('Median age of all passengers: {}'.format(df_all['Age'].median()))
df_all['Age'] = df_all.groupby(['Sex', 'Pclass'])['Age'].apply(lambda x: x.fillna(x.median())) | Titanic - Machine Learning from Disaster |
2,725,427 | vectors = Vectors(name='.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec', cache='./')
MAX_VOCAB_SIZE = 100000
TEXT.build_vocab(train_ds,
max_size = MAX_VOCAB_SIZE,
vectors = vectors,
unk_init = torch.Tensor.zero_)
LABEL.build_vocab(train_ds )<count_unique_values> | df_all[df_all['Embarked'].isnull() ] | Titanic - Machine Learning from Disaster |
2,725,427 | print("Size of TEXT vocabulary:",len(TEXT.vocab))
print("Size of LABEL vocabulary:",len(LABEL.vocab))
print(TEXT.vocab.freqs.most_common(10))
<split> | df_all['Embarked'] = df_all['Embarked'].fillna('S' ) | Titanic - Machine Learning from Disaster |
2,725,427 | BATCH_SIZE = 64
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_iterator, valid_iterator = data.BucketIterator.splits(
(train_ds, val_ds),
batch_size = BATCH_SIZE,
sort_within_batch = True,
device = device )<init_hyperparams> | df_all[df_all['Fare'].isnull() ] | Titanic - Machine Learning from Disaster |
2,725,427 | num_epochs = 25
learning_rate = 0.001
INPUT_DIM = len(TEXT.vocab)
EMBEDDING_DIM = 300
HIDDEN_DIM = 256
OUTPUT_DIM = 1
N_LAYERS = 2
BIDIRECTIONAL = True
DROPOUT = 0.2
PAD_IDX = TEXT.vocab.stoi[TEXT.pad_token]<choose_model_class> | med_fare = df_all.groupby(['Pclass', 'Parch', 'SibSp'] ).Fare.median() [3][0][0]
df_all['Fare'] = df_all['Fare'].fillna(med_fare ) | Titanic - Machine Learning from Disaster |
2,725,427 | class LSTM_net(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers,
bidirectional, dropout, pad_idx):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx = pad_idx)
self.rnn = nn.LSTM(embedding_dim,
hidden_dim,
num_layers=n_layers,
bidirectional=bidirectional,
dropout=dropout,
batch_first=True)
self.fc1 = nn.Linear(hidden_dim * 2, hidden_dim)
self.fc2 = nn.Linear(hidden_dim, 1)
self.dropout = nn.Dropout(dropout)
def forward(self, text, text_lengths):
embedded = self.embedding(text)
packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, text_lengths, batch_first=True)
packed_output,(hidden, cell)= self.rnn(packed_embedded)
hidden = self.dropout(torch.cat(( hidden[-2,:,:], hidden[-1,:,:]), dim = 1))
output = self.fc1(hidden)
output = self.dropout(self.fc2(output))
return output<choose_model_class> | idx = df_all[df_all['Deck'] == 'T'].index
df_all.loc[idx, 'Deck'] = 'A' | Titanic - Machine Learning from Disaster |
2,725,427 | model = LSTM_net(INPUT_DIM,
EMBEDDING_DIM,
HIDDEN_DIM,
OUTPUT_DIM,
N_LAYERS,
BIDIRECTIONAL,
DROPOUT,
PAD_IDX )<find_best_params> | df_all_decks_survived = df_all.groupby(['Deck', 'Survived'] ).count().drop(columns=['Sex', 'Age', 'SibSp', 'Parch', 'Fare',
'Embarked', 'Pclass', 'Cabin', 'PassengerId', 'Ticket'] ).rename(columns={'Name':'Count'} ).transpose()
def get_survived_dist(df):
surv_counts = {'A':{}, 'B':{}, 'C':{}, 'D':{}, 'E':{}, 'F':{}, 'G':{}, 'M':{}}
decks = df.columns.levels[0]
for deck in decks:
for survive in range(0, 2):
surv_counts[deck][survive] = df[deck][survive][0]
df_surv = pd.DataFrame(surv_counts)
surv_percentages = {}
for col in df_surv.columns:
surv_percentages[col] = [(count / df_surv[col].sum())* 100 for count in df_surv[col]]
return surv_counts, surv_percentages
def display_surv_dist(percentages):
df_survived_percentages = pd.DataFrame(percentages ).transpose()
deck_names =('A', 'B', 'C', 'D', 'E', 'F', 'G', 'M')
bar_count = np.arange(len(deck_names))
bar_width = 0.85
not_survived = df_survived_percentages[0]
survived = df_survived_percentages[1]
plt.figure(figsize=(20, 10))
plt.bar(bar_count, not_survived, color='
plt.bar(bar_count, survived, bottom=not_survived, color='
plt.xlabel('Deck', size=15, labelpad=20)
plt.ylabel('Survival Percentage', size=15, labelpad=20)
plt.xticks(bar_count, deck_names)
plt.tick_params(axis='x', labelsize=15)
plt.tick_params(axis='y', labelsize=15)
plt.legend(loc='upper left', bbox_to_anchor=(1, 1), prop={'size': 15})
plt.title('Survival Percentage in Decks', size=18, y=1.05)
plt.show()
all_surv_count, all_surv_per = get_survived_dist(df_all_decks_survived)
display_surv_dist(all_surv_per ) | Titanic - Machine Learning from Disaster |
2,725,427 | print(model)
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f'The model has {count_parameters(model):,} trainable parameters' )<feature_engineering> | df_all['Deck'] = df_all['Deck'].replace(['A', 'B', 'C'], 'ABC')
df_all['Deck'] = df_all['Deck'].replace(['D', 'E'], 'DE')
df_all['Deck'] = df_all['Deck'].replace(['F', 'G'], 'FG')
df_all['Deck'].value_counts() | Titanic - Machine Learning from Disaster |
2,725,427 | pretrained_embeddings = TEXT.vocab.vectors
model.embedding.weight.data.copy_(pretrained_embeddings)
model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM )<compute_test_metric> | df_all.drop(['Cabin'], inplace=True, axis=1)
df_train, df_test = divide_df(df_all)
dfs = [df_train, df_test]
for df in dfs:
display_missing(df ) | Titanic - Machine Learning from Disaster |
2,725,427 | def binary_accuracy(preds, y):
rounded_preds = torch.round(torch.sigmoid(preds))
correct =(rounded_preds == y ).float()
acc = correct.sum() / len(correct)
return acc<train_on_grid> | corr = df_train_corr_nd['Correlation Coefficient'] > 0.1
df_train_corr_nd[corr] | Titanic - Machine Learning from Disaster |
2,725,427 | def train(model, iterator, optimizer, criterion):
epoch_loss = 0
epoch_acc = 0
model.train()
for batch in iterator:
text, text_lengths = batch.text
optimizer.zero_grad()
predictions = model(text, text_lengths ).squeeze(1)
loss = criterion(predictions, batch.label)
acc = binary_accuracy(predictions, batch.label)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator )<compute_train_metric> | corr = df_test_corr_nd['Correlation Coefficient'] > 0.1
df_test_corr_nd[corr] | Titanic - Machine Learning from Disaster |
2,725,427 | def evaluate(model, iterator, criterion):
epoch_loss = 0
epoch_acc = 0
model.eval()
with torch.no_grad() :
for batch in iterator:
text, text_lengths = batch.text
predictions = model(text, text_lengths ).squeeze(1)
loss = criterion(predictions, batch.label)
acc = binary_accuracy(predictions, batch.label)
epoch_loss += loss.item()
epoch_acc += acc.item()
return epoch_loss / len(iterator), epoch_acc / len(iterator )<choose_model_class> | df_all = concat_df(df_train, df_test)
df_all.head() | Titanic - Machine Learning from Disaster |
2,725,427 | t = time.time()
best_valid_loss = float('inf')
model.to(device)
criterion = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters() , lr=learning_rate)
for epoch in range(num_epochs):
train_loss, train_acc = train(model, train_iterator, optimizer, criterion)
valid_loss, valid_acc = evaluate(model, valid_iterator, criterion)
print(f'\tTrain Loss: {train_loss:.4f} | Train Acc: {train_acc*100:.4f}%')
print(f'\t Val.Loss: {valid_loss:.4f} | Val.Acc: {valid_acc*100:.4f}%')
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict() , 'best_model.pt')
print(f'time:{time.time() -t:.3f}' )<predict_on_test> | df_all['Fare'] = pd.qcut(df_all['Fare'], 13 ) | Titanic - Machine Learning from Disaster |
2,725,427 | nlp = spacy.load('en')
def predict(model, sentence):
tokenized = [tok.text for tok in nlp.tokenizer(sentence)]
indexed = [TEXT.vocab.stoi[t] for t in tokenized]
length = [len(indexed)]
tensor = torch.LongTensor(indexed ).to(device)
tensor = tensor.unsqueeze(1 ).T
length_tensor = torch.LongTensor(length)
prediction = model(tensor, length_tensor ).squeeze(1)
rounded_preds = torch.round(torch.sigmoid(prediction))
predict_class = rounded_preds.tolist() [0]
return predict_class<predict_on_test> | df_all['Age'] = pd.qcut(df_all['Age'], 10 ) | Titanic - Machine Learning from Disaster |
2,725,427 | PATH = ".. /working/best_model.pt"
model.load_state_dict(torch.load(PATH))
predicts = []
for i in range(len(test_data.text)) :
predict_class = predict(model, test_data.text[i])
predicts.append(int(predict_class))<load_from_csv> | df_all['Ticket_Frequency'] = df_all.groupby('Ticket')['Ticket'].transform('count' ) | Titanic - Machine Learning from Disaster |
2,725,427 | submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv")
submission['target'] = predicts
submission<save_to_csv> | df_all['Title'] = df_all['Name'].str.split(', ', expand=True)[1].str.split('.', expand=True)[0]
df_all['Is_Married'] = 0
df_all['Is_Married'].loc[df_all['Title'] == 'Mrs'] = 1 | Titanic - Machine Learning from Disaster |
2,725,427 | submission.to_csv('submission.csv',index=False )<merge> | def extract_surname(data):
families = []
for i in range(len(data)) :
name = data.iloc[i]
if '(' in name:
name_no_bracket = name.split('(')[0]
else:
name_no_bracket = name
family = name_no_bracket.split(',')[0]
title = name_no_bracket.split(',')[1].strip().split(' ')[0]
for c in string.punctuation:
family = family.replace(c, '' ).strip()
families.append(family)
return families
df_all['Family'] = extract_surname(df_all['Name'])
df_train = df_all.loc[:890]
df_test = df_all.loc[891:]
dfs = [df_train, df_test] | Titanic - Machine Learning from Disaster |
2,725,427 | gt_df = pd.read_csv(".. /input/disasters-on-social-media/socialmedia-disaster-tweets-DFE.csv", encoding='latin_1')
gt_df = gt_df[['choose_one', 'text']]
gt_df['target'] =(gt_df['choose_one']=='Relevant' ).astype(int)
gt_df['id'] = gt_df.index
merged_df = pd.merge(test_data, gt_df, on='id')
merged_df<prepare_x_and_y> | mean_survival_rate = np.mean(df_train['Survived'])
train_family_survival_rate = []
train_family_survival_rate_NA = []
test_family_survival_rate = []
test_family_survival_rate_NA = []
for i in range(len(df_train)) :
if df_train['Family'][i] in family_rates:
train_family_survival_rate.append(family_rates[df_train['Family'][i]])
train_family_survival_rate_NA.append(1)
else:
train_family_survival_rate.append(mean_survival_rate)
train_family_survival_rate_NA.append(0)
for i in range(len(df_test)) :
if df_test['Family'].iloc[i] in family_rates:
test_family_survival_rate.append(family_rates[df_test['Family'].iloc[i]])
test_family_survival_rate_NA.append(1)
else:
test_family_survival_rate.append(mean_survival_rate)
test_family_survival_rate_NA.append(0)
df_train['Family_Survival_Rate'] = train_family_survival_rate
df_train['Family_Survival_Rate_NA'] = train_family_survival_rate_NA
df_test['Family_Survival_Rate'] = test_family_survival_rate
df_test['Family_Survival_Rate_NA'] = test_family_survival_rate_NA
train_ticket_survival_rate = []
train_ticket_survival_rate_NA = []
test_ticket_survival_rate = []
test_ticket_survival_rate_NA = []
for i in range(len(df_train)) :
if df_train['Ticket'][i] in ticket_rates:
train_ticket_survival_rate.append(ticket_rates[df_train['Ticket'][i]])
train_ticket_survival_rate_NA.append(1)
else:
train_ticket_survival_rate.append(mean_survival_rate)
train_ticket_survival_rate_NA.append(0)
for i in range(len(df_test)) :
if df_test['Ticket'].iloc[i] in ticket_rates:
test_ticket_survival_rate.append(ticket_rates[df_test['Ticket'].iloc[i]])
test_ticket_survival_rate_NA.append(1)
else:
test_ticket_survival_rate.append(mean_survival_rate)
test_ticket_survival_rate_NA.append(0)
df_train['Ticket_Survival_Rate'] = train_ticket_survival_rate
df_train['Ticket_Survival_Rate_NA'] = train_ticket_survival_rate_NA
df_test['Ticket_Survival_Rate'] = test_ticket_survival_rate
df_test['Ticket_Survival_Rate_NA'] = test_ticket_survival_rate_NA | Titanic - Machine Learning from Disaster |
2,725,427 | target_df = merged_df[['id', 'target']]
target_df<save_to_csv> | for df in [df_train, df_test]:
df['Survival_Rate'] =(df['Ticket_Survival_Rate'] + df['Family_Survival_Rate'])/ 2
df['Survival_Rate_NA'] =(df['Ticket_Survival_Rate_NA'] + df['Family_Survival_Rate_NA'])/ 2 | Titanic - Machine Learning from Disaster |
2,725,427 | target_df.to_csv('perfect_submission.csv', index=False )<compute_test_metric> | non_numeric_features = ['Embarked', 'Sex', 'Deck', 'Title', 'Family_Size_Grouped', 'Age', 'Fare']
for df in dfs:
for feature in non_numeric_features:
df[feature] = LabelEncoder().fit_transform(df[feature] ) | Titanic - Machine Learning from Disaster |
2,725,427 | target_df["predict"] = list(submission.target)
print('\t\tCLASSIFICATIION METRICS
')
print(metrics.classification_report(target_df.target, target_df.predict))<set_options> | cat_features = ['Pclass', 'Sex', 'Deck', 'Embarked', 'Title', 'Family_Size_Grouped']
encoded_features = []
for df in dfs:
for feature in cat_features:
encoded_feat = OneHotEncoder().fit_transform(df[feature].values.reshape(-1, 1)).toarray()
n = df[feature].nunique()
cols = ['{}_{}'.format(feature, n)for n in range(1, n + 1)]
encoded_df = pd.DataFrame(encoded_feat, columns=cols)
encoded_df.index = df.index
encoded_features.append(encoded_df)
df_train = pd.concat([df_train, *encoded_features[:6]], axis=1)
df_test = pd.concat([df_test, *encoded_features[6:]], axis=1 ) | Titanic - Machine Learning from Disaster |
2,725,427 | plt.style.use('ggplot')
warnings.filterwarnings('ignore')
<define_variables> | df_all = concat_df(df_train, df_test)
drop_cols = ['Deck', 'Embarked', 'Family', 'Family_Size', 'Family_Size_Grouped', 'Survived',
'Name', 'Parch', 'PassengerId', 'Pclass', 'Sex', 'SibSp', 'Ticket', 'Title',
'Ticket_Survival_Rate', 'Family_Survival_Rate', 'Ticket_Survival_Rate_NA', 'Family_Survival_Rate_NA']
df_all.drop(columns=drop_cols, inplace=True)
df_all.head() | Titanic - Machine Learning from Disaster |
2,725,427 | def seed_everything(seed):
os.environ['PYTHONHASHSEED']=str(seed)
tf.random.set_seed(seed)
np.random.seed(seed)
random.seed(seed)
seed_everything(34 )<load_from_csv> | X_train = StandardScaler().fit_transform(df_train.drop(columns=drop_cols))
y_train = df_train['Survived'].values
X_test = StandardScaler().fit_transform(df_test.drop(columns=drop_cols))
print('X_train shape: {}'.format(X_train.shape))
print('y_train shape: {}'.format(y_train.shape))
print('X_test shape: {}'.format(X_test.shape)) | Titanic - Machine Learning from Disaster |
2,725,427 | train = pd.read_csv('.. /input/nlp-getting-started/train.csv')
test = pd.read_csv('.. /input/nlp-getting-started/test.csv')
train.head()<categorify> | single_best_model = RandomForestClassifier(criterion='gini',
n_estimators=1100,
max_depth=5,
min_samples_split=4,
min_samples_leaf=5,
max_features='auto',
oob_score=True,
random_state=SEED,
n_jobs=-1,
verbose=1)
leaderboard_model = RandomForestClassifier(criterion='gini',
n_estimators=1750,
max_depth=7,
min_samples_split=6,
min_samples_leaf=6,
max_features='auto',
oob_score=True,
random_state=SEED,
n_jobs=-1,
verbose=1 ) | Titanic - Machine Learning from Disaster |
2,725,427 | test_id = test['id']
columns = {'id', 'location'}
train = train.drop(columns = columns)
test = test.drop(columns = columns)
train['keyword'] = train['keyword'].fillna('unknown')
test['keyword'] = test['keyword'].fillna('unknown')
train['text'] = train['text'] + ' ' + train['keyword']
test['text'] = test['text'] + ' ' + test['keyword']
columns = {'keyword'}
train = train.drop(columns = columns)
test = test.drop(columns = columns)
total = train.append(test )<feature_engineering> | N = 5
oob = 0
probs = pd.DataFrame(np.zeros(( len(X_test), N * 2)) , columns=['Fold_{}_Prob_{}'.format(i, j)for i in range(1, N + 1)for j in range(2)])
importances = pd.DataFrame(np.zeros(( X_train.shape[1], N)) , columns=['Fold_{}'.format(i)for i in range(1, N + 1)], index=df_all.columns)
fprs, tprs, scores = [], [], []
skf = StratifiedKFold(n_splits=N, random_state=N, shuffle=True)
for fold,(trn_idx, val_idx)in enumerate(skf.split(X_train, y_train), 1):
print('Fold {}
'.format(fold))
leaderboard_model.fit(X_train[trn_idx], y_train[trn_idx])
trn_fpr, trn_tpr, trn_thresholds = roc_curve(y_train[trn_idx], leaderboard_model.predict_proba(X_train[trn_idx])[:, 1])
trn_auc_score = auc(trn_fpr, trn_tpr)
val_fpr, val_tpr, val_thresholds = roc_curve(y_train[val_idx], leaderboard_model.predict_proba(X_train[val_idx])[:, 1])
val_auc_score = auc(val_fpr, val_tpr)
scores.append(( trn_auc_score, val_auc_score))
fprs.append(val_fpr)
tprs.append(val_tpr)
probs.loc[:, 'Fold_{}_Prob_0'.format(fold)] = leaderboard_model.predict_proba(X_test)[:, 0]
probs.loc[:, 'Fold_{}_Prob_1'.format(fold)] = leaderboard_model.predict_proba(X_test)[:, 1]
importances.iloc[:, fold - 1] = leaderboard_model.feature_importances_
oob += leaderboard_model.oob_score_ / N
print('Fold {} OOB Score: {}
'.format(fold, leaderboard_model.oob_score_))
print('Average OOB Score: {}'.format(oob)) | Titanic - Machine Learning from Disaster |
2,725,427 | total['unique word count'] = total['text'].apply(lambda x: len(set(x.split())))
total['stopword count'] = total['text'].apply(lambda x: len([i for i in x.lower().split() if i in wordcloud.STOPWORDS]))
total['stopword ratio'] = total['stopword count'] / total['word count']
total['punctuation count'] = total['text'].apply(lambda x: len([i for i in str(x)if i in string.punctuation]))
train = total[:len(train)]
disaster = train['target'] == 1
fig, axes = plt.subplots(4, figsize=(20, 30))
graph1 = sns.kdeplot(train.loc[~disaster]['unique word count'], shade = True, label = 'Not Disaster', ax=axes[0])
graph1 = sns.kdeplot(train.loc[disaster]['unique word count'], shade = True, label = 'Disaster', ax=axes[0])
graph1.set_title('Distribution of Unique Word Count')
graph2 = sns.kdeplot(train.loc[~disaster]['stopword count'], shade = True, label = 'Not Disaster', ax=axes[1])
graph2 = sns.kdeplot(train.loc[disaster]['stopword count'], shade = True, label = 'Disaster', ax=axes[1])
graph2.set_title('Distribution of Stopword Word Count')
graph3 = sns.kdeplot(train.loc[~disaster]['punctuation count'], shade = True, label = 'Not Disaster', ax=axes[2], bw = 1)
graph3 = sns.kdeplot(train.loc[disaster]['punctuation count'], shade = True, label = 'Disaster', ax=axes[2], bw = 1)
graph3.set_title('Distribution of Punctuation Count')
graph4 = sns.kdeplot(train.loc[~disaster]['stopword ratio'], shade = True, label = 'Not Disaster', ax=axes[3], bw =.05)
graph4 = sns.kdeplot(train.loc[disaster]['stopword ratio'], shade = True, label = 'Disaster', ax=axes[3], bw =.05)
graph4.set_title('Distribution of Stopword Ratio')
fig.tight_layout()
plt.show()<string_transform> | class_survived = [col for col in probs.columns if col.endswith('Prob_1')]
probs['1'] = probs[class_survived].sum(axis=1)/ N
probs['0'] = probs.drop(columns=class_survived ).sum(axis=1)/ N
probs['pred'] = 0
pos = probs[probs['1'] >= 0.5].index
probs.loc[pos, 'pred'] = 1
y_pred = probs['pred'].astype(int)
submission_df = pd.DataFrame(columns=['PassengerId', 'Survived'])
submission_df['PassengerId'] = df_test['PassengerId']
submission_df['Survived'] = y_pred.values
submission_df.to_csv('submissions.csv', header=True, index=False)
submission_df.head(10 ) | Titanic - Machine Learning from Disaster |
11,548,643 | def remove_punctuation(x):
return x.translate(str.maketrans('', '', string.punctuation))
def remove_stopwords(x):
return ' '.join([i for i in x.split() if i not in wordcloud.STOPWORDS])
def remove_less_than(x):
return ' '.join([i for i in x.split() if len(i)> 3])
def remove_non_alphabet(x):
return ' '.join([i for i in x.split() if i.isalpha() ])
def strip_all_entities(x):
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x ).split() )<drop_column> | !pip install fastai2 | Titanic - Machine Learning from Disaster |
11,548,643 | strip_all_entities('@shawn Titanic
Times: Telegraph.co.ukTitanic tragedy could have been preve...http://bet.ly/tuN2wx' )<string_transform> | !pip install fastcore==0.1.35 | Titanic - Machine Learning from Disaster |
11,548,643 | !pip install autocorrect
def spell_check(x):
spell = Speller(lang='en')
return " ".join([spell(i)for i in x.split() ])
mispelled = 'Pleaze spelcheck this sentince'
spell_check(mispelled )<feature_engineering> | fastcore.__version__ | Titanic - Machine Learning from Disaster |
11,548,643 | PROCESS_TWEETS = False
if PROCESS_TWEETS:
total['text'] = total['text'].apply(lambda x: x.lower())
total['text'] = total['text'].apply(lambda x: re.sub(r'https?://\S+|www\.\S+', '', x, flags = re.MULTILINE))
total['text'] = total['text'].apply(remove_punctuation)
total['text'] = total['text'].apply(remove_stopwords)
total['text'] = total['text'].apply(remove_less_than)
total['text'] = total['text'].apply(remove_non_alphabet)
total['text'] = total['text'].apply(spell_check )<define_variables> | fastai2.__version__ | Titanic - Machine Learning from Disaster |
11,548,643 | contractions = {
"ain't": "am not / are not / is not / has not / have not",
"aren't": "are not / am not",
"can't": "cannot",
"can't've": "cannot have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"couldn't've": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he had / he would",
"he'd've": "he would have",
"he'll": "he shall / he will",
"he'll've": "he shall have / he will have",
"he's": "he has / he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how has / how is / how does",
"I'd": "I had / I would",
"I'd've": "I would have",
"I'll": "I shall / I will",
"I'll've": "I shall have / I will have",
"I'm": "I am",
"I've": "I have",
"isn't": "is not",
"it'd": "it had / it would",
"it'd've": "it would have",
"it'll": "it shall / it will",
"it'll've": "it shall have / it will have",
"it's": "it has / it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she had / she would",
"she'd've": "she would have",
"she'll": "she shall / she will",
"she'll've": "she shall have / she will have",
"she's": "she has / she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so as / so is",
"that'd": "that would / that had",
"that'd've": "that would have",
"that's": "that has / that is",
"there'd": "there had / there would",
"there'd've": "there would have",
"there's": "there has / there is",
"they'd": "they had / they would",
"they'd've": "they would have",
"they'll": "they shall / they will",
"they'll've": "they shall have / they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we had / we would",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what shall / what will",
"what'll've": "what shall have / what will have",
"what're": "what are",
"what's": "what has / what is",
"what've": "what have",
"when's": "when has / when is",
"when've": "when have",
"where'd": "where did",
"where's": "where has / where is",
"where've": "where have",
"who'll": "who shall / who will",
"who'll've": "who shall have / who will have",
"who's": "who has / who is",
"who've": "who have",
"why's": "why has / why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you had / you would",
"you'd've": "you would have",
"you'll": "you shall / you will",
"you'll've": "you shall have / you will have",
"you're": "you are",
"you've": "you have"
}
contractions_re = re.compile('(%s)' % '|'.join(contractions.keys()))
def expand_contractions(s, contractions = contractions):
def replace(match):
return contractions[match.group(0)]
return contractions_re.sub(replace, s)
expand_contractions("can't stop won't stop" )<feature_engineering> | from fastai2.tabular.all import * | Titanic - Machine Learning from Disaster |
11,548,643 | total['text'] = total['text'].apply(expand_contractions )<categorify> | df_test= pd.read_csv('/kaggle/input/titanic-extended/test.csv')
df_train= pd.read_csv('.. /input/titanic-extended/train.csv')
df_train.head() | Titanic - Machine Learning from Disaster |
11,548,643 | def clean(tweet):
tweet = re.sub(r"tnwx", "Tennessee Weather", tweet)
tweet = re.sub(r"azwx", "Arizona Weather", tweet)
tweet = re.sub(r"alwx", "Alabama Weather", tweet)
tweet = re.sub(r"wordpressdotcom", "wordpress", tweet)
tweet = re.sub(r"gawx", "Georgia Weather", tweet)
tweet = re.sub(r"scwx", "South Carolina Weather", tweet)
tweet = re.sub(r"cawx", "California Weather", tweet)
tweet = re.sub(r"usNWSgov", "United States National Weather Service", tweet)
tweet = re.sub(r"MH370", "Malaysia Airlines Flight 370", tweet)
tweet = re.sub(r"okwx", "Oklahoma City Weather", tweet)
tweet = re.sub(r"arwx", "Arkansas Weather", tweet)
tweet = re.sub(r"lmao", "laughing my ass off", tweet)
tweet = re.sub(r"amirite", "am I right", tweet)
tweet = re.sub(r"w/e", "whatever", tweet)
tweet = re.sub(r"w/", "with", tweet)
tweet = re.sub(r"USAgov", "USA government", tweet)
tweet = re.sub(r"recentlu", "recently", tweet)
tweet = re.sub(r"Ph0tos", "Photos", tweet)
tweet = re.sub(r"exp0sed", "exposed", tweet)
tweet = re.sub(r"<3", "love", tweet)
tweet = re.sub(r"amageddon", "armageddon", tweet)
tweet = re.sub(r"Trfc", "Traffic", tweet)
tweet = re.sub(r"WindStorm", "Wind Storm", tweet)
tweet = re.sub(r"16yr", "16 year", tweet)
tweet = re.sub(r"TRAUMATISED", "traumatized", tweet)
tweet = re.sub(r"IranDeal", "Iran Deal", tweet)
tweet = re.sub(r"ArianaGrande", "Ariana Grande", tweet)
tweet = re.sub(r"camilacabello97", "camila cabello", tweet)
tweet = re.sub(r"RondaRousey", "Ronda Rousey", tweet)
tweet = re.sub(r"MTVHottest", "MTV Hottest", tweet)
tweet = re.sub(r"TrapMusic", "Trap Music", tweet)
tweet = re.sub(r"ProphetMuhammad", "Prophet Muhammad", tweet)
tweet = re.sub(r"PantherAttack", "Panther Attack", tweet)
tweet = re.sub(r"StrategicPatience", "Strategic Patience", tweet)
tweet = re.sub(r"socialnews", "social news", tweet)
tweet = re.sub(r"IDPs:", "Internally Displaced People :", tweet)
tweet = re.sub(r"ArtistsUnited", "Artists United", tweet)
tweet = re.sub(r"ClaytonBryant", "Clayton Bryant", tweet)
tweet = re.sub(r"jimmyfallon", "jimmy fallon", tweet)
tweet = re.sub(r"justinbieber", "justin bieber", tweet)
tweet = re.sub(r"Time2015", "Time 2015", tweet)
tweet = re.sub(r"djicemoon", "dj icemoon", tweet)
tweet = re.sub(r"LivingSafely", "Living Safely", tweet)
tweet = re.sub(r"FIFA16", "Fifa 2016", tweet)
tweet = re.sub(r"thisiswhywecanthavenicethings", "this is why we cannot have nice things", tweet)
tweet = re.sub(r"bbcnews", "bbc news", tweet)
tweet = re.sub(r"UndergroundRailraod", "Underground Railraod", tweet)
tweet = re.sub(r"c4news", "c4 news", tweet)
tweet = re.sub(r"MUDSLIDE", "mudslide", tweet)
tweet = re.sub(r"NoSurrender", "No Surrender", tweet)
tweet = re.sub(r"NotExplained", "Not Explained", tweet)
tweet = re.sub(r"greatbritishbakeoff", "great british bake off", tweet)
tweet = re.sub(r"LondonFire", "London Fire", tweet)
tweet = re.sub(r"KOTAWeather", "KOTA Weather", tweet)
tweet = re.sub(r"LuchaUnderground", "Lucha Underground", tweet)
tweet = re.sub(r"KOIN6News", "KOIN 6 News", tweet)
tweet = re.sub(r"LiveOnK2", "Live On K2", tweet)
tweet = re.sub(r"9NewsGoldCoast", "9 News Gold Coast", tweet)
tweet = re.sub(r"nikeplus", "nike plus", tweet)
tweet = re.sub(r"david_cameron", "David Cameron", tweet)
tweet = re.sub(r"peterjukes", "Peter Jukes", tweet)
tweet = re.sub(r"MikeParrActor", "Michael Parr", tweet)
tweet = re.sub(r"4PlayThursdays", "Foreplay Thursdays", tweet)
tweet = re.sub(r"TGF2015", "Tontitown Grape Festival", tweet)
tweet = re.sub(r"realmandyrain", "Mandy Rain", tweet)
tweet = re.sub(r"GraysonDolan", "Grayson Dolan", tweet)
tweet = re.sub(r"ApolloBrown", "Apollo Brown", tweet)
tweet = re.sub(r"saddlebrooke", "Saddlebrooke", tweet)
tweet = re.sub(r"TontitownGrape", "Tontitown Grape", tweet)
tweet = re.sub(r"AbbsWinston", "Abbs Winston", tweet)
tweet = re.sub(r"ShaunKing", "Shaun King", tweet)
tweet = re.sub(r"MeekMill", "Meek Mill", tweet)
tweet = re.sub(r"TornadoGiveaway", "Tornado Giveaway", tweet)
tweet = re.sub(r"GRupdates", "GR updates", tweet)
tweet = re.sub(r"SouthDowns", "South Downs", tweet)
tweet = re.sub(r"braininjury", "brain injury", tweet)
tweet = re.sub(r"auspol", "Australian politics", tweet)
tweet = re.sub(r"PlannedParenthood", "Planned Parenthood", tweet)
tweet = re.sub(r"calgaryweather", "Calgary Weather", tweet)
tweet = re.sub(r"weallheartonedirection", "we all heart one direction", tweet)
tweet = re.sub(r"edsheeran", "Ed Sheeran", tweet)
tweet = re.sub(r"TrueHeroes", "True Heroes", tweet)
tweet = re.sub(r"ComplexMag", "Complex Magazine", tweet)
tweet = re.sub(r"TheAdvocateMag", "The Advocate Magazine", tweet)
tweet = re.sub(r"CityofCalgary", "City of Calgary", tweet)
tweet = re.sub(r"EbolaOutbreak", "Ebola Outbreak", tweet)
tweet = re.sub(r"SummerFate", "Summer Fate", tweet)
tweet = re.sub(r"RAmag", "Royal Academy Magazine", tweet)
tweet = re.sub(r"offers2go", "offers to go", tweet)
tweet = re.sub(r"ModiMinistry", "Modi Ministry", tweet)
tweet = re.sub(r"TAXIWAYS", "taxi ways", tweet)
tweet = re.sub(r"Calum5SOS", "Calum Hood", tweet)
tweet = re.sub(r"JamesMelville", "James Melville", tweet)
tweet = re.sub(r"JamaicaObserver", "Jamaica Observer", tweet)
tweet = re.sub(r"TweetLikeItsSeptember11th2001", "Tweet like it is september 11th 2001", tweet)
tweet = re.sub(r"cbplawyers", "cbp lawyers", tweet)
tweet = re.sub(r"fewmoretweets", "few more tweets", tweet)
tweet = re.sub(r"BlackLivesMatter", "Black Lives Matter", tweet)
tweet = re.sub(r"NASAHurricane", "NASA Hurricane", tweet)
tweet = re.sub(r"onlinecommunities", "online communities", tweet)
tweet = re.sub(r"humanconsumption", "human consumption", tweet)
tweet = re.sub(r"Typhoon-Devastated", "Typhoon Devastated", tweet)
tweet = re.sub(r"Meat-Loving", "Meat Loving", tweet)
tweet = re.sub(r"facialabuse", "facial abuse", tweet)
tweet = re.sub(r"LakeCounty", "Lake County", tweet)
tweet = re.sub(r"BeingAuthor", "Being Author", tweet)
tweet = re.sub(r"withheavenly", "with heavenly", tweet)
tweet = re.sub(r"thankU", "thank you", tweet)
tweet = re.sub(r"iTunesMusic", "iTunes Music", tweet)
tweet = re.sub(r"OffensiveContent", "Offensive Content", tweet)
tweet = re.sub(r"WorstSummerJob", "Worst Summer Job", tweet)
tweet = re.sub(r"HarryBeCareful", "Harry Be Careful", tweet)
tweet = re.sub(r"NASASolarSystem", "NASA Solar System", tweet)
tweet = re.sub(r"animalrescue", "animal rescue", tweet)
tweet = re.sub(r"KurtSchlichter", "Kurt Schlichter", tweet)
tweet = re.sub(r"Throwingknifes", "Throwing knives", tweet)
tweet = re.sub(r"GodsLove", "God's Love", tweet)
tweet = re.sub(r"bookboost", "book boost", tweet)
tweet = re.sub(r"ibooklove", "I book love", tweet)
tweet = re.sub(r"NestleIndia", "Nestle India", tweet)
tweet = re.sub(r"realDonaldTrump", "Donald Trump", tweet)
tweet = re.sub(r"DavidVonderhaar", "David Vonderhaar", tweet)
tweet = re.sub(r"CecilTheLion", "Cecil The Lion", tweet)
tweet = re.sub(r"weathernetwork", "weather network", tweet)
tweet = re.sub(r"GOPDebate", "GOP Debate", tweet)
tweet = re.sub(r"RickPerry", "Rick Perry", tweet)
tweet = re.sub(r"frontpage", "front page", tweet)
tweet = re.sub(r"NewsInTweets", "News In Tweets", tweet)
tweet = re.sub(r"ViralSpell", "Viral Spell", tweet)
tweet = re.sub(r"til_now", "until now", tweet)
tweet = re.sub(r"volcanoinRussia", "volcano in Russia", tweet)
tweet = re.sub(r"ZippedNews", "Zipped News", tweet)
tweet = re.sub(r"MicheleBachman", "Michele Bachman", tweet)
tweet = re.sub(r"53inch", "53 inch", tweet)
tweet = re.sub(r"KerrickTrial", "Kerrick Trial", tweet)
tweet = re.sub(r"abstorm", "Alberta Storm", tweet)
tweet = re.sub(r"Beyhive", "Beyonce hive", tweet)
tweet = re.sub(r"RockyFire", "Rocky Fire", tweet)
tweet = re.sub(r"Listen/Buy", "Listen / Buy", tweet)
tweet = re.sub(r"ArtistsUnited", "Artists United", tweet)
tweet = re.sub(r"ENGvAUS", "England vs Australia", tweet)
tweet = re.sub(r"ScottWalker", "Scott Walker", tweet)
return tweet
total['text'] = total['text'].apply(clean )<define_variables> | df_train.isnull().sum().sort_index() /len(df_train ) | Titanic - Machine Learning from Disaster |
11,548,643 | tweets = [tweet for tweet in total['text']]
train = total[:len(train)]
test = total[len(train):]<categorify> | df_train.dtypes
g_train =df_train.columns.to_series().groupby(df_train.dtypes ).groups
g_train | Titanic - Machine Learning from Disaster |
11,548,643 | def generate_ngrams(text, n_gram=1):
token = [token for token in text.lower().split(' ')if token != '' if token not in wordcloud.STOPWORDS]
ngrams = zip(*[token[i:] for i in range(n_gram)])
return [' '.join(ngram)for ngram in ngrams]
disaster_unigrams = defaultdict(int)
for word in total[train['target'] == 1]['text']:
for word in generate_ngrams(word, n_gram = 1):
disaster_unigrams[word] += 1
disaster_unigrams = pd.DataFrame(sorted(disaster_unigrams.items() , key=lambda x: x[1])[::-1])
nondisaster_unigrams = defaultdict(int)
for word in total[train['target'] == 0]['text']:
for word in generate_ngrams(word, n_gram = 1):
nondisaster_unigrams[word] += 1
nondisaster_unigrams = pd.DataFrame(sorted(nondisaster_unigrams.items() , key=lambda x: x[1])[::-1])
disaster_bigrams = defaultdict(int)
for word in total[train['target'] == 1]['text']:
for word in generate_ngrams(word, n_gram = 2):
disaster_bigrams[word] += 1
disaster_bigrams = pd.DataFrame(sorted(disaster_bigrams.items() , key=lambda x: x[1])[::-1])
nondisaster_bigrams = defaultdict(int)
for word in total[train['target'] == 0]['text']:
for word in generate_ngrams(word, n_gram = 2):
nondisaster_bigrams[word] += 1
nondisaster_bigrams = pd.DataFrame(sorted(nondisaster_bigrams.items() , key=lambda x: x[1])[::-1])
disaster_trigrams = defaultdict(int)
for word in total[train['target'] == 1]['text']:
for word in generate_ngrams(word, n_gram = 3):
disaster_trigrams[word] += 1
disaster_trigrams = pd.DataFrame(sorted(disaster_trigrams.items() , key=lambda x: x[1])[::-1])
nondisaster_trigrams = defaultdict(int)
for word in total[train['target'] == 0]['text']:
for word in generate_ngrams(word, n_gram = 3):
nondisaster_trigrams[word] += 1
nondisaster_trigrams = pd.DataFrame(sorted(nondisaster_trigrams.items() , key=lambda x: x[1])[::-1])
disaster_4grams = defaultdict(int)
for word in total[train['target'] == 1]['text']:
for word in generate_ngrams(word, n_gram = 4):
disaster_4grams[word] += 1
disaster_4grams = pd.DataFrame(sorted(disaster_4grams.items() , key=lambda x: x[1])[::-1])
nondisaster_4grams = defaultdict(int)
for word in total[train['target'] == 0]['text']:
for word in generate_ngrams(word, n_gram = 4):
nondisaster_4grams[word] += 1
nondisaster_4grams = pd.DataFrame(sorted(nondisaster_4grams.items() , key=lambda x: x[1])[::-1] )<string_transform> | cat_names= [
'Name', 'Sex', 'Ticket', 'Cabin',
'Embarked', 'Name_wiki', 'Hometown',
'Boarded', 'Destination', 'Lifeboat',
'Body'
]
cont_names = [
'PassengerId', 'Pclass', 'SibSp', 'Parch',
'Age', 'Fare', 'WikiId', 'Age_wiki','Class'
]
| Titanic - Machine Learning from Disaster |
11,548,643 | to_exclude = '*+-/() %
[\\]{|}^_`~\t'
to_tokenize = '!"
tokenizer = Tokenizer(filters = to_exclude)
text = 'Why are you so f%
text = re.sub(r'(['+to_tokenize+'])', r' \1 ', text)
tokenizer.fit_on_texts([text])
print(tokenizer.word_index )<feature_engineering> | splits = RandomSplitter(valid_pct=0.2 )(range_of(df_train))
to = TabularPandas(df_train, procs=[Categorify, FillMissing,Normalize],
cat_names = cat_names,
cont_names = cont_names,
y_names='Survived',
splits=splits ) | Titanic - Machine Learning from Disaster |
11,548,643 |
<string_transform> | g_train =to.train.xs.columns.to_series().groupby(to.train.xs.dtypes ).groups
g_train | Titanic - Machine Learning from Disaster |
11,548,643 | tokenizer = Tokenizer()
tokenizer.fit_on_texts(tweets)
sequences = tokenizer.texts_to_sequences(tweets)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
data = pad_sequences(sequences)
labels = train['target']
print('Shape of data tensor:', data.shape)
print('Shape of label tensor:', labels.shape)
nlp_train = data[:len(train)]
labels = labels
nlp_test = data[len(train):]
MAX_SEQUENCE_LENGTH = data.shape[1]<feature_engineering> | to.train | Titanic - Machine Learning from Disaster |
11,548,643 | embeddings_index = {}
with open('.. /input/glove-global-vectors-for-word-representation/glove.6B.200d.txt','r')as f:
for line in tqdm(f):
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
print('Found %s word vectors in the GloVe library' % len(embeddings_index))<define_variables> | to.train.xs | Titanic - Machine Learning from Disaster |
11,548,643 | EMBEDDING_DIM = 200<categorify> | X_train, y_train = to.train.xs, to.train.ys.values.ravel()
X_valid, y_valid = to.valid.xs, to.valid.ys.values.ravel() | Titanic - Machine Learning from Disaster |
11,548,643 | embedding_matrix = np.zeros(( len(word_index)+ 1, EMBEDDING_DIM))
for word, i in tqdm(word_index.items()):
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
print("Our embedded matrix is of dimension", embedding_matrix.shape )<choose_model_class> | rnf_classifier= RandomForestClassifier(n_estimators=100, n_jobs=-1)
rnf_classifier.fit(X_train,y_train ) | Titanic - Machine Learning from Disaster |
11,548,643 | embedding = Embedding(len(word_index)+ 1, EMBEDDING_DIM, weights = [embedding_matrix],
input_length = MAX_SEQUENCE_LENGTH, trainable = False)
<normalization> | y_pred=rnf_classifier.predict(X_valid)
accuracy_score(y_pred, y_valid ) | Titanic - Machine Learning from Disaster |
11,548,643 | def scale(df, scaler):
return scaler.fit_transform(df.iloc[:, 2:])
meta_train = scale(train, StandardScaler())
meta_test = scale(test, StandardScaler() )<choose_model_class> | df_test.dtypes
g_train =df_test.columns.to_series().groupby(df_test.dtypes ).groups
g_train | Titanic - Machine Learning from Disaster |
11,548,643 | def create_lstm(spatial_dropout, dropout, recurrent_dropout, learning_rate, bidirectional = False):
activation = LeakyReLU(alpha = 0.01)
nlp_input = Input(shape =(MAX_SEQUENCE_LENGTH,), name = 'nlp_input')
meta_input_train = Input(shape =(7,), name = 'meta_train')
emb = embedding(nlp_input)
emb = SpatialDropout1D(dropout )(emb)
if bidirectional:
nlp_out =(Bidirectional(LSTM(100, dropout = dropout, recurrent_dropout = recurrent_dropout,
kernel_initializer = 'orthogonal')) )(emb)
else:
nlp_out =(LSTM(100, dropout = dropout, recurrent_dropout = recurrent_dropout,
kernel_initializer = 'orthogonal'))(emb)
x = Concatenate()([nlp_out, meta_input_train])
x = Dropout(dropout )(x)
preds = Dense(1, activation='sigmoid', kernel_regularizer = regularizers.l2(1e-4))(x)
model = Model(inputs=[nlp_input , meta_input_train], outputs = preds)
optimizer = Adam(learning_rate = learning_rate)
model.compile(loss = 'binary_crossentropy', optimizer = optimizer, metrics = ['accuracy'])
return model<choose_model_class> | cat_names= [
'Name', 'Sex', 'Ticket', 'Cabin',
'Embarked', 'Name_wiki', 'Hometown',
'Boarded', 'Destination', 'Lifeboat',
'Body'
]
cont_names = [
'PassengerId', 'Pclass', 'SibSp', 'Parch',
'Age', 'Fare', 'WikiId', 'Age_wiki','Class'
] | Titanic - Machine Learning from Disaster |
11,548,643 | lstm = create_lstm(spatial_dropout =.2, dropout =.2, recurrent_dropout =.2,
learning_rate = 3e-4, bidirectional = True)
lstm.summary()<train_model> | test = TabularPandas(df_test, procs=[Categorify, FillMissing,Normalize],
cat_names = cat_names,
cont_names = cont_names,
) | Titanic - Machine Learning from Disaster |
11,548,643 | history1 = lstm.fit([nlp_train, meta_train], labels, validation_split =.2,
epochs = 5, batch_size = 21, verbose = 1 )<choose_model_class> | X_test= test.train.xs | Titanic - Machine Learning from Disaster |
11,548,643 | callback = EarlyStopping(monitor = 'val_loss', patience = 4)
<choose_model_class> | X_test.dtypes
g_train =X_test.columns.to_series().groupby(X_test.dtypes ).groups
g_train | Titanic - Machine Learning from Disaster |
11,548,643 | def create_lstm_2(spatial_dropout, dropout, recurrent_dropout, learning_rate, bidirectional = False):
activation = LeakyReLU(alpha = 0.01)
nlp_input = Input(shape =(MAX_SEQUENCE_LENGTH,), name = 'nlp_input')
meta_input_train = Input(shape =(7,), name = 'meta_train')
emb = embedding(nlp_input)
emb = SpatialDropout1D(dropout )(emb)
if bidirectional:
nlp_out =(Bidirectional(LSTM(100, dropout = dropout, recurrent_dropout = recurrent_dropout,
kernel_initializer = 'orthogonal')) )(emb)
else:
nlp_out =(LSTM(100, dropout = dropout, recurrent_dropout = recurrent_dropout,
kernel_initializer = 'orthogonal'))(emb)
x = Concatenate()([nlp_out, meta_input_train])
x = Dropout(dropout )(x)
x =(Dense(100, activation = activation, kernel_regularizer = regularizers.l2(1e-4),
kernel_initializer = 'he_normal'))(x)
x = Dropout(dropout )(x)
preds = Dense(1, activation='sigmoid', kernel_regularizer = regularizers.l2(1e-4))(x)
model = Model(inputs=[nlp_input , meta_input_train], outputs = preds)
optimizer = Adam(learning_rate = learning_rate)
model.compile(loss = 'binary_crossentropy', optimizer = optimizer, metrics = ['accuracy'])
return model<choose_model_class> | X_test= X_test.drop('Fare_na', axis=1 ) | Titanic - Machine Learning from Disaster |
11,548,643 | lstm_2 = create_lstm_2(spatial_dropout =.4, dropout =.4, recurrent_dropout =.4,
learning_rate = 3e-4, bidirectional = True)
lstm_2.summary()<train_model> | y_pred=rnf_classifier.predict(X_test)
| Titanic - Machine Learning from Disaster |
11,548,643 | history2 = lstm_2.fit([nlp_train, meta_train], labels, validation_split =.2,
epochs = 30, batch_size = 21, verbose = 1 )<predict_on_test> | y_pred= y_pred.astype(int ) | Titanic - Machine Learning from Disaster |
11,548,643 | <choose_model_class><EOS> | output= pd.DataFrame({'PassengerId':df_test.PassengerId, 'Survived': y_pred})
output.to_csv('my_submission_titanic.csv', index=False)
output.head() | Titanic - Machine Learning from Disaster |
4,005,064 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<train_model> | print(os.listdir(".. /input"))
| Titanic - Machine Learning from Disaster |
4,005,064 | history3 = dual_lstm.fit([nlp_train, meta_train], labels, validation_split =.2,
epochs = 25, batch_size = 21, verbose = 1 )<predict_on_test> | train_df = pd.read_csv(".. /input/train.csv")
test_df = pd.read_csv(".. /input/test.csv")
print("Train shape : ",train_df.shape)
print("Test shape : ",test_df.shape ) | Titanic - Machine Learning from Disaster |
4,005,064 | submission_lstm2 = pd.DataFrame()
submission_lstm2['id'] = test_id
submission_lstm2['prob'] = dual_lstm.predict([nlp_test, meta_test])
submission_lstm2['target'] = submission_lstm2['prob'].apply(lambda x: 0 if x <.5 else 1)
submission_lstm2.head(10 )<define_variables> | tabla_completa = train_df.append(test_df, ignore_index=True ) | Titanic - Machine Learning from Disaster |
4,005,064 | BATCH_SIZE = 32
EPOCHS = 2
USE_META = True
ADD_DENSE = False
DENSE_DIM = 64
ADD_DROPOUT = False
DROPOUT =.2<install_modules> | tabla_completa["Cabin"] = tabla_completa["Cabin"].fillna("N")
letras_cabinas = tabla_completa["Cabin"].str[0].unique().tolist() | Titanic - Machine Learning from Disaster |
4,005,064 | !pip install --quiet transformers
<categorify> | tabla_completa["Letra_Cabina"] = tabla_completa["Cabin"].str[0] | Titanic - Machine Learning from Disaster |
4,005,064 | TOKENIZER = AutoTokenizer.from_pretrained("bert-large-uncased")
enc = TOKENIZER.encode("Encode me!")
dec = TOKENIZER.decode(enc)
print("Encode: " + str(enc))
print("Decode: " + str(dec))<categorify> | dic_titulos_simples = {
"Mr" : "Mr",
"Mrs" : "Mrs",
"Miss" : "Miss",
"Master" : "Master",
"Don" : "Nobleza",
"Rev" : "Oficial",
"Dr" : "Oficial",
"Mme" : "Mrs",
"Ms" : "Mrs",
"Major" : "Oficial",
"Lady" : "Nobleza",
"Sir" : "Nobleza",
"Mlle" : "Miss",
"Col" : "Oficial",
"Capt" : "Oficial",
"Countess" : "Nobleza",
"Jonkheer" : "Nobleza",
"Dona" : "Nobleza"
}
tabla_completa["Titulo"] = tabla_completa["Name"].str.partition('.')[0].str.rpartition() [2].map(dic_titulos_simples ) | Titanic - Machine Learning from Disaster |
4,005,064 | def bert_encode(data,maximum_len):
input_ids = []
attention_masks = []
for i in range(len(data.text)) :
encoded = TOKENIZER.encode_plus(data.text[i],
add_special_tokens=True,
max_length=maximum_len,
pad_to_max_length=True,
return_attention_mask=True)
input_ids.append(encoded['input_ids'])
attention_masks.append(encoded['attention_mask'])
return np.array(input_ids),np.array(attention_masks )<choose_model_class> | grupo = tabla_completa.groupby(['Sex','Pclass','Titulo'])
tabla_completa['Age'] = grupo['Age'].apply(lambda x: x.fillna(x.median())) | Titanic - Machine Learning from Disaster |
4,005,064 | def build_model(model_layer, learning_rate, use_meta = USE_META, add_dense = ADD_DENSE,
dense_dim = DENSE_DIM, add_dropout = ADD_DROPOUT, dropout = DROPOUT):
input_ids = tf.keras.Input(shape=(60,),dtype='int32')
attention_masks = tf.keras.Input(shape=(60,),dtype='int32')
meta_input = tf.keras.Input(shape =(meta_train.shape[1],))
transformer_layer = model_layer([input_ids,attention_masks])
output = transformer_layer[1]
if use_meta:
output = tf.keras.layers.Concatenate()([output, meta_input])
if add_dense:
print("Training with additional dense layer...")
output = tf.keras.layers.Dense(dense_dim,activation='relu' )(output)
if add_dropout:
print("Training with dropout...")
output = tf.keras.layers.Dropout(dropout )(output)
output = tf.keras.layers.Dense(1,activation='sigmoid' )(output)
if use_meta:
print("Training with meta-data...")
model = tf.keras.models.Model(inputs = [input_ids,attention_masks, meta_input],outputs = output)
else:
print("Training without meta-data...")
model = tf.keras.models.Model(inputs = [input_ids,attention_masks],outputs = output)
model.compile(tf.keras.optimizers.Adam(lr=learning_rate), loss='binary_crossentropy', metrics=['accuracy'])
return model<load_from_csv> | tabla_completa['Fare'] = tabla_completa['Fare'].fillna(tabla_completa['Fare'].median() ) | Titanic - Machine Learning from Disaster |
4,005,064 | train = pd.read_csv('.. /input/nlp-getting-started/train.csv')
test = pd.read_csv('.. /input/nlp-getting-started/test.csv' )<categorify> | tabla_completa['Num_Familiares'] = tabla_completa['SibSp'] + tabla_completa['Parch'] | Titanic - Machine Learning from Disaster |
4,005,064 | bert_large = TFAutoModel.from_pretrained('bert-large-uncased')
TOKENIZER = AutoTokenizer.from_pretrained("bert-large-uncased")
train_input_ids,train_attention_masks = bert_encode(train,60)
test_input_ids,test_attention_masks = bert_encode(test,60)
print('Train length:', len(train_input_ids))
print('Test length:', len(test_input_ids))
BERT_large = build_model(bert_large, learning_rate = 1e-5)
BERT_large.summary()<train_model> | tabla_completa['Sex'] = tabla_completa['Sex'].map({"male": 0, "female":1})
dummies_pclass = pd.get_dummies(tabla_completa['Pclass'], prefix="Pclass")
dummies_titulo = pd.get_dummies(tabla_completa['Titulo'], prefix="Titulo")
dummies_letra_cab = pd.get_dummies(tabla_completa['Letra_Cabina'], prefix="Letra_Cabina")
dummies_grupo_edad = pd.get_dummies(tabla_completa['Grupo_Edad'], prefix="Grupo_Edad")
dummies_tabla = pd.concat([tabla_completa, dummies_pclass, dummies_titulo, dummies_letra_cab,dummies_grupo_edad], axis=1)
dummies_tabla.drop(['Pclass', 'Titulo', 'Cabin', 'Letra_Cabina', 'Grupo_Edad', 'Embarked', 'Name', 'Ticket'], axis=1, inplace=True ) | Titanic - Machine Learning from Disaster |
4,005,064 | history_bert = BERT_large.fit([train_input_ids,train_attention_masks, meta_train], train.target,
validation_split =.2, epochs = EPOCHS, callbacks = [checkpoint], batch_size = BATCH_SIZE )<predict_on_test> | train_df = dummies_tabla[ :len(train_df)]
test_df = dummies_tabla[(len(dummies_tabla)- len(test_df)) : ]
train_df['Survived'] = train_df['Survived'].astype(int)
print("Train:
",train_df)
print("Test:
",test_df ) | Titanic - Machine Learning from Disaster |
4,005,064 | BERT_large.load_weights('large_model.h5')
preds_bert = BERT_large.predict([test_input_ids,test_attention_masks,meta_test] )<prepare_output> | test_df = test_df.reset_index(drop = True)
train_df = train_df.reset_index(drop = True)
train_dfX = train_df.drop(['PassengerId','Survived'], axis=1)
train_dfY = train_df['Survived']
submission = pd.DataFrame(data=test_df['PassengerId'].copy())
print(submission)
test_df = test_df.drop(['PassengerId', 'Survived'], axis=1 ) | Titanic - Machine Learning from Disaster |
4,005,064 | submission_bert = pd.DataFrame()
submission_bert['id'] = test_id
submission_bert['prob'] = preds_bert
submission_bert['target'] = np.round(submission_bert['prob'] ).astype(int)
submission_bert.head(10 )<save_to_csv> | sc = StandardScaler()
train_dfX = sc.fit_transform(train_dfX)
test_df = sc.transform(test_df ) | Titanic - Machine Learning from Disaster |
4,005,064 | submission_bert = submission_bert[['id', 'target']]
submission_bert.to_csv('submission_bert.csv', index = False)
print('Blended submission has been saved to disk' )<set_options> | train_dfX,val_dfX,train_dfY, val_dfY = train_test_split(train_dfX,train_dfY , test_size=0.1, stratify=train_dfY)
print("Entrnamiento: ",train_dfX.shape)
print("Validacion : ",val_dfX.shape ) | Titanic - Machine Learning from Disaster |
4,005,064 | plt.style.use('ggplot')
warnings.filterwarnings('ignore')
<define_variables> | def func_model(arquitectura):
np.random.seed(42)
random_seed = 42
first =True
inp = Input(shape=(train_dfX.shape[1],))
for capa in arquitectura:
if first:
x=Dense(capa, activation="relu", kernel_initializer=initializers.RandomNormal(seed=random_seed), bias_initializer='zeros' )(inp)
first = False
else:
x=Dense(capa, activation="relu", kernel_initializer=initializers.RandomNormal(seed=random_seed), bias_initializer='zeros' )(x)
x=Dense(1, activation="sigmoid", kernel_initializer=initializers.RandomNormal(seed=random_seed), bias_initializer='zeros' )(x)
model = Model(inputs=inp, outputs=x)
model.compile(loss='binary_crossentropy', optimizer=optimizers.Adam(lr=0.0002), metrics=['binary_accuracy'])
return model | Titanic - Machine Learning from Disaster |
4,005,064 | def seed_everything(seed):
os.environ['PYTHONHASHSEED']=str(seed)
tf.random.set_seed(seed)
np.random.seed(seed)
random.seed(seed)
seed_everything(34 )<load_from_csv> | arq1 = [1024, 1024, 512]
model1 = None
model1 = func_model(arq1)
train_history_tam1 = model1.fit(train_dfX, train_dfY, batch_size=32, epochs=epochs, validation_data=(val_dfX, val_dfY))
graf_model(train_history_tam1)
precision(model1 ) | Titanic - Machine Learning from Disaster |
4,005,064 | train = pd.read_csv('.. /input/nlp-getting-started/train.csv')
test = pd.read_csv('.. /input/nlp-getting-started/test.csv')
train.head()<categorify> | arq2 = [1024, 512, 512]
model2 = None
model2 = func_model(arq2)
train_history_tam2 = model2.fit(train_dfX, train_dfY, batch_size=32, epochs=epochs, validation_data=(val_dfX, val_dfY))
graf_model(train_history_tam2)
precision(model2 ) | Titanic - Machine Learning from Disaster |
4,005,064 | test_id = test['id']
columns = {'id', 'location'}
train = train.drop(columns = columns)
test = test.drop(columns = columns)
train['keyword'] = train['keyword'].fillna('unknown')
test['keyword'] = test['keyword'].fillna('unknown')
train['text'] = train['text'] + ' ' + train['keyword']
test['text'] = test['text'] + ' ' + test['keyword']
columns = {'keyword'}
train = train.drop(columns = columns)
test = test.drop(columns = columns)
total = train.append(test )<feature_engineering> | arqFinal = [1024, 1024, 1024]
modelF = None
modelF = func_model(arqFinal)
print(modelF.summary())
train_history_tamF = modelF.fit(train_dfX, train_dfY, batch_size=32, epochs=epochs, validation_data=(val_dfX, val_dfY))
graf_model(train_history_tamF)
precision(modelF, True ) | Titanic - Machine Learning from Disaster |
4,005,064 | total['unique word count'] = total['text'].apply(lambda x: len(set(x.split())))
total['stopword count'] = total['text'].apply(lambda x: len([i for i in x.lower().split() if i in wordcloud.STOPWORDS]))
total['stopword ratio'] = total['stopword count'] / total['word count']
total['punctuation count'] = total['text'].apply(lambda x: len([i for i in str(x)if i in string.punctuation]))
train = total[:len(train)]
disaster = train['target'] == 1
fig, axes = plt.subplots(4, figsize=(20, 30))
graph1 = sns.kdeplot(train.loc[~disaster]['unique word count'], shade = True, label = 'Not Disaster', ax=axes[0])
graph1 = sns.kdeplot(train.loc[disaster]['unique word count'], shade = True, label = 'Disaster', ax=axes[0])
graph1.set_title('Distribution of Unique Word Count')
graph2 = sns.kdeplot(train.loc[~disaster]['stopword count'], shade = True, label = 'Not Disaster', ax=axes[1])
graph2 = sns.kdeplot(train.loc[disaster]['stopword count'], shade = True, label = 'Disaster', ax=axes[1])
graph2.set_title('Distribution of Stopword Word Count')
graph3 = sns.kdeplot(train.loc[~disaster]['punctuation count'], shade = True, label = 'Not Disaster', ax=axes[2], bw = 1)
graph3 = sns.kdeplot(train.loc[disaster]['punctuation count'], shade = True, label = 'Disaster', ax=axes[2], bw = 1)
graph3.set_title('Distribution of Punctuation Count')
graph4 = sns.kdeplot(train.loc[~disaster]['stopword ratio'], shade = True, label = 'Not Disaster', ax=axes[3], bw =.05)
graph4 = sns.kdeplot(train.loc[disaster]['stopword ratio'], shade = True, label = 'Disaster', ax=axes[3], bw =.05)
graph4.set_title('Distribution of Stopword Ratio')
fig.tight_layout()
plt.show()<string_transform> | def func_model_reg() :
np.random.seed(42)
random_seed = 42
inp = Input(shape=(train_dfX.shape[1],))
x=Dropout(0.1 )(inp)
x=Dense(1024, activation="relu", kernel_initializer=initializers.RandomNormal(seed=random_seed), bias_initializer='zeros', kernel_regularizer=regularizers.l2(0.01))(x)
x=Dropout(0.7 )(x)
x=Dense(1024, activation="relu", kernel_initializer=initializers.RandomNormal(seed=random_seed), bias_initializer='zeros', kernel_regularizer=regularizers.l2(0.01))(x)
x=Dropout(0.7 )(x)
x=Dense(512, activation="relu", kernel_initializer=initializers.RandomNormal(seed=random_seed), bias_initializer='zeros', kernel_regularizer=regularizers.l2(0.01))(x)
x=Dropout(0.9 )(x)
x=Dense(1, activation="sigmoid", kernel_initializer=initializers.RandomNormal(seed=random_seed), bias_initializer='zeros' )(x)
model = Model(inputs=inp, outputs=x)
model.compile(loss='binary_crossentropy', optimizer=optimizers.Adam(lr=0.0002), metrics=['binary_accuracy'])
return model | Titanic - Machine Learning from Disaster |
4,005,064 | def remove_punctuation(x):
return x.translate(str.maketrans('', '', string.punctuation))
def remove_stopwords(x):
return ' '.join([i for i in x.split() if i not in wordcloud.STOPWORDS])
def remove_less_than(x):
return ' '.join([i for i in x.split() if len(i)> 3])
def remove_non_alphabet(x):
return ' '.join([i for i in x.split() if i.isalpha() ])
def strip_all_entities(x):
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x ).split() )<drop_column> | modelReg = None
modelReg = func_model_reg()
train_history_tamReg = modelReg.fit(train_dfX, train_dfY, batch_size=32, epochs=epochs, validation_data=(val_dfX, val_dfY))
graf_model(train_history_tamReg)
precision(modelReg ) | Titanic - Machine Learning from Disaster |
4,005,064 | <string_transform><EOS> | y_test = modelReg.predict(test_df)
submission['Survived'] = y_test.round().astype(int)
submission.to_csv('submission.csv', index=False ) | Titanic - Machine Learning from Disaster |
6,488,543 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<feature_engineering> | %matplotlib inline
py.init_notebook_mode(connected=True)
warnings.filterwarnings('ignore')
GradientBoostingClassifier, ExtraTreesClassifier)
| Titanic - Machine Learning from Disaster |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.