kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
6,488,543 | 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)
... | train = pd.read_csv('.. /input/train.csv')
test = pd.read_csv('.. /input/test.csv')
PassengerId = test['PassengerId']
train.head(3 ) | Titanic - Machine Learning from Disaster |
6,488,543 | 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",
... | full_data = [train, test]
train['Name_length'] = train['Name'].apply(len)
test['Name_length'] = test['Name'].apply(len)
train['Has_Cabin'] = train["Cabin"].apply(lambda x: 0 if type(x)== float else 1)
test['Has_Cabin'] = test["Cabin"].apply(lambda x: 0 if type(x)== float else 1)
for dataset in full_data:
dataset['F... | Titanic - Machine Learning from Disaster |
6,488,543 | total['text'] = total['text'].apply(expand_contractions )<categorify> | drop_elements = ['PassengerId', 'Name', 'Ticket', 'Cabin', 'SibSp']
train = train.drop(drop_elements, axis = 1)
train = train.drop(['CategoricalAge', 'CategoricalFare'], axis = 1)
test = test.drop(drop_elements, axis = 1 ) | Titanic - Machine Learning from Disaster |
6,488,543 | 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 ... | ntrain = train.shape[0]
ntest = test.shape[0]
SEED = 0
NFOLDS = 5
kf = KFold(ntrain, n_folds= NFOLDS, random_state=SEED)
class SklearnHelper(object):
def __init__(self, clf, seed=0, params=None):
params['random_state'] = seed
self.clf = clf(**params)
def train(self, x_train, y_train):
self.clf.fit(x_train, y_train)
... | Titanic - Machine Learning from Disaster |
6,488,543 | tweets = [tweet for tweet in total['text']]
train = total[:len(train)]
test = total[len(train):]<categorify> | def get_oof(clf, x_train, y_train, x_test):
oof_train = np.zeros(( ntrain,))
oof_test = np.zeros(( ntest,))
oof_test_skf = np.empty(( NFOLDS, ntest))
for i,(train_index, test_index)in enumerate(kf):
x_tr = x_train[train_index]
y_tr = y_train[train_index]
x_te = x_train[test_index]
clf.train(x_tr, y_tr)
oof_train[test_... | Titanic - Machine Learning from Disaster |
6,488,543 | 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']... | rf_params = {
'n_jobs': -1,
'n_estimators': 500,
'warm_start': True,
'max_depth': 6,
'min_samples_leaf': 2,
'max_features' : 'sqrt',
'verbose': 0
}
et_params = {
'n_jobs': -1,
'n_estimators':500,
'max_depth': 8,
'min_samples_leaf': 2,
'verbose': 0
}
ada_params = {
'n_estimators': 500,
'learning_rate' : 0.75
}
gb_params... | Titanic - Machine Learning from Disaster |
6,488,543 | 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> | rf = SklearnHelper(clf=RandomForestClassifier, seed=SEED, params=rf_params)
et = SklearnHelper(clf=ExtraTreesClassifier, seed=SEED, params=et_params)
ada = SklearnHelper(clf=AdaBoostClassifier, seed=SEED, params=ada_params)
gb = SklearnHelper(clf=GradientBoostingClassifier, seed=SEED, params=gb_params)
svc = Sklear... | Titanic - Machine Learning from Disaster |
6,488,543 |
<string_transform> | y_train = train['Survived'].ravel()
train = train.drop(['Survived'], axis=1)
x_train = train.values
x_test = test.values | Titanic - Machine Learning from Disaster |
6,488,543 | 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 tenso... | et_oof_train, et_oof_test = get_oof(et, x_train, y_train, x_test)
rf_oof_train, rf_oof_test = get_oof(rf,x_train, y_train, x_test)
ada_oof_train, ada_oof_test = get_oof(ada, x_train, y_train, x_test)
gb_oof_train, gb_oof_test = get_oof(gb,x_train, y_train, x_test)
svc_oof_train, svc_oof_test = get_oof(svc,x_train, ... | Titanic - Machine Learning from Disaster |
6,488,543 | 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' % ... | rf_feature = rf.feature_importances(x_train,y_train)
et_feature = et.feature_importances(x_train, y_train)
ada_feature = ada.feature_importances(x_train, y_train)
gb_feature = gb.feature_importances(x_train,y_train ) | Titanic - Machine Learning from Disaster |
6,488,543 | EMBEDDING_DIM = 200<categorify> | rf_features = [0.10474135, 0.21837029, 0.04432652, 0.02249159, 0.05432591, 0.02854371
,0.07570305, 0.01088129 , 0.24247496, 0.13685733 , 0.06128402]
et_features = [ 0.12165657, 0.37098307 ,0.03129623 , 0.01591611 , 0.05525811 , 0.028157
,0.04589793 , 0.02030357 , 0.17289562 , 0.04853517, 0.08910063]
ada_features = [0.0... | Titanic - Machine Learning from Disaster |
6,488,543 | 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> | cols = train.columns.values
feature_dataframe = pd.DataFrame({'features': cols,
'Random Forest feature importances': rf_features,
'Extra Trees feature importances': et_features,
'AdaBoost feature importances': ada_features,
'Gradient Boost feature importances': gb_features
} ) | Titanic - Machine Learning from Disaster |
6,488,543 | embedding = Embedding(len(word_index)+ 1, EMBEDDING_DIM, weights = [embedding_matrix],
input_length = MAX_SEQUENCE_LENGTH, trainable = False)
<normalization> | feature_dataframe['mean'] = feature_dataframe.mean(axis= 1)
feature_dataframe.head(3 ) | Titanic - Machine Learning from Disaster |
6,488,543 | def scale(df, scaler):
return scaler.fit_transform(df.iloc[:, 2:])
meta_train = scale(train, StandardScaler())
meta_test = scale(test, StandardScaler() )<choose_model_class> | base_predictions_train = pd.DataFrame({'RandomForest': rf_oof_train.ravel() ,
'ExtraTrees': et_oof_train.ravel() ,
'AdaBoost': ada_oof_train.ravel() ,
'GradientBoost': gb_oof_train.ravel()
})
base_predictions_train.head() | Titanic - Machine Learning from Disaster |
6,488,543 | 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(d... | x_train = np.concatenate(( et_oof_train, rf_oof_train, ada_oof_train, gb_oof_train, svc_oof_train), axis=1)
x_test = np.concatenate(( et_oof_test, rf_oof_test, ada_oof_test, gb_oof_test, svc_oof_test), axis=1 ) | Titanic - Machine Learning from Disaster |
6,488,543 | lstm = create_lstm(spatial_dropout =.2, dropout =.2, recurrent_dropout =.2,
learning_rate = 3e-4, bidirectional = True)
lstm.summary()<train_model> | gbm = xgb.XGBClassifier(
n_estimators= 2000,
max_depth= 4,
min_child_weight= 2,
gamma=0.9,
subsample=0.8,
colsample_bytree=0.8,
objective= 'binary:logistic',
nthread= -1,
scale_pos_weight=1 ).fit(x_train, y_train)
predictions = gbm.predict(x_test ) | Titanic - Machine Learning from Disaster |
6,488,543 | <choose_model_class><EOS> | StackingSubmission = pd.DataFrame({ 'PassengerId': PassengerId,
'Survived': predictions })
StackingSubmission.to_csv("gender_submission.csv", index=False ) | Titanic - Machine Learning from Disaster |
7,258,897 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<choose_model_class> | import math, time, random, datetime | Titanic - Machine Learning from Disaster |
7,258,897 | 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... | %matplotlib inline
plt.style.use('seaborn-whitegrid')
warnings.filterwarnings('ignore' ) | Titanic - Machine Learning from Disaster |
7,258,897 | lstm_2 = create_lstm_2(spatial_dropout =.4, dropout =.4, recurrent_dropout =.4,
learning_rate = 3e-4, bidirectional = True)
lstm_2.summary()<train_model> | train = pd.read_csv('.. /input/titanic/train.csv')
test = pd.read_csv('.. /input/titanic/test.csv' ) | Titanic - Machine Learning from Disaster |
7,258,897 | history2 = lstm_2.fit([nlp_train, meta_train], labels, validation_split =.2,
epochs = 30, batch_size = 21, verbose = 1 )<predict_on_test> | ntrain = train.shape[0]
ntest = test.shape[0]
y_train = train['Survived'].values
passId = test['PassengerId']
data = pd.concat(( train, test))
print("data size is: {}".format(data.shape)) | Titanic - Machine Learning from Disaster |
7,258,897 | submission_lstm = pd.DataFrame()
submission_lstm['id'] = test_id
submission_lstm['prob'] = lstm_2.predict([nlp_test, meta_test])
submission_lstm['target'] = submission_lstm['prob'].apply(lambda x: 0 if x <.5 else 1)
submission_lstm.head(10 )<choose_model_class> | data.isnull().sum() | Titanic - Machine Learning from Disaster |
7,258,897 | def create_dual_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 = SpatialDropou... | data.Age.isnull().any() | Titanic - Machine Learning from Disaster |
7,258,897 | history3 = dual_lstm.fit([nlp_train, meta_train], labels, validation_split =.2,
epochs = 25, batch_size = 21, verbose = 1 )<predict_on_test> | train.groupby(['Pclass','Survived'])['Survived'].count() | Titanic - Machine Learning from Disaster |
7,258,897 | 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> | train.groupby('Pclass' ).Survived.mean() | Titanic - Machine Learning from Disaster |
7,258,897 | BATCH_SIZE = 32
EPOCHS = 2
USE_META = True
ADD_DENSE = False
DENSE_DIM = 64
ADD_DROPOUT = False
DROPOUT =.2<install_modules> | data.Name.value_counts() | Titanic - Machine Learning from Disaster |
7,258,897 | !pip install --quiet transformers
<categorify> | temp = data.copy()
temp['Initial']=0
for i in train:
temp['Initial']=data.Name.str.extract('([A-Za-z]+)\.' ) | Titanic - Machine Learning from Disaster |
7,258,897 | 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> | def survpct(a):
return temp.groupby(a ).Survived.mean()
survpct('Initial' ) | Titanic - Machine Learning from Disaster |
7,258,897 | 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(encod... | temp.groupby('Initial')['Age'].mean() | Titanic - Machine Learning from Disaster |
7,258,897 | 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... | temp['Newage']=temp['Age']
def newage(k,n):
temp.loc[(temp.Age.isnull())&(temp.Initial==k),'Newage']= n
newage('Capt',int(70.000000))
newage('Col',int(54.000000))
newage('Countess',int(33.000000))
newage('Don',int(40.000000))
newage('Dona',int(39.000000))
newage('Dr',int(43.571429))
newage('Jonkheer',int(38.000000))
ne... | Titanic - Machine Learning from Disaster |
7,258,897 | train = pd.read_csv('.. /input/nlp-getting-started/train.csv')
test = pd.read_csv('.. /input/nlp-getting-started/test.csv' )<categorify> | groupmean('Age_Range', 'Survived' ) | Titanic - Machine Learning from Disaster |
7,258,897 | 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:', l... | temp['Gender']= temp['Sex']
for n in range(1,4):
temp.loc[(temp['Sex'] == 'male')&(temp['Pclass'] == n),'Gender']= 'm'+str(n)
temp.loc[(temp['Sex'] == 'female')&(temp['Pclass'] == n),'Gender']= 'w'+str(n)
temp.loc[(temp['Gender'] == 'm3'),'Gender']= 'm2'
temp.loc[(temp['Gender'] == 'w3'),'Gender']= 'w2'
temp.loc[(tem... | Titanic - Machine Learning from Disaster |
7,258,897 | 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> | groupmean('Gender', 'Survived' ) | Titanic - Machine Learning from Disaster |
7,258,897 | BERT_large.load_weights('large_model.h5')
preds_bert = BERT_large.predict([test_input_ids,test_attention_masks,meta_test] )<prepare_output> | temp['Agroup']=0
temp.loc[temp['Newage']<1.0,'Agroup']= 1
temp.loc[(temp['Newage']>=1.0)&(temp['Newage']<=3.0),'Agroup']= 2
temp.loc[(temp['Newage']>3.0)&(temp['Newage']<11.0),'Agroup']= 7
temp.loc[(temp['Newage']>=11.0)&(temp['Newage']<15.0),'Agroup']= 13
temp.loc[(temp['Newage']>=15.0)&(temp['Newage']<18.0),'Agroup']... | Titanic - Machine Learning from Disaster |
7,258,897 | 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> | groupmean('Agroup', 'Survived' ) | Titanic - Machine Learning from Disaster |
7,258,897 | submission_bert = submission_bert[['id', 'target']]
submission_bert.to_csv('submission_bert.csv', index = False)
print('Blended submission has been saved to disk' )<install_modules> | groupmean('Agroup', 'Age' ) | Titanic - Machine Learning from Disaster |
7,258,897 | !pip install bert-for-tf2<import_modules> | temp['Alone']=0
temp.loc[(temp['SibSp']==0)&(temp['Parch']==0),'Alone']= 1 | Titanic - Machine Learning from Disaster |
7,258,897 | import numpy as np
import pandas as pd
import re
import tensorflow as tf
from tensorflow_core.python.keras.layers import Dense, Input
from tensorflow.keras.optimizers import Adam
from tensorflow_core.python.keras.models import Model
from tensorflow_core.python.keras.callbacks import ModelCheckpoint
import tensorflow_hu... | temp['Family']=0
for i in temp:
temp['Family'] = temp['Parch'] + temp['SibSp'] +1 | Titanic - Machine Learning from Disaster |
7,258,897 | def clean_text(text):
new_text = []
for each in text.split() :
if each.isalpha() :
new_text.append(each)
cleaned_text = ' '.join(new_text)
cleaned_text = re.sub(r'https?:\/\/t.co\/[A-Za-z0-9]+','',cleaned_text)
return cleaned_text<categorify> | bag('Parch','Survived','Survived per Parch','Parch Survived vs Not Survived' ) | Titanic - Machine Learning from Disaster |
7,258,897 | def bert_encode(texts, tokenizer, max_len =512):
all_tokens = []
all_masks = []
all_segments = []
for text in texts:
text = tokenizer.tokenize(text)
text = text[:max_len-2]
input_sequence = ['[CLS]'] + text +['[SEP]']
pad_len = max_len - len(input_sequence)
tokens = tokenizer.convert_tokens_to_ids(input_sequence)
to... | temp.Ticket.isnull().any() | Titanic - Machine Learning from Disaster |
7,258,897 | test_text = list(test_data['text'])
test_input = bert_encode(test_text, tokenizer, max_len=100)
min_loss_index = all_loss.index(min(all_loss))
results = all_models[min_loss_index].predict(test_input)
submission_data = pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv')
submission_data['target'] =... | temp['Initick'] = 0
for s in temp:
temp['Initick']=temp.Ticket.str.extract('^([A-Za-z]+)')
for s in temp:
temp.loc[(temp.Initick.isnull()),'Initick']='X'
temp.head() | Titanic - Machine Learning from Disaster |
7,258,897 | train = pd.read_csv('.. /input/nlp-getting-started/train.csv')
test = pd.read_csv('.. /input/nlp-getting-started/test.csv')
sample = pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv' )<count_duplicates> | train['Tgroup'] = 0
temp['Tgroup'] = 0
temp.loc[(temp['Initick']=='X')&(temp['Pclass']==1),'Tgroup']= 1
temp.loc[(temp['Initick']=='X')&(temp['Pclass']==2),'Tgroup']= 2
temp.loc[(temp['Initick']=='X')&(temp['Pclass']==3),'Tgroup']= 3
temp.loc[(temp['Initick']=='Fa'),'Tgroup']= 3
temp.loc[(temp['Initick']=='SCO'),'Tgrou... | Titanic - Machine Learning from Disaster |
7,258,897 | sns.countplot(train.text.duplicated() )<count_duplicates> | groupmean('Tgroup', 'Survived' ) | Titanic - Machine Learning from Disaster |
7,258,897 | duplicate_index = train[train.text.duplicated() ].index
train.drop(index = duplicate_index, inplace = True)
train.reset_index(drop = True, inplace = True )<define_variables> | temp['Fgroup']=0
temp.loc[temp['Fare']<= 7.125,'Fgroup']=5.0
temp.loc[(temp['Fare']>7.125)&(temp['Fare']<=7.9),'Fgroup']= 7.5
temp.loc[(temp['Fare']>7.9)&(temp['Fare']<=8.03),'Fgroup']= 8.0
temp.loc[(temp['Fare']>8.03)&(temp['Fare']<10.5),'Fgroup']= 9.5
temp.loc[(temp['Fare']>=10.5)&(temp['Fare']<23.0),'Fgroup']= 16.0
... | Titanic - Machine Learning from Disaster |
7,258,897 | shortforms = {"ain't": "am not",
"aren't": "are 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",
"h... | temp.Cabin.value_counts() | Titanic - Machine Learning from Disaster |
7,258,897 | def cleaner(text):
text = str(text ).lower()
text = re.sub(r'<*?>',' ',text)
text = re.sub(r'https?://\S+|www\.\S+',' ',text)
text = ' '.join([shortforms[word]
if word in shortforms.keys() else word
for word in text.split() ])
text = str(text ).lower()
text = re.sub(r'^\s','',text)
text = re.sub(r'\s+',' ',text)
r... | temp.Cabin.isnull().sum() | Titanic - Machine Learning from Disaster |
7,258,897 | %%time
train['cleaner_text'] = train.text.progress_apply(lambda x: cleaner(x))
test['cleaner_text'] = test.text.progress_apply(lambda x: cleaner(x))<load_pretrained> | temp['Inicab'] = 0
for i in temp:
temp['Inicab']=temp.Cabin.str.extract('^([A-Za-z]+)')
temp.loc[(( temp.Cabin.isnull())&(temp.Pclass.values == 1)) ,'Inicab']='X'
temp.loc[(( temp.Cabin.isnull())&(temp.Pclass.values == 2)) ,'Inicab']='Y'
temp.loc[(( temp.Cabin.isnull())&(temp.Pclass.values == 3)) ,'Inicab']='Z'
| Titanic - Machine Learning from Disaster |
7,258,897 | case = 'roberta-base'
tokenizer = RobertaTokenizer.from_pretrained(case)
config = AutoConfig.from_pretrained(case, output_attentions = True, output_hidden_states = True)
model = TFAutoModel.from_pretrained(case, config = config)
bert = TFRobertaMainLayer(config )<categorify> | temp.Inicab.value_counts() | Titanic - Machine Learning from Disaster |
7,258,897 | %%time
def convert2token(all_text):
token_id, attention_id = [], []
for i, sent in tqdm.tqdm(enumerate(all_text)) :
token_dict = tokenizer.encode_plus(sent, max_length=60, pad_to_max_length=True, return_attention_mask=True,
return_tensors='tf', add_special_tokens= True)
token_id.append(token_dict['input_ids'])
attent... | temp['Inicab'].replace(['A','B', 'C', 'D', 'E', 'F', 'G','T', 'X', 'Y', 'Z'],[1,2,3,4,5,6,7,8,9,10,11],inplace=True ) | Titanic - Machine Learning from Disaster |
7,258,897 | def building_model(need_emb):
inp_1 = tf.keras.layers.Input(shape =(60,), name = 'token_id', dtype = 'int32')
inp_2 = tf.keras.layers.Input(shape =(60,), name = 'mask_id', dtype = 'int32')
x1 = tf.keras.layers.Reshape(( 60,))(inp_1)
x2 = tf.keras.layers.Reshape(( 60,))(inp_2)
if need_emb:
emb = model(x1, attention_... | temp.loc[(temp.Embarked.isnull())] | Titanic - Machine Learning from Disaster |
7,258,897 | Emb_Model.compile(metrics=['accuracy'], optimizer=tf.keras.optimizers.Adam(learning_rate = 4e-5), loss='binary_crossentropy')
Emb_Model.fit([np.reshape(train_token_id,(7503,60)) , np.reshape(train_attention_id,(7503,60)) ], train.target, epochs=10,
batch_size=64, validation_split=0.20, shuffle = True )<predict_on_test... | temp.loc[(temp.Ticket == '113572')] | Titanic - Machine Learning from Disaster |
7,258,897 | %%time
Emb_Model_Answer = Emb_Model.predict([np.reshape(test_token_id,(3263,60)) , np.reshape(test_attention_id,(3263,60)) ] )<train_model> | temp.sort_values(['Ticket'], ascending = True)[35:45] | Titanic - Machine Learning from Disaster |
7,258,897 | Tune_Bert.compile(metrics=['accuracy'], optimizer=tf.keras.optimizers.Adam(learning_rate=1e-5), loss='binary_crossentropy')
Tune_Bert.fit([np.reshape(train_token_id,(7503,60)) , np.reshape(train_attention_id,(7503,60)) ], train.target, epochs=10,
batch_size=64, validation_split=0.20, shuffle = True, callbacks = [callb... | temp.loc[(train.Embarked.isnull()),'Embarked']='S' | Titanic - Machine Learning from Disaster |
7,258,897 | Tune_Bert.load_weights('best.hdf5')
Tune_answer = Tune_Bert.predict([np.reshape(test_token_id,(3263,60)) , np.reshape(test_attention_id,(3263,60)) ] )<create_dataframe> | temp.sort_values(['Ticket'], ascending = True)[35:45] | Titanic - Machine Learning from Disaster |
7,258,897 | answer_Emb = pd.DataFrame({'id': sample.id, 'target': np.where(Emb_Model_Answer>0.5,1,0 ).reshape(Emb_Model_Answer.shape[0])})
answer_tune = pd.DataFrame({'id': sample.id, 'target': np.where(Tune_answer>0.5,1,0 ).reshape(Tune_answer.shape[0])} )<save_to_csv> | temp.groupby('Initial' ).Survived.mean() | Titanic - Machine Learning from Disaster |
7,258,897 | answer_Emb.to_csv('submission_emb.csv', index = False)
answer_tune.to_csv('submission_tune.csv', index = False )<load_from_url> | temp['Initial'].replace(['Capt', 'Col', 'Countess', 'Don', 'Dona' , 'Dr', 'Jonkheer', 'Lady', 'Major', 'Master', 'Miss' ,'Mlle', 'Mme', 'Mr', 'Mrs', 'Ms', 'Rev', 'Sir'],[1, 2, 3, 4, 5, 6, 4, 3, 2, 8, 9, 3, 3, 4, 5, 3, 1, 3 ],inplace=True ) | Titanic - Machine Learning from Disaster |
7,258,897 | !wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py<import_modules> | temp.groupby('Initial' ).Survived.mean() | Titanic - Machine Learning from Disaster |
7,258,897 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
from wordcloud import WordCloud
from nltk.corpus import stopwords
from tqdm.notebook import tqdm
import tensorflow as tf
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import Adam
fr... | temp.groupby('Embarked' ).Survived.mean() | Titanic - Machine Learning from Disaster |
7,258,897 | pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
plt.style.use('fivethirtyeight' )<load_from_csv> | temp["Embarked"].replace(['C','Q', 'S'], [1,2,3], inplace =True ) | Titanic - Machine Learning from Disaster |
7,258,897 | train_data = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv")
test_data = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv" )<count_missing_values> | temp["Gender"].replace(['baby','m1', 'm2', 'old', 'w1', 'w2'], [1,2,3,4,5,6], inplace =True ) | Titanic - Machine Learning from Disaster |
7,258,897 | print("Shape of the training dataset: {}.".format(train_data.shape))
print("Shape of the testing dataset: {}".format(test_data.shape))
for col in train_data.columns:
nan_vals = train_data[col].isna().sum()
pcent =(train_data[col].isna().sum() / train_data[col].count())* 100
print("Total NaN values in column '{}' are: {... | df = pd.DataFrame() | Titanic - Machine Learning from Disaster |
7,258,897 | def bert_encode(texts, tokenizer, max_len=512):
all_tokens, all_masks, all_segments = [], [], []
for text in tqdm(texts):
text = tokenizer.tokenize(text)
text = text[:max_len-2]
input_sequence = ["[CLS]"] + text + ["[SEP]"]
pad_len = max_len - len(input_sequence)
tokens = tokenizer.convert_tokens_to_ids(input_sequenc... | df.isnull().sum() | Titanic - Machine Learning from Disaster |
7,258,897 | %%time
url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1"
bert_layer = hub.KerasLayer(url, trainable=True )<data_type_conversions> | score = df.copy() | Titanic - Machine Learning from Disaster |
7,258,897 | vocab_fl = bert_layer.resolved_object.vocab_file.asset_path.numpy()
lower_case = bert_layer.resolved_object.do_lower_case.numpy()
tokenizer = tokenization.FullTokenizer(vocab_fl, lower_case )<categorify> | score['Survived'] = temp['Survived'] | Titanic - Machine Learning from Disaster |
7,258,897 | %%time
train_input = bert_encode(train_data['text'].values, tokenizer, max_len=160)
test_input = bert_encode(test_data['text'].values, tokenizer, max_len=160)
train_labels = train_data['target'].values<choose_model_class> | score['Score'] = 0 | Titanic - Machine Learning from Disaster |
7,258,897 | def build_model(transformer, max_len=512):
input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name='input_word_ids')
input_mask = Input(shape=(max_len,), dtype=tf.int32, name='input_mask')
segment_ids = Input(shape=(max_len,), dtype=tf.int32, name='segment_ids')
_, seq_op = transformer([input_word_ids, input_m... | def see(a):
return score.groupby(a ).Survived.mean()
see('Pclass' ) | Titanic - Machine Learning from Disaster |
7,258,897 | model = build_model(bert_layer, max_len=160)
model.summary()<train_model> | score['Class'] = 0
score['CE'] = 0
score['CN'] = 0
score['CP'] = 0
for i in score:
score.loc[(( score.Embarked.values == 1)) ,'CE']=1
score.loc[(( score.Name.values == 2)) ,'CN']=1
score.loc[(( score.Name.values == 3)) ,'CN']=5
score.loc[(( score.Pclass.values == 1)) ,'Class']=1
score.loc[(( score.Pclass.values == 3)) ... | Titanic - Machine Learning from Disaster |
7,258,897 | checkpoint = ModelCheckpoint('model.h5', monitor='val_loss', save_best_only=True)
train_history = model.fit(
train_input, train_labels,
validation_split=0.1,
epochs=3,
callbacks=[checkpoint],
batch_size=16
)<predict_on_test> | score['Wealth'] = 0
score['WC'] = 0
score['WF'] = 0
score['WT'] = 0
for i in score:
score.loc[(( score.Cabin.values == 8)) ,'WC']=-5
score.loc[(( score.Cabin.values == 11)) ,'WC']=-1
score.loc[(( score.Cabin.values == 3)) ,'WC']=1
score.loc[(( score.Cabin.values == 6)) ,'WC']=1
score.loc[(( score.Cabin.values == 7)) ,'... | Titanic - Machine Learning from Disaster |
7,258,897 | preds = model.predict(test_input )<save_to_csv> | score['Priority'] = 0
score['PA'] = 0
score['PN'] = 0
score['PS'] = 0
for i in score:
score.loc[(( score.Age.values == 1)) ,'PA']=5
score.loc[(( score.Age.values == 13)) ,'PA']=1
score.loc[(( score.Age.values == 2)) ,'PA']=1
score.loc[(( score.Age.values == 31)) ,'PA']=-1
score.loc[(( score.Age.values == 7)) ,'PA']=1
s... | Titanic - Machine Learning from Disaster |
7,258,897 | sub_fl = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv")
sub_fl['target'] = preds.round().astype(int)
sub_fl.to_csv("submission.csv", index=False )<set_options> | score['Situation'] = 0
score['SA'] = 0
score['SF'] = 0
for i in score:
score.loc[(( score.Age.values == 36)) ,'SA']=1
score.loc[(( score.Family.values == 2)) ,'SF']=1
score.loc[(( score.Family.values == 3)) ,'SF']=1
score.loc[(( score.Family.values == 4)) ,'SF']=3
score['Situation'] = score['SA'] + score['SF']
score.he... | Titanic - Machine Learning from Disaster |
7,258,897 | warnings.filterwarnings('ignore' )<randomize_order> | score['Sacrificed'] = 0
score['SN'] = 0
score['FS'] = 0
for i in score:
score.loc[(( score.Name.values == 1)) ,'SN']=-5
score.loc[(( score.Family.values == 5)) ,'FS']=-1
score.loc[(( score.Family.values == 6)) ,'FS']=-3
score.loc[(( score.Family.values == 8)) ,'FS']=-5
score.loc[(( score.Family.values >= 9)) ,'FS']=-5
... | Titanic - Machine Learning from Disaster |
7,258,897 | def seed_everything(seed=0):
random.seed(seed)
np.random.seed(seed)
def df_parallelize_run(func, t_split):
num_cores = np.min([N_CORES,len(t_split)])
pool = Pool(num_cores)
df = pd.concat(pool.map(func, t_split), axis=1)
pool.close()
pool.join()
return df<categorify> | score['Score'] = score['Class'] + score['Wealth'] + score['Priority'] + score['Situation'] + score['Sacrificed'] | Titanic - Machine Learning from Disaster |
7,258,897 | def get_data_by_store(store):
df = pd.concat([pd.read_pickle(BASE),
pd.read_pickle(PRICE ).iloc[:,2:],
pd.read_pickle(CALENDAR ).iloc[:,2:]],
axis=1)
df = df[df['store_id']==store]
df2 = pd.read_pickle(MEAN_ENC)[mean_features]
df2 = df2[df2.index.isin(df.index)]
df3 = pd.read_pickle(LAGS ).iloc[:,3:]
df3 = df3[df3.ind... | df_new = pd.DataFrame() | Titanic - Machine Learning from Disaster |
7,258,897 | lgb_params = {
'boosting_type': 'gbdt',
'objective': 'tweedie',
'tweedie_variance_power': 1.1,
'metric': 'rmse',
'subsample': 0.5,
'subsample_freq': 1,
'learning_rate': 0.03,
'num_leaves': 2**11-1,
'min_data_in_leaf': 2**12-1,
'feature_fraction': 0.5,
'max_bin': 100,
'n_estimators': 1400,
'boost_from_average': False,
'... | df_enc = df_new.apply(LabelEncoder().fit_transform)
df_enc.head() | Titanic - Machine Learning from Disaster |
7,258,897 | VER = 1
SEED = 42
seed_everything(SEED)
lgb_params['seed'] = SEED
N_CORES = psutil.cpu_count()
TARGET = 'sales'
START_TRAIN = 0
END_TRAIN = 1913
P_HORIZON = 28
USE_AUX = True
remove_features = ['id','state_id','store_id',
'date','wm_yr_wk','d',TARGET]
mean_features = ['enc_cat_id_mean','enc_cat_id_std',
'enc_dept_id_m... | train = df_enc[:ntrain]
test = df_enc[ntrain:] | Titanic - Machine Learning from Disaster |
7,258,897 | if USE_AUX:
lgb_params['n_estimators'] = 2
<init_hyperparams> | X_test = test
X_train = train | Titanic - Machine Learning from Disaster |
7,258,897 | for store_id in STORES_IDS:
print('Train', store_id)
grid_df, features_columns = get_data_by_store(store_id)
train_mask = grid_df['d']<=END_TRAIN
valid_mask = train_mask&(grid_df['d']>(END_TRAIN-P_HORIZON))
preds_mask = grid_df['d']>(END_TRAIN-100)
train_data = lgb.Dataset(grid_df[train_mask][features_columns],
labe... | scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test ) | Titanic - Machine Learning from Disaster |
7,258,897 | all_preds = pd.DataFrame()
base_test = get_base_test()
main_time = time.time()
for PREDICT_DAY in range(1,29):
print('Predict | Day:', PREDICT_DAY)
start_time = time.time()
grid_df = base_test.copy()
grid_df = pd.concat([grid_df, df_parallelize_run(make_lag_roll, ROLS_SPLIT)], axis=1)
for store_id in STORES_IDS:
mode... | ran = RandomForestClassifier(random_state=1)
knn = KNeighborsClassifier()
log = LogisticRegression()
xgb = XGBClassifier()
gbc = GradientBoostingClassifier()
svc = SVC(probability=True)
ext = ExtraTreesClassifier()
ada = AdaBoostClassifier()
gnb = GaussianNB()
gpc = GaussianProcessClassifier()
bag = BaggingClassifier... | Titanic - Machine Learning from Disaster |
7,258,897 | submission = pd.read_csv(ORIGINAL+'sample_submission.csv')[['id']]
submission = submission.merge(all_preds, on=['id'], how='left' ).fillna(0)
submission.to_csv('submission_v'+str(VER)+'.csv', index=False )<set_options> | results = pd.DataFrame({
'Model': ['Random Forest', 'K Nearest Neighbour', 'Logistic Regression', 'XGBoost', 'Gradient Boosting', 'SVC', 'Extra Trees', 'AdaBoost', 'Gaussian Naive Bayes', 'Gaussian Process', 'Bagging Classifier'],
'Score': scores})
result_df = results.sort_values(by='Score', ascending=False ).reset_in... | Titanic - Machine Learning from Disaster |
7,258,897 | warnings.filterwarnings('ignore' )<randomize_order> | fi = {'Features':train.columns.tolist() , 'Importance':xgb.feature_importances_}
importance = pd.DataFrame(fi, index=None ).sort_values('Importance', ascending=False ) | Titanic - Machine Learning from Disaster |
7,258,897 | def seed_everything(seed=0):
random.seed(seed)
np.random.seed(seed)
def df_parallelize_run(func, t_split):
num_cores = np.min([N_CORES,len(t_split)])
pool = Pool(num_cores)
df = pd.concat(pool.map(func, t_split), axis=1)
pool.close()
pool.join()
return df<categorify> | fi = {'Features':train.columns.tolist() , 'Importance':np.transpose(log.coef_[0])}
importance = pd.DataFrame(fi, index=None ).sort_values('Importance', ascending=False ) | Titanic - Machine Learning from Disaster |
7,258,897 | def get_data_by_store(store):
df = pd.concat([pd.read_pickle(BASE),
pd.read_pickle(PRICE ).iloc[:,2:],
pd.read_pickle(CALENDAR ).iloc[:,2:]],
axis=1)
df = df[df['store_id']==store]
df2 = pd.read_pickle(MEAN_ENC)[mean_features]
df2 = df2[df2.index.isin(df.index)]
df3 = pd.read_pickle(LAGS ).iloc[:,3:]
df3 = df3[df3.ind... | gbc_imp = pd.DataFrame({'Feature':train.columns, 'gbc importance':gbc.feature_importances_})
xgb_imp = pd.DataFrame({'Feature':train.columns, 'xgb importance':xgb.feature_importances_})
ran_imp = pd.DataFrame({'Feature':train.columns, 'ran importance':ran.feature_importances_})
ext_imp = pd.DataFrame({'Feature':trai... | Titanic - Machine Learning from Disaster |
7,258,897 | lgb_params = {
'boosting_type': 'gbdt',
'objective': 'tweedie',
'tweedie_variance_power': 1.1,
'metric': 'rmse',
'subsample': 0.5,
'subsample_freq': 1,
'learning_rate': 0.02,
'num_leaves': 2**11-1,
'min_data_in_leaf': 2**12-1,
'feature_fraction': 0.5,
'max_bin': 100,
'n_estimators': 1300,
'early_stopping_rounds': 30,
'... | fi = {'Features':importances['Feature'], 'Importance':importances['Average']}
importance = pd.DataFrame(fi, index=None ).sort_values('Importance', ascending=False ) | Titanic - Machine Learning from Disaster |
7,258,897 | VER = 11
SEED = 41
seed_everything(SEED)
lgb_params['seed'] = SEED
N_CORES = psutil.cpu_count()
TARGET = 'sales'
START_TRAIN = 30
END_TRAIN = 1941
P_HORIZON = 28
USE_AUX = True
remove_features = ['id','state_id','store_id',
'date','wm_yr_wk','d',TARGET]
mean_features = ['enc_cat_id_mean','enc_cat_id_std',
'enc_dept_id... | train = train.drop(['Class', 'Pclass', 'Embarked'], axis=1)
test = test.drop(['Class', 'Pclass', 'Embarked'], axis=1)
X_train = train
X_test = test
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test ) | Titanic - Machine Learning from Disaster |
7,258,897 | gc.collect()<define_variables> | ran = RandomForestClassifier(random_state=1)
knn = KNeighborsClassifier()
log = LogisticRegression()
xgb = XGBClassifier(random_state=1)
gbc = GradientBoostingClassifier(random_state=1)
svc = SVC(probability=True)
ext = ExtraTreesClassifier(random_state=1)
ada = AdaBoostClassifier(random_state=1)
gnb = GaussianNB... | Titanic - Machine Learning from Disaster |
7,258,897 | for store_id in STORES_IDS:
print('Train', store_id)
grid_df, features_columns = get_data_by_store(store_id)
train_mask = grid_df['d']<=END_TRAIN
valid_mask = train_mask&(grid_df['d']>(END_TRAIN-P_HORIZON))
preds_mask = grid_df['d']>(END_TRAIN-100)
train_data = lgb.Dataset(grid_df[train_mask][features_columns],
labe... | Cs = [0.001, 0.01, 0.1, 1, 5, 10, 15, 20, 50, 100]
gammas = [0.001, 0.01, 0.1, 1]
hyperparams = {'C': Cs, 'gamma' : gammas}
gd=GridSearchCV(estimator = SVC(probability=True), param_grid = hyperparams,
verbose=True, cv=5, scoring = "accuracy")
gd.fit(X_train, y_train)
print(gd.best_score_)
print(gd.best_estimator_ ) | Titanic - Machine Learning from Disaster |
7,258,897 | all_preds = pd.DataFrame()
base_test = get_base_test()
main_time = time.time()
for PREDICT_DAY in range(1,29):
print('Predict | Day:', PREDICT_DAY)
start_time = time.time()
grid_df = base_test.copy()
grid_df = pd.concat([grid_df, df_parallelize_run(make_lag_roll, ROLS_SPLIT)], axis=1)
for store_id in STORES_IDS:
mode... | learning_rate = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]
n_estimators = [100, 250, 500, 750, 1000, 1250, 1500]
hyperparams = {'learning_rate': learning_rate, 'n_estimators': n_estimators}
gd=GridSearchCV(estimator = GradientBoostingClassifier() , param_grid = hyperparams,
verbose=True, cv=5, scoring = "accu... | Titanic - Machine Learning from Disaster |
7,258,897 | submission = pd.read_csv(ORIGINAL+'sample_submission.csv')[['id']]
submission = submission.merge(all_preds, on=['id'], how='left' ).fillna(0)
submission.to_csv('submission_v'+str(VER)+'.csv', index=False )<set_options> | penalty = ['l1', 'l2']
C = np.logspace(0, 4, 10)
hyperparams = {'penalty': penalty, 'C': C}
gd=GridSearchCV(estimator = LogisticRegression() , param_grid = hyperparams,
verbose=True, cv=5, scoring = "accuracy")
gd.fit(X_train, y_train)
print(gd.best_score_)
print(gd.best_estimator_ ) | Titanic - Machine Learning from Disaster |
7,258,897 | gc.collect()<set_options> | learning_rate = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]
n_estimators = [10, 25, 50, 75, 100, 250, 500, 750, 1000]
hyperparams = {'learning_rate': learning_rate, 'n_estimators': n_estimators}
gd=GridSearchCV(estimator = XGBClassifier() , param_grid = hyperparams,
verbose=True, cv=5, scoring = "accuracy")
g... | Titanic - Machine Learning from Disaster |
7,258,897 | !pip install.. /input/kaggle-efficientnet-repo/efficientnet-1.0.0-py3-none-any.whl
gc.enable()<categorify> | max_depth = [3, 4, 5, 6, 7, 8, 9, 10]
min_child_weight = [1, 2, 3, 4, 5, 6]
hyperparams = {'max_depth': max_depth, 'min_child_weight': min_child_weight}
gd=GridSearchCV(estimator = XGBClassifier(learning_rate=0.0001, n_estimators=10), param_grid = hyperparams,
verbose=True, cv=5, scoring = "accuracy")
gd.fit(X_train, ... | Titanic - Machine Learning from Disaster |
7,258,897 | sz = 256
N = 48
def tile(img):
result = []
shape = img.shape
pad0,pad1 =(sz - shape[0]%sz)%sz,(sz - shape[1]%sz)%sz
img = np.pad(img,[[pad0//2,pad0-pad0//2],[pad1//2,pad1-pad1//2],[0,0]],
constant_values=255)
img = img.reshape(img.shape[0]//sz,sz,img.shape[1]//sz,sz,3)
img = img.transpose(0,2,1,3,4 ).reshape(-1,sz,sz... | gamma = [i*0.1 for i in range(0,5)]
hyperparams = {'gamma': gamma}
gd=GridSearchCV(estimator = XGBClassifier(learning_rate=0.0001, n_estimators=10, max_depth=3,
min_child_weight=1), param_grid = hyperparams,
verbose=True, cv=5, scoring = "accuracy")
gd.fit(X_train, y_train)
print(gd.best_score_)
print(gd.best_estima... | Titanic - Machine Learning from Disaster |
7,258,897 | class ConvNet(tf.keras.Model):
def __init__(self, engine, input_shape, weights):
super(ConvNet, self ).__init__()
self.engine = engine(
include_top=False, input_shape=input_shape, weights=weights)
self.avg_pool2d = tf.keras.layers.GlobalAveragePooling2D()
self.dropout = tf.keras.layers.Dropout(0.5)
self.dense_1 = tf... | subsample = [0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1]
colsample_bytree = [0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1]
hyperparams = {'subsample': subsample, 'colsample_bytree': colsample_bytree}
gd=GridSearchCV(estimator = XGBClassifier(learning_rate=0.0001, n_estimators=10, max_depth=3,
min_child_weight=1, ga... | Titanic - Machine Learning from Disaster |
7,258,897 | is_ef = True
backbone_name = 'efficientnet-b0'
N_TILES = 42
IMG_SIZE = 256
if backbone_name.startswith('efficientnet'):
model_fn = getattr(efn, f'EfficientNetB{backbone_name[-1]}')
model = ConvNet(engine=model_fn, input_shape=(IMG_SIZE, IMG_SIZE, 3), weights=None)
dummy_data = tf.zeros(( 2 * N_TILES, IMG_SIZE, IMG_SI... | reg_alpha = [1e-5, 1e-2, 0.1, 1, 100]
hyperparams = {'reg_alpha': reg_alpha}
gd=GridSearchCV(estimator = XGBClassifier(learning_rate=0.0001, n_estimators=10, max_depth=3,
min_child_weight=1, gamma=0, subsample=0.6, colsample_bytree=0.9),
param_grid = hyperparams, verbose=True, cv=5, scoring = "accuracy")
gd.fit(X_trai... | Titanic - Machine Learning from Disaster |
7,258,897 | model.load_weights('.. /input/tpu-training-tensorflow-iafoos-method-42x256x256x3/efficientnet-b0.h5' )<load_from_csv> | n_restarts_optimizer = [0, 1, 2, 3]
max_iter_predict = [1, 2, 5, 10, 20, 35, 50, 100]
warm_start = [True, False]
hyperparams = {'n_restarts_optimizer': n_restarts_optimizer, 'max_iter_predict': max_iter_predict, 'warm_start': warm_start}
gd=GridSearchCV(estimator = GaussianProcessClassifier() , param_grid = hyperparams... | Titanic - Machine Learning from Disaster |
7,258,897 | TRAIN = '.. /input/prostate-cancer-grade-assessment/train_images/'
MASKS = '.. /input/prostate-cancer-grade-assessment/train_label_masks/'
BASE_PATH = '.. /input/prostate-cancer-grade-assessment/'
train = pd.read_csv(BASE_PATH + "train.csv")
train.head()<load_from_csv> | n_estimators = [10, 25, 50, 75, 100, 125, 150, 200]
learning_rate = [0.001, 0.01, 0.1, 0.5, 1, 1.5, 2]
hyperparams = {'n_estimators': n_estimators, 'learning_rate': learning_rate}
gd=GridSearchCV(estimator = AdaBoostClassifier() , param_grid = hyperparams,
verbose=True, cv=5, scoring = "accuracy")
gd.fit(X_train, y_tr... | Titanic - Machine Learning from Disaster |
7,258,897 | sub = pd.read_csv(".. /input/prostate-cancer-grade-assessment/sample_submission.csv")
sub.head()<load_from_csv> | n_neighbors = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20]
algorithm = ['auto']
weights = ['uniform', 'distance']
leaf_size = [1, 2, 3, 4, 5, 10, 15, 20, 25, 30]
hyperparams = {'algorithm': algorithm, 'weights': weights, 'leaf_size': leaf_size,
'n_neighbors': n_neighbors}
gd=GridSearchCV(estimator = KNeighborsCl... | Titanic - Machine Learning from Disaster |
7,258,897 | test = pd.read_csv(".. /input/prostate-cancer-grade-assessment/test.csv")
test.head()<define_variables> | n_estimators = [10, 25, 50, 75, 100]
max_depth = [3, None]
max_features = [1, 3, 5, 7]
min_samples_split = [2, 4, 6, 8, 10]
min_samples_leaf = [2, 4, 6, 8, 10]
hyperparams = {'n_estimators': n_estimators, 'max_depth': max_depth, 'max_features': max_features,
'min_samples_split': min_samples_split, 'min_samples_leaf': m... | Titanic - Machine Learning from Disaster |
7,258,897 | TEST = '.. /input/prostate-cancer-grade-assessment/test_images/'<define_variables> | n_estimators = [10, 25, 50, 75, 100]
max_depth = [3, None]
max_features = [1, 3, 5, 7]
min_samples_split = [2, 4, 6, 8, 10]
min_samples_leaf = [2, 4, 6, 8, 10]
hyperparams = {'n_estimators': n_estimators, 'max_depth': max_depth, 'max_features': max_features,
'min_samples_split': min_samples_split, 'min_samples_leaf': m... | Titanic - Machine Learning from Disaster |
7,258,897 | PRED_PATH = TEST
df = sub
t_df = test<concatenate> | n_estimators = [10, 15, 20, 25, 50, 75, 100, 150]
max_samples = [1, 2, 3, 5, 7, 10, 15, 20, 25, 30, 50]
max_features = [1, 3, 5, 7]
hyperparams = {'n_estimators': n_estimators, 'max_samples': max_samples, 'max_features': max_features}
gd=GridSearchCV(estimator = BaggingClassifier() , param_grid = hyperparams,
verbose=T... | Titanic - Machine Learning from Disaster |
7,258,897 | transforms = albumentations.Compose([
albumentations.Transpose(p=0.5),
albumentations.VerticalFlip(p=0.5),
albumentations.HorizontalFlip(p=0.5),
] )<categorify> | ran = RandomForestClassifier(n_estimators=25,
max_depth=3,
max_features=3,
min_samples_leaf=2,
min_samples_split=8,
random_state=1)
knn = KNeighborsClassifier(algorithm='auto',
leaf_size=1,
n_neighbors=5,
weights='uniform')
log = LogisticRegression(C=2.7825594022071245,
penalty='l2')
xgb = XGBClassifier(learning_rat... | 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.