kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
10,421,422 | vocab = build_vocab(df['question_text'])
print("Glove : ")
oov_glove = check_coverage(vocab, embed_glove )<categorify> | titanic.SurnameFreq=titanic.TicketFreq | Titanic - Machine Learning from Disaster |
10,421,422 | def clean_numbers(x):
x = re.sub('[0-9]{5,}', ' number ', x)
x = re.sub('[0-9]{4}', ' number ', x)
x = re.sub('[0-9]{3}', ' number ', x)
x = re.sub('[0-9]{2}', ' number ', x)
return x<feature_engineering> | titanic['Deck']=titanic['Cabin'].notnull().astype(str ).str[0]
titanic['Deck'].value_counts() | Titanic - Machine Learning from Disaster |
10,421,422 | df['question_text'] = df['question_text'].apply(lambda x: clean_numbers(x))<compute_test_metric> | titanic=titanic.drop(['Cabin'],axis=1 ) | Titanic - Machine Learning from Disaster |
10,421,422 | vocab = build_vocab(df['question_text'])
print("Glove : ")
oov_glove = check_coverage(vocab, embed_glove )<feature_engineering> | Titanic - Machine Learning from Disaster | |
10,421,422 | train_df['treated_question'] = train_df['question_text'].apply(lambda x: x.lower())
train_df['treated_question'] = train_df['treated_question'].apply(lambda x: clean_contractions(x, contraction_mapping))
train_df['treated_question'] = train_df['treated_question'].apply(lambda x: clean_special_chars(x, punct, punct_map... | def FamilyGroup(family):
a=''
if family<=1:
a='Single'
elif family<=4:
a='Small'
else:
a='Large'
return a
titanic['FamilyGroup']=titanic['Family'].map(FamilyGroup)
titanic=titanic.drop(['Family'],axis=1 ) | Titanic - Machine Learning from Disaster |
10,421,422 | test_df['treated_question'] = test_df['question_text'].apply(lambda x: x.lower())
test_df['treated_question'] = test_df['treated_question'].apply(lambda x: clean_contractions(x, contraction_mapping))
test_df['treated_question'] = test_df['treated_question'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))... | def AgeGroup(age):
a=''
if age<=15:
a='Child'
elif age<=30:
a='Young'
elif age<=50:
a='Adult'
else:
a='Old'
return a
titanic['AgeGroup']=titanic['Age'].map(AgeGroup)
titanic=titanic.drop(['Age'],axis=1 ) | Titanic - Machine Learning from Disaster |
10,421,422 |
<split> | titanic=titanic.drop(['PassengerId','TicketFreq','Ticket','Fare','Title','Surname'], axis=1 ) | Titanic - Machine Learning from Disaster |
10,421,422 | train, val = train_test_split(train_df, test_size=0.2, random_state=2)
<prepare_x_and_y> | titanic_data=pd.get_dummies(titanic,columns=['Embarked','AgeGroup','Sex','Deck','FamilyGroup'] ) | Titanic - Machine Learning from Disaster |
10,421,422 | xtrain = train['question_text'].fillna('_na_' ).values
xval = val['question_text'].fillna('_na_' ).values
xtest = test_df['question_text'].fillna('_na_' ).values<string_transform> | titanic_data.loc[891:1308] | Titanic - Machine Learning from Disaster |
10,421,422 | EMBED_SIZE = 300
MAX_FEATURES = 100000
MAXLEN = 60
tokenizer = Tokenizer(num_words=MAX_FEATURES)
tokenizer.fit_on_texts(list(xtrain))
xtrain = tokenizer.texts_to_sequences(xtrain)
xval = tokenizer.texts_to_sequences(xval)
xtest = tokenizer.texts_to_sequences(xtest )<string_transform> | train_df = titanic_data.loc[0:890]
train_df['Survived'] = train_results
test_df = titanic_data.loc[891:1308] | Titanic - Machine Learning from Disaster |
10,421,422 | xtrain = pad_sequences(xtrain, maxlen=MAXLEN)
xval = pad_sequences(xval, maxlen=MAXLEN)
xtest = pad_sequences(xtest, maxlen=MAXLEN )<prepare_x_and_y> | X=train_df.drop(['Survived'],axis=1)
X.head()
y=train_df.Survived
y.head()
| Titanic - Machine Learning from Disaster |
10,421,422 | ytrain = train['target'].values
yval = val['target'].values<statistical_test> | Titanic - Machine Learning from Disaster | |
10,421,422 | def load_glove_matrix(word_index, embeddings_index):
all_embs = np.stack(embeddings_index.values())
emb_mean, emb_std = all_embs.mean() , all_embs.std()
EMBED_SIZE = all_embs.shape[1]
nb_words = min(MAX_FEATURES, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, EMBED_SIZE))
for word, i... | xgbr=XGBClassifier(n_estimators=2800,
min_child_weight=0.1,
learning_rate=0.002,
max_depth=2,
subsample=0.47,
colsample_bytree=0.35,
gamma=0.4,
reg_lambda=0.4,
random_state=42,
n_jobs=-1,)
xgbr.fit(X,y)
predicts=xgbr.predict(test_df)
| Titanic - Machine Learning from Disaster |
10,421,422 | np.random.seed(2)
trn_idx = np.random.permutation(len(xtrain))
val_idx = np.random.permutation(len(xval))
xtrain = xtrain[trn_idx]
ytrain = ytrain[trn_idx]
xval = xval[val_idx]
yval = yval[val_idx]
embedding_matrix_glove = load_glove_matrix(tokenizer.word_index, embed_glove )<set_options> | submission = pd.DataFrame({
"PassengerId": test_data["PassengerId"],
"Survived": predicts
})
submission.Survived = submission.Survived.round().astype("int")
submission.to_csv('titanic.csv', index=False)
print("Submitted Successfully")
| Titanic - Machine Learning from Disaster |
1,646,791 | class Attention(Layer):
def __init__(self, step_dim,
W_regularizer=None, b_regularizer=None,
W_constraint=None, b_constraint=None,
bias=True, **kwargs):
self.supports_masking = True
self.init = initializers.get('glorot_uniform')
self.W_regularizer = regularizers.get(W_regularizer)
self.b_regularizer = regularizers.ge... | %matplotlib inline
warnings.filterwarnings('ignore')
| Titanic - Machine Learning from Disaster |
1,646,791 | def f1(y_true, y_pred):
def recall(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true*y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall = true_positives/(possible_positives + K.epsilon())
return recall
def precision(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_tr... | train = pd.read_csv('.. /input/train.csv')
test = pd.read_csv('.. /input/test.csv')
all_data = [train,test] | Titanic - Machine Learning from Disaster |
1,646,791 | def model_lstm_att(embedding_matrix):
inp = Input(shape=(MAXLEN,))
x = Embedding(MAX_FEATURES, EMBED_SIZE, weights=[embedding_matrix], trainable=False )(inp)
x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)
x = Bidirectional(CuDNNLSTM(32, return_sequences=True))(x)
att = Attention(MAXLEN )(x)
y = Dense(32... | cor_map(train.drop(['PassengerId'],axis=1)) | Titanic - Machine Learning from Disaster |
1,646,791 | paragram = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
embedding_matrix_para = load_glove_matrix(tokenizer.word_index, load_embed(paragram))<compute_test_metric> | train[['Pclass','Survived']].groupby(['Pclass'], as_index=False ).mean().sort_values(by='Survived',ascending=False ) | Titanic - Machine Learning from Disaster |
1,646,791 | embedding_matrix = np.mean([embedding_matrix_glove, embedding_matrix_para], axis=0 )<find_best_params> | train[['Sex','Survived']].groupby(['Sex'],as_index=False ).mean().sort_values(by='Survived',ascending=False ) | Titanic - Machine Learning from Disaster |
1,646,791 | def train_pred(model, epochs=2):
for e in range(epochs):
model.fit(xtrain, ytrain, batch_size=512, epochs=3, validation_data=(xval, yval))
pred_val_y = model.predict([xval], batch_size=1024, verbose=1)
best_thresh = 0.5
best_score = 0.0
for thresh in np.arange(0.1, 0.501, 0.01):
thresh = np.round(thresh, 2)
score = m... | train[['Embarked','Survived']].groupby(['Embarked'],as_index=False ).mean().sort_values(by='Survived',ascending=False ) | Titanic - Machine Learning from Disaster |
1,646,791 | outputs = []
pred_val_y, pred_test_y, best_score = train_pred(model_lstm, epochs=2)
outputs.append([pred_val_y, pred_test_y, best_score, 'model_lstm_att only Glove'] )<compute_test_metric> | guess_ages = np.zeros(( 3,9))
for dataset in all_data:
dataset['ageFill']=dataset.Age.isnull().map({False:0,True:1})
med_all = dataset['Age'].median()
for i in range(0,3):
for j in range(0,9):
guess_df=dataset[(dataset['Pclass']==i+1)&\
(dataset['SibSp']==j)]['Age'].dropna()
age_guess=guess_df.median()
try:
guess_age... | Titanic - Machine Learning from Disaster |
1,646,791 | outputs.sort(key=lambda x: x[2])
weights = [i for i in range(1, len(outputs)+ 1)]
weights = [float(i)/ sum(weights)for i in weights]
pred_val_y = np.mean([outputs[i][0] for i in range(len(outputs)) ], axis = 0)
thresholds = []
for thresh in np.arange(0.1, 0.501, 0.01):
thresh = np.round(thresh, 2)
res = metrics.f1_s... | freq_port = train.Embarked.dropna().mode() [0]
train.Embarked = train.Embarked.fillna(freq_port)
print(freq_port)
| Titanic - Machine Learning from Disaster |
1,646,791 | print("Mejor limite:", best_thresh, "y puntuacion F1 ", thresholds[0][1] )<data_type_conversions> | test['Fare']=test.Fare.fillna(test.Fare.mean())
test.info() | Titanic - Machine Learning from Disaster |
1,646,791 | pred_test_y = np.mean([outputs[i][1] for i in range(len(outputs)) ], axis = 0)
pred_test_y =(pred_test_y > best_thresh ).astype(int )<save_to_csv> | for dataset in all_data:
dataset['Title'] = dataset.Name.str.extract('([A-Za-z]+)\.',expand=False)
pd.crosstab(train['Title'],train['Sex'] ) | Titanic - Machine Learning from Disaster |
1,646,791 | sub = pd.read_csv('.. /input/sample_submission.csv')
out_df = pd.DataFrame({"qid":sub["qid"].values})
out_df['prediction'] = pred_test_y
out_df.to_csv("submission.csv", index=False )<import_modules> | def cleanTicket(ticket):
ticket = ticket.replace('.' , '')
ticket = ticket.replace('/' , '')
ticket = ticket.split()
ticket = map(lambda t : t.strip() , ticket)
ticket = list(filter(lambda t : not t.isdigit() , ticket))
if len(ticket)> 0:
return ticket[0]
else:
return 'XXX'
for dataset in all_data:
dataset[ 'ticketP... | Titanic - Machine Learning from Disaster |
1,646,791 | ps = PorterStemmer()
lc = LancasterStemmer()
sb = SnowballStemmer("english")
<set_options> | for dataset in all_data:
title_mapping = {'Mr':1,'Rare':2,'Master':3,'Miss':4,'Mrs':5}
dataset['Title'] = dataset['Title'].map(title_mapping)
dataset['Title'] = dataset['Title'].fillna(0)
train.head() | Titanic - Machine Learning from Disaster |
1,646,791 | gc.collect()
K.clear_session()<normalization> | for dataset in all_data:
dataset['Sex']=dataset.Sex.map({'male':0,'female':1})
train.head() | Titanic - Machine Learning from Disaster |
1,646,791 | class AttentionWeightedAverage(Layer):
def __init__(self, return_attention=False, **kwargs):
self.init = initializers.get('uniform')
self.supports_masking = True
self.return_attention = return_attention
super(AttentionWeightedAverage, self ).__init__(** kwargs)
def build(self, input_shape):
self.input_spec = [InputSp... | for dataset in all_data:
dataset['Embarked']=dataset.Embarked.map({'S':0,'Q':1,"C":2})
train.head() | Titanic - Machine Learning from Disaster |
1,646,791 | spell_model = gensim.models.KeyedVectors.load_word2vec_format('.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec')
words = spell_model.index2word
w_rank = {}
for i,word in enumerate(words):
w_rank[word] = i
WORDS = w_rank<set_options> | for dataset in all_data:
dataset['AgeBand']=pd.cut(dataset['Age'],5,labels=[0,1,2,3,4])
dataset['AgeBand']=dataset.AgeBand.astype(int)
train[['AgeBand','Survived']].groupby(['AgeBand'],as_index=False ).mean().sort_values(by='Survived',ascending=False ) | Titanic - Machine Learning from Disaster |
1,646,791 | del spell_model, w_rank
gc.collect()<categorify> | for dataset in all_data:
dataset['cabinRec']=dataset.Cabin.isnull().map({False:0,True:1})
train.head() | Titanic - Machine Learning from Disaster |
1,646,791 | def words(text): return re.findall(r'\w+', text.lower())
def P(word):
"Probability of `word`."
return - WORDS.get(word, 0)
def correction(word):
"Most probable spelling correction for word."
return max(candidates(word), key=P)
def candidates(word):
"Generate possible spelling corrections for word."
return(known([wor... | for dataset in all_data:
dataset['Fare'].fillna(dataset['Fare'].median() , inplace = True)
dataset['FareBin'] = pd.qcut(dataset['Fare'], 5,labels=[1,2,3,4,5])
dataset['FareBin'] = dataset.FareBin.astype(int)
train.head() | Titanic - Machine Learning from Disaster |
1,646,791 | def load_glove(word_dict, lemma_dict):
EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE))
embed_size = 300
nb_words = len(word_dict)+1
embeddi... | Titanic - Machine Learning from Disaster | |
1,646,791 | def load_fasttext(word_dict, lemma_dict):
EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100)
embed_size = 300
nb_words = len... | train_df=train.drop(['AgeBand','FareBin','Ticket','Cabin','Name','PassengerId','ticketPos'],axis=1)
test_df=test.drop(['AgeBand','FareBin','Ticket','Cabin','Name','PassengerId','ticketPos'],axis=1)
combine_df = [train_df,test_df]
train_df.head() | Titanic - Machine Learning from Disaster |
1,646,791 | def load_para(word_dict, lemma_dict):
EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100)
... | for dataset in combine_df:
dataset['Cabin_Class'] =(dataset.cabinRec+1)*dataset.Pclass | Titanic - Machine Learning from Disaster |
1,646,791 | def build_model(embedding_matrix, nb_words, embedding_size=300):
inp = Input(shape=(max_length,))
x = Embedding(nb_words, embedding_size, weights=[embedding_matrix], trainable=False )(inp)
x = SpatialDropout1D(0.3 )(x)
x1 = Bidirectional(LSTM(256, return_sequences=True))(x)
x2 = Bidirectional(GRU(128, return_sequenc... | train_df=train_df.drop('Sex',axis=1)
test_df=test_df.drop('Sex',axis=1 ) | Titanic - Machine Learning from Disaster |
1,646,791 | start_time = time.time()
print("Loading data...")
train = pd.read_csv(".. /input/train.csv" ).fillna(' ')
test = pd.read_csv('.. /input/test.csv' ).fillna(' ')
train_text = train['question_text']
test_text = test['question_text']
text_list = pd.concat([train_text, test_text])
y = train['target'].values
num_train_da... | X_train_valid = train_df.drop('Survived',axis=1)
y_train_valid = train_df['Survived']
X_test = test_df
X_train,X_valid,y_train,y_valid=train_test_split(X_train_valid,y_train_valid,test_size=0.25,random_state=0)
print(X_train.shape,X_test.shape,X_valid.shape ) | Titanic - Machine Learning from Disaster |
1,646,791 | print("Start training...")
start_time = time.time()
model = build_model(embedding_matrix, nb_words, embedding_size)
model.summary()<train_model> | gradb= GradientBoostingClassifier(learning_rate=0.01,random_state=0,n_estimators=2000,max_features=4)
gradb.fit(X_train,y_train)
print(gradb.score(X_valid,y_valid))
plot_model_var_imp(gradb,X_train,y_train ) | Titanic - Machine Learning from Disaster |
1,646,791 | model.fit(train_word_sequences, y, batch_size=batch_size, epochs=num_epoch-1, verbose=2)
pred_prob += 0.15*np.squeeze(model.predict(test_word_sequences, batch_size=batch_size, verbose=2))
model.fit(train_word_sequences, y, batch_size=batch_size, epochs=1, verbose=2)
pred_prob += 0.35*np.squeeze(model.predict(test_wor... | clf = XGBClassifier(random_state=0,n_jobs=-1)
cv_sets = ShuffleSplit(X_train.shape[0], n_iter =5, test_size = 0.20, random_state = 7)
parameters = {'n_estimators':list(range(100,1000,100)) ,
'learning_rate':[0.05,0.1,0.25,0.5,0.75],
'reg_lambda':[1,10,15,20,25]}
acc_scorer=make_scorer(accuracy_score)
grid_obj=GridSe... | Titanic - Machine Learning from Disaster |
1,646,791 | <train_model><EOS> | ids=test['PassengerId']
predictions = clf_best.predict(X_test)
my_submission = pd.DataFrame({ 'PassengerId' : ids, 'Survived': predictions })
my_submission.to_csv('submission.csv', index=False)
| Titanic - Machine Learning from Disaster |
446,701 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<load_from_csv> | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import G... | Titanic - Machine Learning from Disaster |
446,701 | 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)
train_df["question_text"] = train_df["question_text"].str.lower()
test_df["question_text"] = test_df["question_text"].str.lower()
def clean_text1(x):
... | titanic_df = pd.read_csv(".. /input/train.csv")
test_df = pd.read_csv(".. /input/test.csv")
titanic_df.head() | Titanic - Machine Learning from Disaster |
446,701 | np.random.seed(481945 )<import_modules> | def get_combined_data() :
train = pd.read_csv('.. /input/train.csv')
test = pd.read_csv('.. /input/test.csv')
targets = train.Survived
train.drop('Survived', 1, inplace=True)
combined = train.append(test)
combined.reset_index(inplace=True)
combined.drop('index', inplace=True, axis=1)
return combined | Titanic - Machine Learning from Disaster |
446,701 | from sklearn.metrics import pairwise<import_modules> | combined['Cabin'][combined.Cabin.isnull() ] = 'U0' | Titanic - Machine Learning from Disaster |
446,701 | from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn import metrics<categorify> | def get_titles() :
global combined
combined['Title'] = combined['Name'].map(lambda name:name.split(',')[1].split('.')[0].strip())
Title_Dictionary = {
"Capt": "Officer",
"Col": "Officer",
"Major": "Officer",
"Jonkheer": "Royalty",
"Don": "Royalty",
"Sir" : "Royalty",
"Dr": "Officer",
"Rev": "Officer",
"the Countess":"... | Titanic - Machine Learning from Disaster |
446,701 | def summary(model, input_size, batch_size=-1, device="cuda", input_type=torch.float32):
def register_hook(module):
def hook(module, input, output):
class_name = str(module.__class__ ).split(".")[-1].split("'")[0]
module_idx = len(summary)
m_key = "%s-%i" %(class_name, module_idx + 1)
summary[m_key] = OrderedDict()
su... | grouped_train = combined.head(891 ).groupby(['Sex','Pclass','Title'])
grouped_median_train = grouped_train.median()
grouped_test = combined.iloc[891:].groupby(['Sex','Pclass','Title'])
grouped_median_test = grouped_test.median()
grouped_median_train | Titanic - Machine Learning from Disaster |
446,701 | class CyclicLR(_LRScheduler):
def __init__(self,
optimizer,
base_lr=1e-3,
max_lr=6e-3,
step_size_up=2000,
step_size_down=None,
mode='triangular',
gamma=1.,
scale_fn=None,
scale_mode='cycle',
last_batch_idx=-1):
if not isinstance(optimizer, Optimizer):
raise TypeError('{} is not an Optimizer'.format(
type(optimizer )... | def process_age() :
global combined
def fillAges(row, grouped_median):
if row['Sex']=='female' and row['Pclass'] == 1:
if row['Title'] == 'Miss':
return grouped_median.loc['female', 1, 'Miss']['Age']
elif row['Title'] == 'Mrs':
return grouped_median.loc['female', 1, 'Mrs']['Age']
elif row['Title'] == 'Officer':
return ... | Titanic - Machine Learning from Disaster |
446,701 | quora_data = pd.read_csv('.. /input/train.csv' )<load_from_csv> | def process_names() :
global combined
combined.drop('Name',axis=1,inplace=True)
titles_dummies = pd.get_dummies(combined['Title'],prefix='Title')
combined = pd.concat([combined,titles_dummies],axis=1)
combined.drop('Title',axis=1,inplace=True)
status('names' ) | Titanic - Machine Learning from Disaster |
446,701 | quora_test_data = pd.read_csv('.. /input/test.csv' )<define_variables> | def process_embarked() :
global combined
combined.head(891 ).Embarked.fillna('S', inplace=True)
combined.iloc[891:].Embarked.fillna('S', inplace=True)
embarked_dummies = pd.get_dummies(combined['Embarked'],prefix='Embarked')
combined = pd.concat([combined,embarked_dummies],axis=1)
combined.drop('Embarked',axis=1,in... | Titanic - Machine Learning from Disaster |
446,701 | for s in sample[sample.target == 1].question_text:
print(s )<import_modules> | def process_cabin() :
global combined
combined.Cabin.fillna('U', inplace=True)
combined['Cabin'] = combined['Cabin'].map(lambda c : c[0])
cabin_dummies = pd.get_dummies(combined['Cabin'], prefix='Cabin')
combined = pd.concat([combined,cabin_dummies], axis=1)
combined.drop('Cabin', axis=1, inplace=True)
status('cab... | Titanic - Machine Learning from Disaster |
446,701 | from nltk.tokenize import TweetTokenizer<string_transform> | def process_sex() :
global combined
combined['Sex'] = combined['Sex'].map({'male':1,'female':0})
status('sex' ) | Titanic - Machine Learning from Disaster |
446,701 | print(nltk.tokenize.word_tokenize("Don't spoil the movie or I'll kill you"))<string_transform> | def process_pclass() :
global combined
pclass_dummies = pd.get_dummies(combined['Pclass'], prefix="Pclass")
combined = pd.concat([combined,pclass_dummies],axis=1)
combined.drop('Pclass',axis=1,inplace=True)
status('pclass' ) | Titanic - Machine Learning from Disaster |
446,701 | print(TweetTokenizer().tokenize("Don't spoil the movie or I'll kill you"))<string_transform> | combined.drop('PassengerId', inplace=True, axis=1 ) | Titanic - Machine Learning from Disaster |
446,701 | def tokenize(questions):
tokenized_questions = []
for iteration, text in enumerate(questions):
if iteration % 50000 == 0:
print(iteration, "texts tokenized")
tokenized_questions.append([t.lower() for t in TweetTokenizer().tokenize(text)])
return tokenized_questions<string_transform> | def process_ticket() :
global combined
def cleanTicket(ticket):
ticket = ticket.replace('.','')
ticket = ticket.replace('/','')
ticket = ticket.split()
ticket = map(lambda t : t.strip() , ticket)
ticket = list(filter(lambda t : not t.isdigit() , ticket))
if len(ticket)> 0:
return ticket[0]
else:
return 'XXX'
combine... | Titanic - Machine Learning from Disaster |
446,701 | dev_tokens = tokenize(quora_data.question_text )<string_transform> | def process_family() :
global combined
combined['FamilySize'] = combined['Parch'] + combined['SibSp'] + 1
combined['Singleton'] = combined['FamilySize'].map(lambda s: 1 if s == 1 else 0)
combined['SmallFamily'] = combined['FamilySize'].map(lambda s: 1 if 2<=s<=4 else 0)
combined['LargeFamily'] = combined['FamilySize'... | Titanic - Machine Learning from Disaster |
446,701 | test_tokens = tokenize(quora_test_data.question_text )<import_modules> | pd.isnull(combined ).sum() | Titanic - Machine Learning from Disaster |
446,701 | import torchtext<import_modules> | def compute_score(clf, X, y, scoring='accuracy'):
xval = cross_val_score(clf, X, y, cv = 5, scoring=scoring)
return np.mean(xval ) | Titanic - Machine Learning from Disaster |
446,701 | from collections import Counter
import itertools<split> | def recover_train_test_target() :
global combined
train0 = pd.read_csv('.. /input/train.csv')
targets = train0.Survived
train = combined.head(891)
test = combined.iloc[891:]
return train, test, targets | Titanic - Machine Learning from Disaster |
446,701 | train_tokens, val_tokens, train_labels, val_labels = train_test_split(dev_tokens, quora_data.target, test_size=0.1 )<define_variables> | train.Fare.loc[50:] | Titanic - Machine Learning from Disaster |
446,701 | word_counts = Counter(itertools.chain(*train_tokens))<count_values> | clf = RandomForestClassifier(n_estimators=50, max_features='sqrt')
clf = clf.fit(train,targets)
print(clf.feature_importances_ ) | Titanic - Machine Learning from Disaster |
446,701 | print(len(word_counts))
print(word_counts.most_common(10))<import_modules> | model = SelectFromModel(clf, prefit=True)
train_reduced = model.transform(train)
train_reduced.shape | Titanic - Machine Learning from Disaster |
446,701 | from gensim.models.keyedvectors import KeyedVectors<load_pretrained> | run_gs = False
if run_gs:
parameter_grid = {
'max_depth' : [4, 6, 8],
'n_estimators': [50, 10],
'max_features': ['sqrt', 'auto', 'log2'],
'min_samples_split': [1, 3, 10],
'min_samples_leaf': [1, 3, 10],
'bootstrap': [True, False],
}
forest = RandomForestClassifier()
cross_validation = StratifiedKFold(targets, n_folds=5... | Titanic - Machine Learning from Disaster |
446,701 | gensim_vectors = KeyedVectors.load_word2vec_format('.. /input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin', binary=True )<feature_engineering> | compute_score(model, train, targets, scoring='accuracy' ) | Titanic - Machine Learning from Disaster |
446,701 | def filter_vectors(gensim_vectors, words):
result = {}
for w in words:
if w in gensim_vectors.vocab:
result[w] = gensim_vectors[w].copy()
return result<groupby> | output = model.predict(test ).astype(int)
df_output = pd.DataFrame()
aux = pd.read_csv('.. /input/test.csv')
df_output['PassengerId'] = aux['PassengerId']
df_output['Survived'] = output
df_output[['PassengerId','Survived']].to_csv('output.csv',index=False ) | Titanic - Machine Learning from Disaster |
11,512,965 | filtered_vectors = filter_vectors(gensim_vectors, word_counts.keys() )<drop_column> | train = pd.read_csv('.. /input/titanic/train.csv')
test_x = pd.read_csv('.. /input/titanic/test.csv')
sub = pd.read_csv('.. /input/titanic/gender_submission.csv')
df = pd.concat([train,test_x], sort = False)
df.head() | Titanic - Machine Learning from Disaster |
11,512,965 | del gensim_vectors<count_values> | CabinFill = df[df['Cabin'].notnull() ]
CabinNull = df[df['Cabin'].isnull() ]
CabinFill['Cabin'] = CabinFill['Cabin'].astype(str ).str[0]
df = pd.concat([CabinFill, CabinNull], sort = False ).sort_values(['PassengerId'])
df['Sex'] = pd.Categorical(df.Sex ).codes
df['Embarked'] = pd.Categorical(df.Embarked ).codes
df['C... | Titanic - Machine Learning from Disaster |
11,512,965 | min_occurences = 14
filtered_counts = {w:c for w,c in word_counts.items() if c >= min_occurences}
print(len(filtered_counts))<import_modules> | df.isnull().sum() | Titanic - Machine Learning from Disaster |
11,512,965 | class VocabLike:
def __init__(self, itos, stoi):
self.itos = itos
self.stoi = stoi<import_modules> | df['Title'] = df['Name'].map(lambda name: name.split(',')[1].split('.')[0].strip())
df['Sur'] = df['Name'].map(lambda name: name.split(',')[0])
df['Title'].value_counts() | Titanic - Machine Learning from Disaster |
11,512,965 | from collections import defaultdict<feature_engineering> | titles_dummies = pd.get_dummies(df['Title'], prefix='Title')
sur_dummies = pd.get_dummies(df['Sur'], prefix='Sur')
df = pd.concat([df, titles_dummies, sur_dummies], axis=1)
df.drop(['Title', 'Sur'], axis=1, inplace=True)
df.head() | Titanic - Machine Learning from Disaster |
11,512,965 | specials = ['<unk>', '<pad>', '<eos>']
filtered_counts.update({w:0 for w in specials})
stoi = defaultdict(lambda:0)
itos = [0] * len(filtered_counts)
trainable_words = {w for w in filtered_counts.keys() if w not in specials and w not in filtered_vectors}
pretrained_words = {w for w in filtered_counts.keys() if w not... | logloss, accuracy, y_preds = [],[],[]
cv_train = np.zeros(( len(train),))
drop_cols = ['Name','PassengerId','Ticket','Survived','Fare','Cabin','Embarked',
'Age','SibSp','Parch']
train = df[:len(train)]
train_x = train.drop(drop_cols, axis=1)
train_y = train['Survived']
test = df[len(train):]
test_x = test.drop(drop_co... | Titanic - Machine Learning from Disaster |
11,512,965 | def extract_vectors(vocab, vec_dict, offset, total, vec_size):
vectors = np.zeros(( total, vec_size), dtype=np.float32)
for i in range(total):
word = vocab.itos[i + offset]
assert word in vec_dict
vectors[i] = vec_dict[word]
return vectors<feature_engineering> | y_pred_cv =(cv_train > 0.5 ).astype(int)
accuracy_score(train_y, y_pred_cv ) | Titanic - Machine Learning from Disaster |
11,512,965 | np_vectors = extract_vectors(vocab, filtered_vectors,
len(specials)+ len(trainable_words),
len(pretrained_words),
300 )<statistical_test> | sub_y_lgb = sum(y_preds)/ len(y_preds)
sub_y_lgb =(sub_y_lgb > 0.5 ).astype(int)
sub['sub_y_lgb'] = sub_y_lgb | Titanic - Machine Learning from Disaster |
11,512,965 | def nearest_neighbors(vocab, embeddings, word, topn, use_offset=False):
offset = len(specials)+ len(trainable_words)if use_offset else 0
assert word in vocab.stoi
word_index = vocab.stoi[word] - offset
sims = pairwise.cosine_similarity(embeddings[word_index].reshape(1,-1),embeddings ).ravel()
indices = np.argsort(sims)... | accuracy, y_preds_LR = [],[]
cv_train = np.zeros(( len(train),))
drop_cols = ['Name','PassengerId','Ticket','Survived','Fare','Cabin','Embarked',
'Age','SibSp','Parch']
train = df[:len(train)]
train_x = train.drop(drop_cols, axis=1)
train_y = train['Survived']
test = df[len(train):]
test_x = test.drop(drop_cols, axis=... | Titanic - Machine Learning from Disaster |
11,512,965 | nearest_neighbors(vocab, np_vectors, 'we'll', 10, True )<set_options> | sub_y_LR = sum(y_preds_LR)/ len(y_preds_LR)
sub_y_LR =(sub_y_LR > 0.5 ).astype(int)
sub['sub_y_LR'] = sub_y_LR | Titanic - Machine Learning from Disaster |
11,512,965 | gc.collect()<categorify> | drop_cols = ['Name','PassengerId','Ticket','Survived']
train = df[:len(train)]
X = train.drop(drop_cols, axis=1)
y = train['Survived']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0)
model = RandomForestClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)... | Titanic - Machine Learning from Disaster |
11,512,965 | def to_word_indices(tokens, vocab, start_index, end_index):
return [[start_index] + [vocab.stoi[w] for w in sent] + [end_index] for sent in tokens]<define_variables> | drop_cols = ['Name','PassengerId','Ticket','Survived']
test = df[len(train):]
test_x = test.drop(drop_cols, axis=1)
sub_y_RF = model.predict(test_x)
sub['sub_y_RF'] = sub_y_RF | Titanic - Machine Learning from Disaster |
11,512,965 | class TokenToIdDataset(torch.utils.data.Dataset):
def __init__(self, tokens, labels, vocab, max_size=-1, min_size=10, precompute=False, precomputed=False):
self._start_index = vocab.stoi['<sos>']
self._end_index = vocab.stoi['<eos>']
self._pad_index = vocab.stoi['<pad>']
if precompute and not precomputed:
tokens = to_w... | drop_cols = ['Name','PassengerId','Ticket','Survived','Fare','Cabin','Embarked',
'Age','SibSp','Parch']
x_NN = df.drop(drop_cols, axis=1)
X_dummies_train = x_NN.iloc[0:890]
X_dummies_test = x_NN.iloc[891:]
Y = df.iloc[0:890]["Survived"] | Titanic - Machine Learning from Disaster |
11,512,965 | min_length=10
train_dataset = TokenToIdDataset(train_tokens,train_labels.values, vocab,min_size=min_length, precompute=True)
val_dataset = TokenToIdDataset(val_tokens, val_labels.values, vocab,min_size=min_length, precompute=True )<set_options> | def create_neural_net(in_shape, lyrs=[4], act='relu', opt='Adam', dr=0.0):
seed(37556)
tf.random.set_seed(37556)
model = Sequential()
model.add(Dense(lyrs[0], input_dim=in_shape, activation=act))
for i in range(1,len(lyrs)) :
model.add(Dense(lyrs[i], activation=act))
model.add(Dropout(dr))
model.add(Dense(1, activati... | Titanic - Machine Learning from Disaster |
11,512,965 | gc.collect()<import_modules> | single_net = create_neural_net(X_dummies_train.shape[1], lyrs =[4])
single_net.summary() | Titanic - Machine Learning from Disaster |
11,512,965 | import tqdm
from tqdm import tqdm_notebook<load_pretrained> | training = single_net.fit(X_dummies_train, Y, epochs=100, batch_size=32,
validation_split=0.25, verbose=0)
val_acc = np.mean(training.history['val_accuracy'])
print("
%s: %.2f%%" %('val_acc', val_acc*100)) | Titanic - Machine Learning from Disaster |
11,512,965 | class BestModel:
def __init__(self, model_path, optimizer_path, best_loss=10000):
self.best_loss = best_loss
self.model_path = model_path
self.optimizer_path = optimizer_path
def update(self, loss, model, optimizer=None):
self.best_loss = loss
torch.save(model.state_dict() , self.model_path)
if optimizer:
torch.save(o... | nn = KerasClassifier(build_fn=create_neural_net,
in_shape = X_dummies_train.shape[1],
lyrs=[12, 8, 4], epochs=50, dr=0.1, batch_size=1,
verbose=0)
nn.fit(X_dummies_train, Y)
sub['sub_y_NN'] = nn.predict(X_dummies_test ).astype('int32' ) | Titanic - Machine Learning from Disaster |
11,512,965 | <categorify><EOS> | model_cols = ['sub_y_lgb','sub_y_RF','sub_y_NN','sub_y_LR']
sub['Survived'] = np.sum(sub[model_cols], axis=1)
sub['Survived'] =(sub['Survived'] >= 3 ).astype(int)
sub.drop(model_cols, axis=1, inplace=True)
sub.to_csv('sub_title_ensembled.csv', index=False)
sub.head() | Titanic - Machine Learning from Disaster |
3,861,474 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<normalization> | import numpy as np
import pandas as pd
import os
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import torch.nn.functional as F
from sklearn.preprocessing import LabelEncoder
| Titanic - Machine Learning from Disaster |
3,861,474 | class DotProductAttentionScoring(nn.Module):
def __init__(self, scale):
super().__init__()
self.scale = np.sqrt(scale)
def forward(self, query, keys):
b_q, n_q, d_q = query.size()
b_k, n_k, d_k = keys.size()
assert b_q == b_k
dot_products = torch.bmm(query, torch.transpose(keys, 1, 2)) / self.scale
return dot_products... | train = pd.read_csv('.. /input/train.csv')
test = pd.read_csv('.. /input/test.csv' ) | Titanic - Machine Learning from Disaster |
3,861,474 | class TimeInvariant(nn.Module):
def __init__(self, inner):
super().__init__()
self.inner = inner
def forward(self, data):
batch,time,dim = data.size()
result = self.inner(data.view(batch * time, dim))
result = result.view(batch, time, -1)
return result
<categorify> | train = pd.read_csv('.. /input/train.csv')
test = pd.read_csv('.. /input/test.csv' ) | Titanic - Machine Learning from Disaster |
3,861,474 | class PositionalEncoding(nn.Module):
"Implement the PE function."
def __init__(self, d_model, max_len=5000):
super(PositionalEncoding, self ).__init__()
pe = torch.zeros(max_len, d_model,dtype=torch.float32)
position = torch.arange(0., max_len ).unsqueeze(1)
div_term = torch.exp(torch.arange(0., d_model, 2)*
-(math.l... | all_df = pd.concat([train, test], sort=False ) | Titanic - Machine Learning from Disaster |
3,861,474 | class SelfAttentionNet(nn.Module):
def __init__(self, vocab, embeddings, num_trainable):
super().__init__()
self.pos_encoding = PositionalEncoding(50,120)
self.num_trainable = num_trainable
self.embedding = nn.Embedding(num_embeddings=len(vocab.itos), embedding_dim=300,padding_idx=vocab.stoi['<pad>'])
self.embedding.... | def preprocess(df, cat_cols):
df = df.drop(['PassengerId', 'Name', 'Ticket', 'Cabin'], axis=1)
for cat_col in cat_cols:
if cat_col in ['Embarked']:
df[cat_col] = LabelEncoder().fit_transform(df[cat_col].astype(str))
else:
df[cat_col] = LabelEncoder().fit_transform(df[cat_col])
df = df.fillna(df.mean())
return df | Titanic - Machine Learning from Disaster |
3,861,474 | class Net(nn.Module):
def __init__(self, vocab, embeddings, num_trainable, normalize=False):
super().__init__()
self.num_trainable = num_trainable
self.embedding = nn.Embedding(num_embeddings=len(vocab.itos), embedding_dim=300,padding_idx=vocab.stoi['<pad>'])
if normalize:
embeddings = embeddings / np.linalg.norm(embe... | cat_cols = ['Pclass', 'Sex', 'SibSp', 'Parch', 'Embarked']
all_df = preprocess(all_df, cat_cols)
all_df.head() | Titanic - Machine Learning from Disaster |
3,861,474 | num_scratch = len(specials)+ len(trainable_words )<choose_model_class> | class TabularDataset(Dataset):
def __init__(self, df, categorical_columns, output_column=None):
super().__init__()
self.len = df.shape[0]
self.categorical_columns = categorical_columns
self.continous_columns = [col for col in df.columns if col not in self.categorical_columns + [output_column]]
if self.continous_columns... | Titanic - Machine Learning from Disaster |
3,861,474 | net = Net(vocab, np_vectors, num_scratch ).cuda()
best_model = BestModel('best_model', 'best_optimizer' )<choose_model_class> | train_ds = TabularDataset(train_df, cat_cols, 'Survived')
train_dl = DataLoader(train_ds, 64, shuffle=True ) | Titanic - Machine Learning from Disaster |
3,861,474 | criterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([1.])).cuda()
optimizer = torch.optim.Adam(net.parameters() , lr=0.0003 )<prepare_x_and_y> | class TitanicNet(nn.Module):
def __init__(self, emb_dims, n_cont, lin_layer_sizes, output_size):
super().__init__()
self.emb_layers = nn.ModuleList([nn.Embedding(x, y)for x, y in emb_dims])
self.n_embs = sum([y for x, y in emb_dims])
self.n_cont = n_cont
first_lin_layer = nn.Linear(self.n_embs + self.n_cont, lin_laye... | Titanic - Machine Learning from Disaster |
3,861,474 | def truncate_batch(batch):
x,y = batch
if x.shape[1] > 100:
x = x[:,:100]
return x,y<load_pretrained> | cat_dims = [int(all_df[col].nunique())for col in cat_cols]
cat_dims | Titanic - Machine Learning from Disaster |
3,861,474 | train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=256,
collate_fn=lambda samples: truncate_batch(train_dataset.collate(samples)) , shuffle=True)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=256,collate_fn=lambda samples: truncate_batch(val_dataset.collate(samples)))
<define_varia... | emb_dims = [(x, min(50,(x + 1)// 2)) for x in cat_dims]
emb_dims | Titanic - Machine Learning from Disaster |
3,861,474 | print(128 * 112 * 112 * 300 * 4 / 1024 / 1024 )<train_model> | torch.manual_seed(2 ) | Titanic - Machine Learning from Disaster |
3,861,474 | train_network(net, optimizer,criterion,train_loader,val_loader,16, 3,best_model,
after_gradient=lambda epoch, network: network.zero_embedding_grad())
best_model.load(net, optimizer)
<train_model> | model = TitanicNet(emb_dims, n_cont=2, lin_layer_sizes=[50, 100, 50], output_size=1)
optimizer = torch.optim.Adam(model.parameters() , lr=0.003)
no_of_epochs = 10
criterion = nn.BCELoss()
for epoch in range(no_of_epochs):
epoch_loss = 0
epoch_accuracy = 0
i = 0
for y, cont_x, cat_x in train_dl:
preds = model(cont_x, ... | Titanic - Machine Learning from Disaster |
3,861,474 | train_network(net, optimizer,criterion,train_loader,val_loader,10, 3,best_model,
after_gradient=lambda epoch, network: network.zero_embedding_grad())
best_model.load(net, optimizer)
<load_pretrained> | test_df = all_df.tail(test.shape[0])
test_ds = TabularDataset(test_df, cat_cols, 'Survived')
test_dl = DataLoader(test_ds, len(test_ds)) | Titanic - Machine Learning from Disaster |
3,861,474 | best_model.load(net, optimizer )<create_dataframe> | with torch.no_grad() :
for _, cont_x, cat_x in test_dl:
preds = model(cont_x, cat_x)
preds =(preds > 0.5 ) | Titanic - Machine Learning from Disaster |
3,861,474 | best_model_with_fixed_embeddings = best_model.copy('best_model_fixed', 'best_optimizer_fixed' )<load_pretrained> | output_df = pd.DataFrame({'PassengerId':test['PassengerId'],'Survived':preds.flatten().numpy() } ) | Titanic - Machine Learning from Disaster |
3,861,474 | <train_model><EOS> | output_df.to_csv('titanic_preds.csv', index=False ) | Titanic - Machine Learning from Disaster |
8,512,706 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<load_pretrained> | pd.plotting.register_matplotlib_converters()
%matplotlib inline
%matplotlib inline
%matplotlib inline
plt.style.use('seaborn-whitegrid')
warnings.filterwarnings('ignore' ) | Titanic - Machine Learning from Disaster |
8,512,706 | best_model2 = best_model_with_fixed_embeddings.copy('best_model_low', 'best_optimizer_low')
best_model2.load(net, optimizer)
for g in optimizer.param_groups:
g['lr'] = 0.00003
train_network(net, optimizer,criterion,train_loader,val_loader,10, 3,best_model2)
best_model2.load(net, optimizer )<load_pretrained> | train=pd.read_csv("/kaggle/input/titanic/train.csv")
X_test=pd.read_csv("/kaggle/input/titanic/test.csv")
X_test.copy()
train.info() | 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.