kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
2,547,283 | def _get_masks(tokens, max_seq_length):
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq length!")
return [1]*len(tokens)+ [0] *(max_seq_length - len(tokens))
def _get_segments(tokens, max_seq_length):
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq le... | train['Cabin'].value_counts().sort_index() | Titanic - Machine Learning from Disaster |
2,547,283 | def compute_spearmanr(trues, preds):
rhos = []
for col_trues, col_pred in zip(trues.T, preds.T):
rhos.append(
spearmanr(col_trues, col_pred + np.random.normal(0, 1e-7, col_pred.shape[0])).correlation)
return np.mean(rhos)
class CustomCallback(tf.keras.callbacks.Callback):
def __init__(self, valid_data, test_data, ba... | for dataset in train_test_data:
dataset['Cabin'] = dataset['Cabin'].str[:1] | Titanic - Machine Learning from Disaster |
2,547,283 | length =(np.linspace(1, 229, num=1))<import_modules> | train.loc[(train['Cabin'].isnull())&(train['Pclass']==1), 'Cabin'] = 'E'
train.loc[(train['Cabin'].isnull())&(train['Pclass']==2), 'Cabin'] = 'D'
train.loc[(train['Cabin'].isnull())&(train['Pclass']==3), 'Cabin'] = 'F'
test.loc[(test['Cabin'].isnull())&(test['Pclass']==1), 'Cabin'] = 'E'
test.loc[(test['Cabin'].isnull(... | Titanic - Machine Learning from Disaster |
2,547,283 | class TextDataset(data.Dataset):
def __init__(self, text, lens, y=None):
self.text = text
self.lens = lens
self.y = y
def __len__(self):
return len(self.lens)
def __getitem__(self, idx):
if self.y is None:
return self.text[idx], self.lens[idx]
return self.text[idx], self.lens[idx], self.y[idx]
class Collator(object):
... | cabin_mapping = {"B": 0, "C": 1 , "A": 2, "T": 3, "E": 4, "D": 5, "F": 6, "G": 7}
for dataset in train_test_data:
dataset['Cabin'] = dataset['Cabin'].map(cabin_mapping ) | Titanic - Machine Learning from Disaster |
2,547,283 | train_collator = SequenceBucketCollator(lambda lengths: lengths.max() ,
sequence_index=0,
length_index=1,
label_index=2)
test_collator = SequenceBucketCollator(lambda lengths: lengths.max() , sequence_index=0, length_index=1)
valid_dataset = data.Subset(train, indices=[0, 1])
train_loader = data.DataLoader(train, ba... | features_drop = ['Ticket', 'SibSp', 'Parch', 'Age_bin', 'Fare_bin']
train = train.drop(features_drop, axis=1)
test = test.drop(features_drop, axis=1 ) | Titanic - Machine Learning from Disaster |
2,547,283 | def compute_spearmanr(trues, preds):
rhos = []
for col_trues, col_pred in zip(trues.T, preds.T):
rhos.append(
spearmanr(col_trues, col_pred + np.random.normal(0, 1e-7, col_pred.shape[0])).correlation)
return np.mean(rhos)
class CustomCallback(tf.keras.callbacks.Callback):
def __init__(self, valid_data, test_data, ba... | train.to_csv('train.csv', index=False)
test.to_csv('test.csv', index=False ) | Titanic - Machine Learning from Disaster |
2,547,283 | test_predictions = [histories[i].test_predictions for i in range(len(histories)) ]
test_predictions = [np.average(test_predictions[i], axis=0)for i in range(len(test_predictions)) ]
test_predictions = np.mean(test_predictions, axis=0)
df_sub.iloc[:, 1:] = test_predictions
df_sub.to_csv('submission.csv', index=False )<... | train['Age'] = train['Age'].astype(int)
test['Age'] = test['Age'].astype(int)
train['Fare'] = train['Fare'].astype(int)
test['Fare'] = test['Fare'].astype(int ) | Titanic - Machine Learning from Disaster |
2,547,283 | ROOT = '.. /input/google-quest-challenge/'
test_df = pd.read_csv(ROOT+'test.csv')
train_df = pd.read_csv(ROOT+'train.csv' )<define_variables> | from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
import numpy as np | Titanic - Machine Learning from Disaster |
2,547,283 | target_cols = ['question_asker_intent_understanding', 'question_body_critical',
'question_conversational', 'question_expect_short_answer',
'question_fact_seeking', 'question_has_commonly_accepted_answer',
'question_interestingness_others', 'question_interestingness_self',
'question_multi_intent', 'question_not_really_a... | np.random.seed(42)
print('tensorflow version : ', tf.__version__)
print('keras version : ', keras.__version__ ) | Titanic - Machine Learning from Disaster |
2,547,283 | import torch
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
from torch.utils.data import RandomSampler, SequentialSampler
from pytorch_transformers import BertTokenizer
from sklearn.preprocessing import MinMaxScaler<load_pretrained> | train = train.drop(['PassengerId'], axis=1 ) | Titanic - Machine Learning from Disaster |
2,547,283 | def read_data(raw_data_path):
test = pd.read_csv(raw_data_path, encoding='utf-8')
targets = [-1] * len(test)
sentence_a = test['question_title'] + test['question_body']
sentence_b = test['answer']
return targets, sentence_a, sentence_b
def save_pickle(data, file_path):
if isinstance(file_path, Path):
file_path = st... | x_data = train.values[:, 1:]
y_data = train.values[:, 0]
X_train, X_val, y_train, y_val = train_test_split(x_data, y_data, test_size = 0.3, random_state = 42 ) | Titanic - Machine Learning from Disaster |
2,547,283 | data = []
for step,(data_x_a, data_x_b, data_y)in enumerate(zip(X_a, X_b, y)) :
data.append(( [data_x_a, data_x_b], data_y))<load_pretrained> | model = Sequential()
model.add(Dense(255, input_shape=(8,), activation = 'relu'))
model.add(Dense(( 1), activation = 'sigmoid'))
model.compile(loss='mse', optimizer='Adam', metrics = ['accuracy'])
model.summary() | Titanic - Machine Learning from Disaster |
2,547,283 | tokenizer = BertTokenizer("/kaggle/input/bertpretrained/uncased_L-24_H-1024_A-16/uncased_L-24_H-1024_A-16/vocab.txt", True )<categorify> | hist = model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=100 ) | Titanic - Machine Learning from Disaster |
2,547,283 | class InputExample(object):
def __init__(self, guid, text_a, text_b=None, label=None):
self.guid = guid
self.text_a = text_a
self.text_b = text_b
self.label = label
class InputFeature(object):
def __init__(self, input_ids, input_mask, segment_ids, label_id, input_len):
self.input_ids = input_ids
self.input_mask = i... | k_fold = KFold(n_splits=10, shuffle=True, random_state=0 ) | Titanic - Machine Learning from Disaster |
2,547,283 | test_examples = create_examples(data, 'test')
test_features = create_features(test_examples )<create_dataframe> | clf = KNeighborsClassifier(n_neighbors = 13)
scoring = 'accuracy'
score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
2,547,283 | def create_dataset(features, is_sorted=False):
if is_sorted:
logger.info("sorted data by th length of input")
features = sorted(features, key=lambda x: x.input_len, reverse=True)
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in featu... | round(np.mean(score)*100, 2 ) | Titanic - Machine Learning from Disaster |
2,547,283 | test_dataset = create_dataset(test_features)
test_sampler = SequentialSampler(test_dataset)
test_dataloader = DataLoader(test_dataset,sampler=test_sampler,batch_size=32 )<choose_model_class> | clf = DecisionTreeClassifier()
scoring = 'accuracy'
score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
2,547,283 | class BertForMultiClass(BertPreTrainedModel):
def __init__(self, config):
super(BertForMultiClass, self ).__init__(config)
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
self.apply(self.init_weights)
def forward... | round(np.mean(score)*100, 2 ) | Titanic - Machine Learning from Disaster |
2,547,283 | def prepare_device(use_gpu=0):
n_gpu_use = [int(x)for x in use_gpu.split(",")]
if not use_gpu:
device_type = 'cpu'
else:
device_type = f"cuda:{n_gpu_use[0]}"
n_gpu = torch.cuda.device_count()
if len(n_gpu_use)> 0 and n_gpu == 0:
device_type = 'cpu'
if len(n_gpu_use)> n_gpu:
msg = f"Warning: The number of GPU's config... | clf = RandomForestClassifier(n_estimators=13)
scoring = 'accuracy'
score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
2,547,283 | model1 = BertForMultiClass.from_pretrained("/kaggle/input/bert-fold1-new/", num_labels=30)
model2 = BertForMultiClass.from_pretrained("/kaggle/input/bert-fold2/", num_labels=30)
model3 = BertForMultiClass.from_pretrained("/kaggle/input/bert-fold3-new/", num_labels=30)
model4 = BertForMultiClass.from_pretrained("/kag... | round(np.mean(score)*100, 2 ) | Titanic - Machine Learning from Disaster |
2,547,283 | test_predictions = np.average(result[0], axis=0 )<define_variables> | clf = GaussianNB()
scoring = 'accuracy'
score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
2,547,283 | n=test_df['url'].apply(lambda x:('english.stackexchange.com' in x)).tolist()
spelling=[]
for x in n:
if x:
spelling.append(0.5)
else:
spelling.append(0.)<feature_engineering> | round(np.mean(score)*100, 2 ) | Titanic - Machine Learning from Disaster |
2,547,283 | test_preds = test_predictions
y_train = train_df[target_cols].values
for column_ind in range(30):
curr_column = y_train[:, column_ind]
values = np.unique(curr_column)
map_quantiles = []
for val in values:
occurrence = np.mean(curr_column == val)
cummulative = sum(el['occurrence'] for el in map_quantiles)
map_quantil... | clf = SVC(C=10)
scoring = 'accuracy'
score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
2,547,283 | submission_df = pd.read_csv(ROOT+'sample_submission.csv')
submission_df[target_cols] = test_preds
submission_df['question_type_spelling']=spelling
submission_df['answer_relevance'] = submission_df['answer_relevance'].apply(lambda x : 0.33333334326744 if x < 0.7 else x)
submission_df<save_to_csv> | round(np.mean(score)*100,2 ) | Titanic - Machine Learning from Disaster |
2,547,283 | sub_file_name = 'submission.csv'
submission_df.to_csv(sub_file_name, index=False)
<install_modules> | model.fit(train_data, target)
test_data = test.drop("PassengerId", axis=1 ).copy()
prediction = model.predict(test_data ) | Titanic - Machine Learning from Disaster |
2,547,283 | !pip install -q.. /input/tensorflow-determinism
!pip install -q.. /input/huggingfacetokenizers/tokenizers-0.0.11-cp36-cp36m-manylinux1_x86_64.whl
!pip uninstall --yes pytorch-transformers
!pip install -q.. /input/huggingface-transformers-master<set_options> | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": prediction
})
submission.to_csv('submission.csv', index=False ) | Titanic - Machine Learning from Disaster |
7,868,253 | os.environ['TF_DETERMINISTIC_OPS'] = '1'
gc.enable()
np.set_printoptions(suppress=True)
print('Tensorflow version', tf.__version__)
print('PyTorch version', torch.__version__)
print('Transformers version',
transformers.__version__ )<set_options> | path = '/kaggle/input/titanic/'
traindf = pd.read_csv(path + 'train.csv')
testdf = pd.read_csv(path + 'test.csv')
submission = pd.read_csv(path + 'gender_submission.csv' ) | Titanic - Machine Learning from Disaster |
7,868,253 | gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
tf.config.experimental.set_visible_devices(gpus[0], 'GPU')
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
except RuntimeError as e:
print(e)
<define_variab... | import catboost
from catboost import CatBoostClassifier, Pool
from sklearn.model_selection import train_test_split | Titanic - Machine Learning from Disaster |
7,868,253 | rand_seed = 20201120
n_splits = 5
BERT_PATH = ".. /input/"
dataset_folder = Path(".. /input/google-quest-challenge")
MODEL_PATH_list = [
".. /input/tf-roberta-base-exp-v7/",
".. /input/bert-base-uncased-exp-v4/",
".. /input/tf-bert-base-cased-exp-v4/",
".. /input/tf-roberta-base-exp-v4/",
".. /input/xlnet-base-cased-e... | testdf['Title'] = testdf.Name.apply(lambda name: name.split(',')[1].split('.')[0].strip())
traindf['Title'] = traindf.Name.apply(lambda name: name.split(',')[1].split('.')[0].strip())
| Titanic - Machine Learning from Disaster |
7,868,253 | for i, p in enumerate(MODEL_PATH_list):
prefix = model_filename_prefix_list[i]
for f in os.listdir(p):
if f != "dataset-metadata.json":
print(p+f)
assert prefix in f<load_from_csv> | testdf['Title'].value_counts() | Titanic - Machine Learning from Disaster |
7,868,253 | df_train = pd.read_csv(dataset_folder / 'train.csv')
df_test = pd.read_csv(dataset_folder / 'test.csv')
df_sub = pd.read_csv(dataset_folder / 'sample_submission.csv')
print('Train shape:', df_train.shape)
print('Test shape:', df_test.shape )<feature_engineering> | traindf = traindf[['PassengerId', 'Title', 'Pclass','Sex', 'Fare', 'Age', 'Survived']]
testdf = testdf[['PassengerId', 'Title', 'Pclass','Sex', 'Age', 'Fare']] | Titanic - Machine Learning from Disaster |
7,868,253 | def extract_netloc(x):
tokens = x.split(".")
if len(tokens)> 3:
print(x)
return ".".join(tokens[:2])
else:
return tokens[0]
df_train['netloc'] = df_train['host'].apply(lambda x: x.split(".")[0])
df_test['netloc'] = df_test['host'].apply(lambda x: x.split(".")[0] )<set_options> | X = traindf.drop('Survived', axis = 1)
y = traindf['Survived']
| Titanic - Machine Learning from Disaster |
7,868,253 | def set_all_seeds(rand_seed):
np.random.seed(rand_seed)
random.seed(rand_seed)
os.environ['PYTHONHASHSEED'] = str(rand_seed)
tf.random.set_seed(rand_seed)
torch.manual_seed(rand_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False<set_options> | cat_features_index = np.where(X.dtypes != float)[0] | Titanic - Machine Learning from Disaster |
7,868,253 | set_all_seeds(rand_seed )<categorify> | X_train, X_val, y_train, y_val = train_test_split(X, y, test_size =.25, random_state = 42 ) | Titanic - Machine Learning from Disaster |
7,868,253 | def _convert_to_transformer_inputs(title, question, answer, tokenizer,
max_sequence_length):
def return_id(str1, str2, truncation_strategy, length):
inputs = tokenizer.encode_plus(str1,
str2,
add_special_tokens=True,
max_length=length,
truncation_strategy=truncation_strategy)
input_ids = inputs["input_ids"]
input_ma... | model = CatBoostClassifier(
iterations = 50000,
task_type = 'GPU',
learning_rate =.001,
early_stopping_rounds = 1000,
depth = 10,
loss_function = 'CrossEntropy',
eval_metric = 'BalancedAccuracy' ) | Titanic - Machine Learning from Disaster |
7,868,253 | def compute_input_arrays(df, columns, tokenizer, max_sequence_length):
input_ids_q, input_masks_q, input_segments_q = [], [], []
input_ids_a, input_masks_a, input_segments_a = [], [], []
for _, instance in tqdm(df[columns].iterrows()):
t, q, a = instance.question_title, instance.question_body, instance.answer
ids_q, ma... | model.fit(X_train, y_train, cat_features = cat_features_index, eval_set =(X_val, y_val), plot = True ) | Titanic - Machine Learning from Disaster |
7,868,253 | def compute_spearmanr_ignore_nan(trues, preds):
rhos = []
for tcol, pcol in zip(np.transpose(trues), np.transpose(preds)) :
rhos.append(spearmanr(tcol, pcol ).correlation)
return np.nanmean(rhos)
def compute_spearmanr(trues, preds):
rhos = []
for tcol, pcol in zip(np.transpose(trues), np.transpose(preds)) :
rhos.appe... | submission['PassengerId'] = testdf['PassengerId']
submission['Survived'] = model.predict(testdf, prediction_type='Class')
submission['Survived'] = submission['Survived'].astype(int)
submission.to_csv('submission.csv', index = False ) | Titanic - Machine Learning from Disaster |
7,868,253 | class SpearmanMonitorCallback(tf.keras.callbacks.Callback):
def __init__(self, valid_data, batch_size=16, fold=None):
self.valid_inputs = valid_data[0]
self.valid_outputs = valid_data[1]
self.batch_size = batch_size
self.fold = fold
def on_train_begin(self, logs={}):
self.valid_predictions = []
def on_epoch_end(self, e... | model.predict(testdf ) | Titanic - Machine Learning from Disaster |
6,087,367 | def create_model(pretrained_model_name):
q_id = tf.keras.layers.Input(( MAX_SEQUENCE_LENGTH,), dtype=tf.int32)
a_id = tf.keras.layers.Input(( MAX_SEQUENCE_LENGTH,), dtype=tf.int32)
q_mask = tf.keras.layers.Input(( MAX_SEQUENCE_LENGTH,), dtype=tf.int32)
a_mask = tf.keras.layers.Input(( MAX_SEQUENCE_LENGTH,), dtype=tf... | train = pd.read_csv(".. /input/train.csv")
test = pd.read_csv(".. /input/test.csv")
print("Train shape: ",train.shape)
print("Test shape: ",test.shape ) | Titanic - Machine Learning from Disaster |
6,087,367 | def create_model_cate_embed(pretrained_model_name, embed_info):
q_id = tf.keras.layers.Input(( MAX_SEQUENCE_LENGTH,), dtype=tf.int32)
a_id = tf.keras.layers.Input(( MAX_SEQUENCE_LENGTH,), dtype=tf.int32)
q_mask = tf.keras.layers.Input(( MAX_SEQUENCE_LENGTH,), dtype=tf.int32)
a_mask = tf.keras.layers.Input(( MAX_SEQU... | train.isnull().sum() | Titanic - Machine Learning from Disaster |
6,087,367 | set_all_seeds(rand_seed)
gkf = GroupKFold(n_splits=n_splits ).split(X=df_train.question_body,
groups=df_train.question_body)
gkf = list(gkf)
len(gkf )<categorify> | test.isnull().sum() | Titanic - Machine Learning from Disaster |
6,087,367 | outputs = compute_output_arrays(df_train, output_categories )<categorify> | datostotales = [train, test] | Titanic - Machine Learning from Disaster |
6,087,367 | def optimize_ranks(preds, unique_labels):
new_preds = np.zeros(preds.shape)
for i in range(preds.shape[1]):
interpolate_bins = np.digitize(preds[:, i],
bins=unique_labels,
right=False)
if len(np.unique(interpolate_bins)) == 1:
new_preds[:, i] = preds[:, i]
else:
new_preds[:, i] = unique_labels[interpolate_bins]
retur... | for datatotal in datostotales:
datatotal['Title'] = datatotal['Name'].str.extract('([A-Za-z]+)\.', expand=False ) | Titanic - Machine Learning from Disaster |
6,087,367 | y_labels = df_train[output_categories].copy()
y_labels = y_labels.values.flatten()
unique_labels = np.array(sorted(np.unique(y_labels)))
unique_labels<define_variables> | title_mapping = {"Mr": 0, "Miss": 1, "Mrs": 2,
"Master": 3, "Dr": 3, "Rev": 3, "Col": 3, "Major": 3, "Mlle": 3,"Countess": 3,
"Ms": 3, "Lady": 3, "Jonkheer": 3, "Don": 3, "Dona" : 3, "Mme": 3,"Capt": 3,"Sir": 3 }
for datatotal in datostotales:
datatotal['Title'] = datatotal['Title'].map(title_mapping ) | Titanic - Machine Learning from Disaster |
6,087,367 | denominator = 60
q = np.arange(0, 101, 100 / denominator)
exp_labels = np.percentile(unique_labels, q)
exp_labels<define_variables> | train.drop('Name', axis=1, inplace=True)
test.drop('Name', axis=1, inplace=True ) | Titanic - Machine Learning from Disaster |
6,087,367 | infer_start_time = time.time()
all_test_preds = []
all_val_preds = []
all_val_scores = []
all_magic_val_scores = []
gc.collect()
for k, MODEL_PATH in enumerate(MODEL_PATH_list):
pretrained_model_name, is_tf, infer_batch_size, cate_embed_mode = pretrained_model_metadata[k]
model_filename_prefix = model_filename_prefix_l... | sex_mapping = {"male": 0, "female": 1}
for datatotal in datostotales:
datatotal['Sex'] = datatotal['Sex'].map(sex_mapping ) | Titanic - Machine Learning from Disaster |
6,087,367 | print(f"Mean Validation Score: {np.mean(all_val_scores):.6f}")
print(f"Mean Magic Validation Score: {np.mean(all_magic_val_scores):.6f}" )<compute_test_metric> | train["Age"].fillna(train.groupby("Title")["Age"].transform("median"), inplace=True)
test["Age"].fillna(test.groupby("Title")["Age"].transform("median"), inplace=True ) | Titanic - Machine Learning from Disaster |
6,087,367 |
<predict_on_test> | for datatotal in datostotales:
datatotal.loc[ datatotal['Age'] <= 15, 'Age'] = 0,
datatotal.loc[(datatotal['Age'] > 15)&(datatotal['Age'] <= 35), 'Age'] = 1,
datatotal.loc[(datatotal['Age'] > 35)&(datatotal['Age'] <= 55), 'Age'] = 2,
datatotal.loc[(datatotal['Age'] > 55)&(datatotal['Age'] <= 69), 'Age'] = 3,
datatotal.... | Titanic - Machine Learning from Disaster |
6,087,367 | def val_ensemble_preds(all_val_preds, weights):
oof_preds = np.zeros(outputs.shape)
for i, model_preds in enumerate(all_val_preds):
for j,(train_idx, valid_idx)in enumerate(gkf):
tmp = np.vstack(model_preds[j])
oof_preds[valid_idx] += tmp * weights[i]
oof_preds /= np.sum(weights)
return oof_preds<load_pretrained> | Pclass1 = train[train['Pclass']==1]['Embarked'].value_counts()
Pclass2 = train[train['Pclass']==2]['Embarked'].value_counts()
Pclass3 = train[train['Pclass']==3]['Embarked'].value_counts()
df = pd.DataFrame([Pclass1, Pclass2, Pclass3])
df.index = ['1st class','2nd class', '3rd class']
df.plot(kind='bar',stacked=True, ... | Titanic - Machine Learning from Disaster |
6,087,367 | with open('ensemble-models-v4-v7.pickle', 'wb')as handle:
pickle.dump(all_val_preds, handle, protocol=pickle.HIGHEST_PROTOCOL )<find_best_params> | for datatotal in datostotales:
datatotal['Embarked'] = datatotal['Embarked'].fillna('Q' ) | Titanic - Machine Learning from Disaster |
6,087,367 | weights = [1.0, 1.0, 1.0, 1.0, 1.0]
oof_preds = val_ensemble_preds(all_val_preds, weights)
magic_preds = optimize_ranks(oof_preds, exp_labels)
blend_score = compute_spearmanr(outputs, magic_preds)
print(weights, blend_score)
weights = [2.0, 1.0, 1.0, 1.0, 2.0]
oof_preds = val_ensemble_preds(all_val_preds, weights)
... | embarked_mapping = {"S": 0, "C": 1, "Q": 2}
for datatotal in datostotales:
datatotal['Embarked'] = datatotal['Embarked'].map(embarked_mapping ) | Titanic - Machine Learning from Disaster |
6,087,367 | submit_preds = [np.average(x, axis=0)for x in all_test_preds]<define_search_space> | train["Fare"].fillna(train.groupby("Pclass")["Fare"].transform("median"), inplace=True)
test["Fare"].fillna(test.groupby("Pclass")["Fare"].transform("median"), inplace=True ) | Titanic - Machine Learning from Disaster |
6,087,367 | submit_preds = np.average(submit_preds, weights = [2.0, 1.0, 1.0, 1.0, 1.5],
axis=0 )<compute_test_metric> | for datatotal in datostotales:
datatotal.loc[(datatotal['Fare'] <= 30), 'Fare'] = 0,
datatotal.loc[(datatotal['Fare'] > 30)&(datatotal['Fare'] <= 100), 'Fare'] = 1,
datatotal.loc[(datatotal['Fare'] > 30)&(datatotal['Fare'] <= 100), 'Fare'] = 2,
datatotal.loc[(datatotal['Fare'] > 100), 'Fare'] = 3 | Titanic - Machine Learning from Disaster |
6,087,367 | submit_preds = optimize_ranks(submit_preds, exp_labels )<save_to_csv> | train.Cabin.value_counts() | Titanic - Machine Learning from Disaster |
6,087,367 | df_sub.iloc[:, 1:] = submit_preds
df_sub.to_csv('submission.csv', index=False )<install_modules> | for datatotal in datostotales:
datatotal['Cabin'] = datatotal['Cabin'].str[:1] | Titanic - Machine Learning from Disaster |
6,087,367 | !pip install.. /input/huggingface-transformers/sacremoses-master/sacremoses-master
!pip install.. /input/huggingface-transformers/transformers-master/transformers-master<set_options> | cabin_mapping = {"A": 0, "B": 0.4, "C": 0.8, "D": 1.2, "E": 1.6, "F": 2, "G": 2.4, "T": 2.8}
for datatotal in datostotales:
datatotal['Cabin'] = datatotal['Cabin'].map(cabin_mapping ) | Titanic - Machine Learning from Disaster |
6,087,367 | tqdm.pandas()
warnings.filterwarnings('ignore')
<load_from_csv> | train["Cabin"].fillna(train.groupby("Pclass")["Cabin"].transform("median"), inplace=True)
test["Cabin"].fillna(test.groupby("Pclass")["Cabin"].transform("median"), inplace=True ) | Titanic - Machine Learning from Disaster |
6,087,367 | PATH = '.. /input/google-quest-challenge/'
BERT_PATH = '.. /input/bert-base-from-tfhub/bert_en_uncased_L-12_H-768_A-12'
tokenizer_google_qa = tokenization.FullTokenizer(BERT_PATH+'/assets/vocab.txt', True)
tokenizer2 = BertTokenizer.from_pretrained(BERT_PATH+'/assets/vocab.txt', do_lower_case=True,)
MAX_SEQUENCE_LENG... | train["FamilySize"] = train["SibSp"] + train["Parch"] + 1
test["FamilySize"] = test["SibSp"] + test["Parch"] + 1 | Titanic - Machine Learning from Disaster |
6,087,367 | tree_tokenizer = TreebankWordTokenizer()
def get_tree_tokens(x):
x = tree_tokenizer.tokenize(x)
x = ' '.join(x)
return x<feature_engineering> | family_size = {1: 0, 2: 0.4, 3: 0.8, 4: 1.2, 5: 1.6, 6: 2, 7: 2.4, 8: 2.8, 9: 3.2, 10: 3.6, 11: 4}
for datatotal in datostotales:
datatotal['FamilySize'] = datatotal['FamilySize'].map(family_size ) | Titanic - Machine Learning from Disaster |
6,087,367 | for col in input_categories:
df_train[f'treated_{col}'] = df_train[col].progress_apply(lambda x: get_tree_tokens(x))
df_test[f'treated_{col}'] = df_test[col].progress_apply(lambda x: get_tree_tokens(x))
df[f'treated_{col}'] = df[col].progress_apply(lambda x: get_tree_tokens(x))<choose_model_class> | features_drop = ['Ticket', 'SibSp', 'Parch']
train = train.drop(features_drop, axis=1)
test = test.drop(features_drop, axis=1)
train = train.drop(['PassengerId'], axis=1 ) | Titanic - Machine Learning from Disaster |
6,087,367 | tokenizer = text.Tokenizer(lower=False )<prepare_x_and_y> | train_dfX = train.drop('Survived', axis=1)
train_dfY = train['Survived']
submission = test[['PassengerId']].copy()
test_df = test.drop(['PassengerId'], axis=1 ) | Titanic - Machine Learning from Disaster |
6,087,367 | X_train_question = df_train['question_body']
X_train_title = df_train['question_title']
X_train_answer = df_train['answer']
X_test_question = df_test['question_body']
X_test_title = df_test['question_title']
X_test_answer = df_test['answer']<train_model> | categorical = ['Embarked', 'Title', 'Pclass', 'Fare']
for var in categorical:
train_dfX = pd.concat([train_dfX, pd.get_dummies(train_dfX[var], prefix=var)], axis=1)
del train_dfX[var] | Titanic - Machine Learning from Disaster |
6,087,367 | tokenizer.fit_on_texts(list(X_train_title)+list(X_train_question)+list(X_train_answer)+list(X_test_title)+list(X_test_question)+list(X_test_answer))<choose_model_class> | categorical = ['Embarked', 'Title', 'Pclass', 'Fare']
for var in categorical:
test_df = pd.concat([test_df, pd.get_dummies(test_df[var], prefix=var)], axis=1)
del test_df[var] | Titanic - Machine Learning from Disaster |
6,087,367 | nlp = English()
sentencizer = nlp.create_pipe('sentencizer')
nlp.add_pipe(sentencizer )<string_transform> | sc = StandardScaler()
train_dfX = sc.fit_transform(train_dfX)
test_df = sc.transform(test_df)
print("Test shape : ",test_df.shape ) | Titanic - Machine Learning from Disaster |
6,087,367 | def split_document(texts):
all_sents = []
max_num_sentences = 0.0
for text in texts:
doc = nlp(text)
sents=[]
for i,sent in enumerate(doc.sents):
sents.append(sent.text)
all_sents.append(sents)
return all_sents
X_train_question = split_document(X_train_question)
X_train_answer = split_document(X_train_answer)
X_te... | train_dfX,val_dfX,train_dfY, val_dfY = train_test_split(train_dfX,train_dfY , test_size=0.10, stratify=train_dfY)
print("Tamaño set de Entrenamiento: ",train_dfX.shape)
print("Tamaño set de Validacion : ",val_dfX.shape ) | Titanic - Machine Learning from Disaster |
6,087,367 | def add_question_metadata_features(text):
doc=nlp(text)
indirect = 0
choice_words=0
reason_explanation_words = 0
question_count = 0
for sent in doc.sents:
if '?' in sent.text and '?' == sent.text[-1]:
question_count += 1
for token in sent:
if token.text.lower() =='why':
reason_explanation_words+=1
elif token.text.lowe... | def func_model() :
inp = Input(shape=(17,))
x=Dropout(0.1 )(inp)
x=Dense(350, activation="relu", kernel_regularizer=regularizers.l2(0.01))(inp)
x=Dropout(0.50 )(x)
x=Dense(350, activation="relu", kernel_regularizer=regularizers.l2(0.01))(x)
x=Dropout(0.50 )(x)
x=Dense(350, activation="relu", kernel_regularizer=reg... | Titanic - Machine Learning from Disaster |
6,087,367 | ans_user_and_category=df_train[df_train[['answer_user_name', 'category']].duplicated() ][['answer_user_name', 'category']].values
ans_user_and_category.shape<string_transform> | train_history = model.fit(train_dfX, train_dfY, batch_size=64, epochs=epochs, validation_data=(val_dfX, val_dfY)) | Titanic - Machine Learning from Disaster |
6,087,367 | def question_answer_author_same(df):
q_username = df['question_user_name']
a_username = df['answer_user_name']
author_same=[]
for i in range(len(df)) :
if q_username[i] == a_username[i]:
author_same.append(int(1))
else:
author_same.append(int(0))
return author_same
<feature_engineering> | print("Tiempo de ejecución %s segundos" %(time.time() - start_time)) | Titanic - Machine Learning from Disaster |
6,087,367 | def add_external_features(df):
df['question_body'] = df['question_body'].progress_apply(lambda x: str(x))
df['question_body_num_words'] = df['question_body'].str.count('\S+')
df['answer'] = df['answer'].progress_apply(lambda x: str(x))
df['answer_num_words'] = df['answer'].str.count('\S+')
df['question_vs_answer_leng... | y_test = model.predict(test_df)
submission['Survived'] = np.rint(y_test ).astype(int)
print(submission)
submission.to_csv('submission.csv', index=False)
| Titanic - Machine Learning from Disaster |
4,641,398 | df_train, handmade_features = add_external_features(df_train)
df_test, handmade_features_test = add_external_features(df_test)
df_train = pd.concat([df_train,pd.DataFrame(handmade_features, columns=['indirect', 'question_count', 'reason_explanation_words', 'choice_words'])],axis=1)
df_test = pd.concat([df_test,pd.Da... | train = pd.read_csv(".. /input/train.csv")
test = pd.read_csv(".. /input/test.csv")
all = pd.concat([train, test], sort = False)
all['Age'] = all['Age'].fillna(value=all['Age'].median())
all['Fare'] = all['Fare'].fillna(value=all['Fare'].median())
all['Embarked'] = all['Embarked'].fillna('S')
all.loc[ all['Age'] ... | Titanic - Machine Learning from Disaster |
4,641,398 | num_words_scaler = MinMaxScaler()
df_train[['question_body_num_words', 'answer_num_words']] = num_words_scaler.fit_transform(df_train[['question_body_num_words', 'answer_num_words']].values)
df_test[['question_body_num_words', 'answer_num_words']] = num_words_scaler.transform(df_test[['question_body_num_words', 'answe... | model = LogisticRegression(solver = 'liblinear')
model.fit(X_train,y_train)
predictions = model.predict(X_test)
confusion_matrix(y_test,predictions)
TestForPred = all_test.drop(['PassengerId', 'Survived'], axis = 1)
t_pred = model.predict(TestForPred ).astype(int)
PassengerId = all_test['PassengerId']
sub = pd.Da... | Titanic - Machine Learning from Disaster |
4,439,667 | df=pd.concat([df,pd.get_dummies(df['host'], drop_first=False, prefix='host')],axis=1)
df=pd.concat([df,pd.get_dummies(df['category'], drop_first=False, prefix='cat')],axis=1 )<define_variables> | train_dir = ".. /input/train.csv"
test_dir = ".. /input/test.csv" | Titanic - Machine Learning from Disaster |
4,439,667 | len(['qa_id']+[i for i in df.columns if i.startswith('host_')or i.startswith('cat_')] )<merge> | df = pd.read_csv(train_dir)
test_df = pd.read_csv(test_dir)
print("Total number of instance : ",len(df))
df.isna().sum() | Titanic - Machine Learning from Disaster |
4,439,667 | df_train=pd.merge(df_train, df[['qa_id']+[i for i in df.columns if i.startswith('host_')or i.startswith('cat_')]], how='inner', on='qa_id')
df_test = pd.merge(df_test, df[['qa_id']+[i for i in df.columns if i.startswith('host_')or i.startswith('cat_')]], how='inner', on='qa_id' )<categorify> | df.drop(["Cabin"], axis = 1, inplace = True)
test_df.drop(["Cabin"], axis = 1, inplace = True)
df.drop(["Ticket"], axis = 1, inplace = True)
test_df.drop(["Ticket"], axis = 1, inplace = True)
df.info()
df.head(10 ) | Titanic - Machine Learning from Disaster |
4,439,667 |
<categorify> | df.drop("PassengerId", axis = 1, inplace = True)
test_df.drop("PassengerId", axis = 1, inplace = True ) | Titanic - Machine Learning from Disaster |
4,439,667 |
<drop_column> | df["Sex"].replace("male", 0, inplace = True)
test_df["Sex"].replace("male", 0, inplace = True)
df["Sex"].replace("female", 1, inplace = True)
test_df["Sex"].replace("female", 1, inplace = True)
df["Embarked"].replace(["S","C","Q"],[0,1,2], inplace = True)
test_df["Embarked"].replace(["S","C","Q"],[0,1,2], inplace ... | Titanic - Machine Learning from Disaster |
4,439,667 | df_train.drop(['host', 'category'], inplace=True, axis=1)
df_test.drop(['host', 'category'], inplace=True, axis=1 )<string_transform> | def create_family_ranges(df):
familysize = []
for members in df["n_fam_mem"]:
if members == 0:
familysize.append(0)
elif members > 0 and members <=4:
familysize.append(1)
elif members > 4:
familysize.append(2)
return familysize
famsize = create_family_ranges(df)
df["familysize"] = famsize
test_famsize = create_fami... | Titanic - Machine Learning from Disaster |
4,439,667 | def _get_masks(tokens, max_seq_length):
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq length!")
return [1]*len(tokens)+[0]*(max_seq_length-len(tokens))
def _get_segments(tokens, max_seq_length):
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq length!")
... | def age_to_int(df):
agelist = df["Age"].values.tolist()
for i in range(len(agelist)) :
if agelist[i] < 18 and agelist[i] >= 0:
agelist[i] = 0
elif agelist[i] >= 18 and agelist[i] < 60:
agelist[i] = 1
elif agelist[i]>=60 and agelist[i]<200:
agelist[i] = 2
else:
agelist[i] = -1
ageint = pd.DataFrame(agelist)
return agei... | Titanic - Machine Learning from Disaster |
4,439,667 | bert_config=BertConfig(unk_token="[QBODY]", pad_token="[ANS]" ).from_pretrained('.. /input/bert-tensorflow/bert-base-uncased-config.json',output_hidden_states=True)
def bertModel() :
input_ids_q = keras.layers.Input(( MAX_SEQUENCE_LENGTH), dtype = tf.int32, name = 'input_word_ids_q')
input_mask_q = keras.layers.Input... | ageint = age_to_int(df)
df["Ageint"] = ageint
df.drop("Age", axis = 1, inplace = True)
test_ageint = age_to_int(test_df)
test_df["Ageint"] = test_ageint
test_df.drop("Age", axis = 1, inplace = True)
| Titanic - Machine Learning from Disaster |
4,439,667 | gkf = GroupKFold(n_splits=10 ).split(X=df_train.question_body, groups=df_train.question_body )<randomize_order> | def conv_fare_ranges(df):
fare_ranges = []
for fare in df.actual_fare:
if fare < 7:
fare_ranges.append(0)
elif fare >=7 and fare < 14:
fare_ranges.append(1)
elif fare >=14 and fare < 30:
fare_ranges.append(2)
elif fare >=30 and fare < 50:
fare_ranges.append(3)
elif fare >=50:
fare_ranges.append(4)
return fare_rang... | Titanic - Machine Learning from Disaster |
4,439,667 | outputs = compute_output_arrays(df_train, output_categories)
inputs_q = compute_input_array_questions(df_train, ['treated_question_title','treated_question_body'], tokenizer2, MAX_SEQUENCE_LENGTH)
inputs_a = compute_input_array_answers(df_train, ['treated_answer'], tokenizer2, MAX_SEQUENCE_LENGTH)
test_inputs_q = co... | def name_to_int(df):
name = df["Name"].values.tolist()
namelist = []
for i in name:
index = 1
inew = i.split()
if inew[0].endswith(","):
index = 1
elif inew[1].endswith(","):
index = 2
elif inew[2].endswith(","):
index = 3
namelist.append(inew[index])
print(set(namelist))
titlelist = []
for i in range(len(namelist)) :... | Titanic - Machine Learning from Disaster |
4,439,667 | histories = []
for fold,(train_idx, valid_idx)in enumerate(gkf):
if fold<2:
keras.backend.clear_session()
model = bertModel()
train_inputs_q = [inputs_q[i][train_idx] for i in range(3)]
train_inputs_a = [inputs_a[i][train_idx] for i in range(3)]
train_outputs = outputs[train_idx]
valid_inputs_q = [inputs_q[i][valid_idx... | titlelist = name_to_int(df)
df["titles"] = titlelist
df["titles"].value_counts()
testtitlelist = name_to_int(test_df)
test_df["titles"] = testtitlelist | Titanic - Machine Learning from Disaster |
4,439,667 | def _get_masks_google_qa(tokens, max_seq_length):
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq length!")
return [1]*len(tokens)+ [0] *(max_seq_length - len(tokens))
def _get_segments_google_qa(tokens, max_seq_length):
if len(tokens)>max_seq_length:
raise IndexError("Token length ... | df["titles"].replace(["Ms.","Jonkheer.","the","Don.","Capt.","Sir.","Lady.","Mme.","Col.","Major."],"sometitle", inplace = True)
test_df["titles"].replace(["Ms.","Jonkheer.","the","Don.","Capt.","Sir.","Lady.","Mme.","Col.","Major."],"sometitle", inplace = True)
df["titles"].replace("Mlle.","Miss.", inplace = True)
... | Titanic - Machine Learning from Disaster |
4,439,667 | gkf_google_qa = GroupKFold(n_splits=10 ).split(X=df_train.question_body, groups=df_train.question_body)
outputs_google_qa = compute_output_arrays_google_qa(df_train, output_categories)
inputs_google_qa = compute_input_arays_google_qa(df_train, ['treated_question_title','treated_question_body','treated_answer'], token... | df["titles"].replace(["Mr.", "Miss.", "Mrs", "Master.", "Dr.", "Rev.", "sometitle"],[0,1,2,3,4,5,6], inplace = True)
df["titles"].astype("int64")
test_df["titles"].replace(["Mr.", "Miss.", "Mrs", "Master.", "Dr.", "Rev.", "sometitle"],[0,1,2,3,4,5,6], inplace = True)
test_df["titles"].astype("int64")
df.drop(["Name... | Titanic - Machine Learning from Disaster |
4,439,667 | test_predictions_google_qa=[]
for fold,(train_idx, valid_idx)in enumerate(gkf_google_qa):
if fold<3:
keras.backend.clear_session()
model_qa = bert_model_google_qa()
print(f'/kaggle/input/google-qa-bert-trained-tfbert-hiddenl-preprocess/bert-base-{fold}-4.hdf5')
model_qa.load_weights(f'/kaggle/input/google-qa-bert-trai... | df.drop(["SibSp","Parch","Fare","n_fam_mem","actual_fare"], axis = 1, inplace = True)
test_df.drop(["SibSp","Parch","Fare","n_fam_mem","actual_fare"], axis = 1, inplace = True ) | Titanic - Machine Learning from Disaster |
4,439,667 | test_preds_google_qa = [test_predictions_google_qa[i] for i in range(len(test_predictions_google_qa)) ]
test_preds_google_qa = [np.average(test_preds_google_qa, axis=0)for i in range(len(test_preds_google_qa)) ]
test_preds_google_qa = np.mean(test_preds_google_qa, axis=0)
test_preds_google_qa.shape<compute_test_metric... | labels = df["Survived"]
data = df.drop("Survived", axis = 1)
X_train, X_test, Y_train, Y_test = train_test_split(data, labels, test_size = 0.1 ) | Titanic - Machine Learning from Disaster |
4,439,667 | final_preds = np.average(np.array([test_preds, test_preds_google_qa]),axis=0)
final_preds.shape<save_to_csv> | final_clf = None
clf_names = ["Logistic Regression", "KNN(3)", "KNN(5)", "Random forest classifier", "Decision Tree Classifier",
"Gradient Boosting Classifier", "Support Vector Machine"]
classifiers = []
scores = [] | Titanic - Machine Learning from Disaster |
4,439,667 | df_sub.iloc[:, 1:] = final_preds
df_sub.to_csv('submission.csv', index=False )<set_options> | bestknn5 = None
bestknn3 = None
bestrf = None
bestgb = None
bestcvm = None
bestlr = None
bestdt = None
for i in range(10):
X_train, X_test, Y_train, Y_test = train_test_split(data, labels, test_size = 0.1)
tempscores = []
lr_clf = LogisticRegression()
lr_clf.fit(X_train, Y_train)
tempscores.append(( lr_clf.score(X_te... | Titanic - Machine Learning from Disaster |
4,439,667 | np.set_printoptions(suppress=True)
tf.random.set_seed(42)
random.seed(42 )<load_from_csv> | scores = np.array(scores)
clfs = pd.DataFrame({"Classifier":clf_names})
clfs["iteration0"] = scores[0].T
clfs["iteration1"] = scores[1].T
clfs["iteration2"] = scores[2].T
clfs["iteration3"] = scores[3].T
clfs["iteration4"] = scores[4].T
clfs["iteration5"] = scores[5].T
clfs["iteration6"] = scores[6].T
clfs["iteration... | Titanic - Machine Learning from Disaster |
4,439,667 | PATH = '.. /input/google-quest-challenge/'
VOCAB_PATH = '.. /input/bert-base-from-tfhub/bert_en_uncased_L-12_H-768_A-12'
tokenizer = tokenization.FullTokenizer(VOCAB_PATH + '/assets/vocab.txt', do_lower_case=True)
MAX_SEQUENCE_LENGTH = 512
df_train = pd.read_csv(PATH+'train.csv')
df_test = pd.read_csv(PATH+'test.csv'... | final_clf = bestsvm | Titanic - Machine Learning from Disaster |
4,439,667 | def _get_masks(tokens, max_seq_length):
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq length!")
return [1]*len(tokens)+ [0] *(max_seq_length - len(tokens))
def _get_segments(tokens, max_seq_length):
if len(tokens)>max_seq_length:
raise IndexError("Token length more than max seq le... | test_data = test_df
predictions = final_clf.predict(test_data)
print(len(predictions)) | Titanic - Machine Learning from Disaster |
4,439,667 | def compute_spearmanr(trues, preds):
rhos = []
for col_trues, col_pred in zip(trues.T, preds.T):
rhos.append(
spearmanr(col_trues, col_pred + np.random.normal(0, 1e-7, col_pred.shape[0])).correlation)
return np.mean(rhos)
class CustomCallback(tf.keras.callbacks.Callback):
def __init__(self, valid_data, test_data, ba... | final_csv = []
csv_title = ['PassengerId', 'Survived']
final_csv.append(csv_title)
for i in range(len(predictions)) :
passengerid = i + 892
survived = predictions[i]
temp = [passengerid, survived]
final_csv.append(temp)
print(len(final_csv))
with open('submission_csv.csv', 'w')as file:
writer = csv.writer(file)
writ... | Titanic - Machine Learning from Disaster |
4,657,296 | gkf = GroupKFold(n_splits=20 ).split(X=df_train.question_body, groups=df_train.question_body)
outputs = compute_output_arrays(df_train, output_categories)
inputs = compute_input_arays(df_train, input_categories, tokenizer, MAX_SEQUENCE_LENGTH)
test_inputs = compute_input_arays(df_test, input_categories, tokenizer, M... | X_full = pd.read_csv(".. /input/train.csv",index_col=0)
X_full_test = pd.read_csv(".. /input/test.csv",index_col=0)
X_full.shape | Titanic - Machine Learning from Disaster |
4,657,296 | histories = []
for fold,(train_idx, valid_idx)in enumerate(gkf):
if fold < 3:
K.clear_session()
model = bert_model()
train_inputs = [inputs[i][train_idx] for i in range(3)]
train_outputs = outputs[train_idx]
valid_inputs = [inputs[i][valid_idx] for i in range(3)]
valid_outputs = outputs[valid_idx]
history = train_and_p... | y = X_full.Survived
features = ['Pclass','Sex','Age','SibSp','Parch']
X = X_full[features].copy()
X_test = X_full_test[features].copy()
X_train, X_valid, y_train, y_valid = train_test_split(X,y,train_size=0.8,test_size=0.2,random_state=0)
X.isnull().sum()
| Titanic - Machine Learning from Disaster |
4,657,296 | test_predictions = [histories[i].test_predictions for i in range(len(histories)) ]
test_predictions = [np.average(test_predictions[i], axis=0)for i in range(len(test_predictions)) ]
test_predictions = np.mean(test_predictions, axis=0)
df_sub.iloc[:, 1:] = test_predictions
df_sub.to_csv('submission.csv', index=False )<... | X_train.fillna(X_train.mean() ,inplace=True)
X_valid.fillna(X_valid.mean() ,inplace=True)
X_test.fillna(X_valid.mean() ,inplace=True)
X_train.head()
| Titanic - Machine Learning from Disaster |
4,657,296 | np.set_printoptions(suppress=True )<load_from_csv> | label_encoder = LabelEncoder()
X_train['Sex'] = label_encoder.fit_transform(X_train['Sex'])
X_valid['Sex'] = label_encoder.transform(X_valid['Sex'])
X_test['Sex'] = label_encoder.fit_transform(X_test['Sex'])
X_train.head() | Titanic - Machine Learning from Disaster |
4,657,296 | PATH = '.. /input/google-quest-challenge/'
BERT_PATH = '.. /input/bert-base-from-tfhub/bert_en_uncased_L-12_H-768_A-12'
tokenizer = tokenization.FullTokenizer(BERT_PATH+'/assets/vocab.txt', True)
MAX_SEQUENCE_LENGTH = 512
df_train = pd.read_csv(PATH+'train.csv')
df_test = pd.read_csv(PATH+'test.csv')
df_sub = pd.rea... | my_model = XGBClassifier(n_estimators=1000, learning_rate=0.05)
my_model.fit(X_train, y_train,
early_stopping_rounds=5,
eval_set=[(X_valid, y_valid)],
verbose=False ) | Titanic - Machine Learning from Disaster |
4,657,296 | targets = [
'question_asker_intent_understanding',
'question_body_critical',
'question_conversational',
'question_expect_short_answer',
'question_fact_seeking',
'question_has_commonly_accepted_answer',
'question_interestingness_others',
'question_interestingness_self',
'question_multi_intent',
'question_not_really_a_qu... | predictions = my_model.predict(X_valid)
print("Accuracy Score: " + str(accuracy_score(predictions, y_valid)) ) | Titanic - Machine Learning from Disaster |
4,657,296 | eng_stopwords = set(stopwords.words("english"))
def include_window_datas(df_q):
out_df = pd.DataFrame()
' can be used to count the number of sentences in each comment
out_df['count_sent']=df_q["question_body"].apply(lambda x: len(re.findall("
",str(x)))+1)
out_df['count_word']=df_q["question_body"].apply(lambda x: len... | preds = my_model.predict(X_valid)
preds_test = my_model.predict(X_test)
| Titanic - Machine Learning from Disaster |
4,657,296 | sc = StandardScaler()
train_add_features = sc.fit_transform(df_train_add_features)
test_add_features = sc.fit_transform(df_test_add_features)
train_add_features[:5]<string_transform> | features = ['Pclass','Sex','Age','SibSp','Embarked']
X = X_full[features].copy()
X_test = X_full_test[features].copy()
X.fillna(X.mean() ,inplace=True)
X_test.fillna(X_test.mean() ,inplace=True)
X['Embarked'] = X['Embarked'].fillna('S')
X_test['Embarked'] = X_test['Embarked'].fillna('S')
X['Sex'] = label_encoder.fi... | 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.