kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
13,407,226 | idx = features = train.columns.values[2:202]
for df in [test, train]:
df['sum'] = df[idx].sum(axis=1)
df['min'] = df[idx].min(axis=1)
df['max'] = df[idx].max(axis=1)
df['mean'] = df[idx].mean(axis=1)
df['std'] = df[idx].std(axis=1)
df['skew'] = df[idx].skew(axis=1)
df['kurt'] = df[idx].kurtosis(axis=1)
df['med']... | def predict_test(model, train_c, test_c, filenamne):
features = train_c.columns.to_list()
features.remove(target)
model.fit(train_c[features], train_c[target])
predictions = model.predict(test_c[features])
submission = pd.DataFrame({"PassengerId":test["passengerid"],"Survived":predictions})
submission.to_csv(file... | Titanic - Machine Learning from Disaster |
13,407,226 | features = [c for c in train.columns if c not in ['ID_code', 'target']]
target = train['target']<init_hyperparams> | cat_features = ['pclass','sex','embarked','age_group']
accuracy = evaluate_lr_model(train, cat_features, num_features)
print('{}: {:.2f}%'.format(cat_features + num_features, accuracy*100)) | Titanic - Machine Learning from Disaster |
13,407,226 | param = {
'bagging_freq': 5,
'bagging_fraction': 0.4,
'boost_from_average':'false',
'boost': 'gbdt',
'feature_fraction': 0.05,
'learning_rate': 0.01,
'max_depth': -1,
'metric':'auc',
'min_data_in_leaf': 80,
'min_sum_hessian_in_leaf': 10.0,
'num_leaves': 13,
'num_threads': 8,
'tree_learner': 'serial',
'objective': 'bina... | titles_map = {
"Mr" : "Mr",
"Mme": "Mrs",
"Ms": "Mrs",
"Mrs" : "Mrs",
"Master" : "Master",
"Mlle": "Miss",
"Miss" : "Miss",
"Capt": "Officer",
"Col": "Officer",
"Major": "Officer",
"Dr": "Officer",
"Rev": "Officer",
"Jonkheer": "Royalty",
"Don": "Royalty",
"Sir" : "Royalty",
"Countess": "Royalty",
"Dona": "Royalty",
"L... | Titanic - Machine Learning from Disaster |
13,407,226 | folds = StratifiedKFold(n_splits=10, shuffle=False, random_state=44000)
oof = np.zeros(len(train))
predictions = np.zeros(len(test))
feature_importance_df = pd.DataFrame()
for fold_,(trn_idx, val_idx)in enumerate(folds.split(train.values, target.values)) :
print("Fold {}".format(fold_))
trn_data = lgb.Dataset(train.il... | cat_features = ['pclass','sex','embarked','age_group','title']
accuracy = evaluate_lr_model(train, cat_features, num_features)
print('{}: {:.2f}%'.format(cat_features + num_features, accuracy*100)) | Titanic - Machine Learning from Disaster |
13,407,226 | sub_df = pd.DataFrame({"ID_code":test["ID_code"].values})
sub_df["target"] = predictions
sub_df.to_csv("submission.csv", index=False )<install_modules> | test['age_group'] = group_age(test['age'])
test["title"] = extract_title(test['name'])
train_c = copy_convert_dataset(train, cat_features, num_features)
test_c = copy_convert_dataset(test, cat_features, num_features, False)
predict_test(lr, train_c, test_c, 'submission_2.csv' ) | Titanic - Machine Learning from Disaster |
13,407,226 | !pip install.. /input/sacremoses > /dev/null
sys.path.insert(0, ".. /input/transformers/" )<set_options> | models = [
{
'name':'Logistic regression',
'estimator':LogisticRegression() ,
'hyperparameters':{
'solver': ['newton-cg', 'lbfgs', 'liblinear']
}
},
{
'name':'Decision tree',
'estimator':DecisionTreeClassifier(random_state=1),
'hyperparameters':{
'criterion':['entropy','gini'],
'splitter':['best','random'],
'max_depth'... | Titanic - Machine Learning from Disaster |
13,407,226 | np.set_printoptions(suppress=True)
print(tf.__version__ )<load_from_csv> | predict_test(models[2]['best_model'], train_c, test_c, 'submission_3.csv' ) | Titanic - Machine Learning from Disaster |
13,063,682 | PATH = '.. /input/google-quest-challenge/'
BERT_PATH = '.. /input/bert-base-uncased-huggingface-transformer/'
tokenizer = BertTokenizer.from_pretrained(BERT_PATH+'bert-base-uncased-vocab.txt')
MAX_SEQUENCE_LENGTH = 512
df_train = pd.read_csv(PATH+'train.csv')
df_test = pd.read_csv(PATH+'test.csv')
df_sub = pd.read_c... | train=pd.read_csv('/kaggle/input/titanic/train.csv')
test=pd.read_csv('/kaggle/input/titanic/test.csv')
submission=pd.DataFrame(test['PassengerId'])
y=train['Survived'] | Titanic - Machine Learning from Disaster |
13,063,682 | 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... | dataset=pd.concat([train.drop(['PassengerId','Survived'],axis=1),test.drop('PassengerId',axis=1)] ) | Titanic - Machine Learning from Disaster |
13,063,682 | 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 create_model() :
q_id = tf.keras.layers.Input(( MAX_SEQUENCE_LENGTH,), dtype=tf.int32)
a_id = tf.keras.layers.Input((... | dataset['Age'].fillna(dataset['Age'].mean() ,inplace=True)
dataset['Fare'].fillna(dataset['Fare'].median() ,inplace=True)
dataset['Embarked'].fillna('S',inplace=True)
dataset.drop(['Cabin','Name','Ticket'],axis=1,inplace=True ) | Titanic - Machine Learning from Disaster |
13,063,682 | outputs = compute_output_arrays(df_train, output_categories)
inputs = compute_input_arrays(df_train, input_categories, tokenizer, MAX_SEQUENCE_LENGTH)
test_inputs = compute_input_arrays(df_test, input_categories, tokenizer, MAX_SEQUENCE_LENGTH)
<load_pretrained> | label=LabelEncoder()
dataset['Sex']=label.fit_transform(dataset['Sex'])
dataset['Age']=dataset['Age'].astype(int ) | Titanic - Machine Learning from Disaster |
13,063,682 | gkf = GroupKFold(n_splits=10 ).split(X=df_train.question_body, groups=df_train.question_body)
valid_preds = []
test_preds = []
for fold,(train_idx, valid_idx)in enumerate(gkf):
train_inputs = [inputs[i][train_idx] for i in range(len(inputs)) ]
train_outputs = outputs[train_idx]
valid_inputs = [inputs[i][valid_idx] for... | dataset['familyno']=dataset['SibSp']+dataset['Parch']+1 | Titanic - Machine Learning from Disaster |
13,063,682 | df_sub.iloc[:, 1:] = np.average(test_preds, axis=0)
df_sub.to_csv('submission.csv', index=False )<import_modules> | dataset=pd.get_dummies(dataset,columns=['Pclass','Embarked'])
dataset.drop(['SibSp','Parch'],axis=1,inplace=True)
xtrain=dataset[:len(train)]
test=dataset[len(train):]
xtrain | Titanic - Machine Learning from Disaster |
13,063,682 |
pyLDAvis.enable_notebook()
np.random.seed(2018)
warnings.filterwarnings('ignore' )<load_from_csv> | sky=GradientBoostingClassifier()
sky.fit(xtrain,y)
c=sky.predict(test)
submission['Survived']=c | Titanic - Machine Learning from Disaster |
13,063,682 | <load_from_csv><EOS> | submission.to_csv('ver1.csv',index=False ) | Titanic - Machine Learning from Disaster |
8,151,668 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<load_from_csv> | %matplotlib inline
warnings.filterwarnings("ignore")
sns.set(style="white", font_scale=1.2)
| Titanic - Machine Learning from Disaster |
8,151,668 | test = pd.read_csv('/kaggle/input/google-quest-challenge/test.csv')
test.head(3 )<define_variables> | df_train = pd.read_csv('.. /input/titanic/train.csv')
df_test = pd.read_csv('.. /input/titanic/test.csv' ) | Titanic - Machine Learning from Disaster |
8,151,668 | 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... | Titanic - Machine Learning from Disaster | |
8,151,668 | lengths = train['question_title'].apply(len)
train['lengths'] = lengths
lengths = train.loc[train['lengths']<4000]['lengths']
sns.distplot(lengths, color='b')
plt.show()<feature_engineering> | df_train.isnull().sum() | Titanic - Machine Learning from Disaster |
8,151,668 | stopwords=stopwords.words('english')
train['que_stopwords']=train['question_body'].apply(lambda x : [x for x in x.split() if x in stopwords])
train['ans_stopwords']=train['answer'].apply(lambda x: [x for x in x.split() if x in stopwords] )<count_unique_values> | df_test.isnull().sum() | Titanic - Machine Learning from Disaster |
8,151,668 | def common_ngrams(col,common=10):
corpus=[]
for question in train[col].values:
words=[str(x[0]+' '+x[1])for x in ngrams(question.split() ,2)]
corpus.append(words)
flatten=[x for one in corpus for x in one]
counter=Counter(flatten)
most_common=counter.most_common(common)
string,value=zip(*(most_common))
return string... | def check_missing_values(df, df_name=None):
print(f'{df_name} - Missing values:')
print('-'*30)
columns = df.columns
for column in columns:
count_missing_values = df[column].isnull().sum()
missing_values =(count_missing_values / len(df[column])) * 100
if missing_values !=0:
print(f'{column} --> {count_missing_values}... | Titanic - Machine Learning from Disaster |
8,151,668 | np.set_printoptions(suppress=True )<load_from_csv> | check_missing_values(df_train, 'TRAIN' ) | Titanic - Machine Learning from Disaster |
8,151,668 | PATH = '.. /input/google-quest-challenge/'
BERT_PATH = '.. /input/bert-base-from-tfhub/bert_en_uncased_L-12_H-768_A-12'
tokenizer = 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.read_csv(PATH+'s... | check_missing_values(df_test, 'TEST' ) | Titanic - Machine Learning from Disaster |
8,151,668 | 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... | df_train.drop(['PassengerId', 'Cabin', 'Ticket'], axis=1, inplace=True)
submission = pd.DataFrame()
submission['PassengerId'] = df_test['PassengerId']
df_test.drop(['PassengerId', 'Cabin', 'Ticket'], axis=1, inplace=True ) | Titanic - Machine Learning from Disaster |
8,151,668 | 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... | check_missing_values(df_train, 'DF TRAIN' ) | Titanic - Machine Learning from Disaster |
8,151,668 | models = []
for i in range(5):
model_path = f'.. /input/bertuned-f{i}/bertuned_f{i}.h5'
model = bert_model()
model.load_weights(model_path)
models.append(model)
model_path = f'.. /input/bertf1e15/Full-0.h5'
model = bert_model()
model.load_weights(model_path)
models.append(model )<load_pretrained> | check_missing_values(df_test, 'DF TEST' ) | Titanic - Machine Learning from Disaster |
8,151,668 | for i in range(2):
model_path = f".. /input/bertmodelpretrained/bert-{i}.h5"
model = bert_model()
model.load_weights(model_path )<concatenate> | df_train['Familysize'] = df_train['SibSp'] + df_train['Parch']
df_test['Familysize'] = df_test['SibSp'] + df_test['Parch'] | Titanic - Machine Learning from Disaster |
8,151,668 | models.append(model )<define_variables> | df_train['Alone'] = df_train['Familysize'].apply(lambda x: 1 if x == 0 else 0)
df_test['Alone'] = df_test['Familysize'].apply(lambda x: 1 if x == 0 else 0 ) | Titanic - Machine Learning from Disaster |
8,151,668 | test_predictions = []<predict_on_test> | df_train[df_train['Embarked'].isnull() ] | Titanic - Machine Learning from Disaster |
8,151,668 | for model in models:
test_predictions.append(model.predict(test_inputs, batch_size=8))<prepare_output> | df_train['Embarked'] = df_train['Embarked'].fillna('C' ) | Titanic - Machine Learning from Disaster |
8,151,668 | final_predictions = np.mean(test_predictions, axis=0 )<save_to_csv> | df_test[df_test['Fare'].isnull() ] | Titanic - Machine Learning from Disaster |
8,151,668 | df_sub.iloc[:, 1:] = final_predictions
df_sub.to_csv('submission.csv', index=False )<load_from_csv> | median_fare = df_test[(df_test['Pclass'] == 3)&(df_test['Embarked'] == 'S')&(df_test['Alone'] == 1)]['Fare'].median()
median_fare | Titanic - Machine Learning from Disaster |
8,151,668 | train = pd.read_csv(".. /input/google-quest-challenge/train.csv", index_col='qa_id')
train.shape<load_from_csv> | df_test['Fare'] = df_test['Fare'].fillna(median_fare ) | Titanic - Machine Learning from Disaster |
8,151,668 | test = pd.read_csv(".. /input/google-quest-challenge/test.csv", index_col='qa_id')
test.shape<define_variables> | def get_age(cols):
age = cols[0]
pclass = cols[1]
sex = cols[2]
if pd.isnull(age):
if pclass == 1:
if sex == 'male':
return 40
else:
return 35
elif pclass == 2:
if sex == 'male':
return 30
else:
return 28
else:
if sex == 'male':
return 25
else:
return 21.5
else:
return age | Titanic - Machine Learning from Disaster |
8,151,668 | target_columns = [
'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_real... | df_train['Age'] = df_train[['Age','Pclass', 'Sex']].apply(get_age, axis=1)
df_test['Age'] = df_test[['Age','Pclass', 'Sex']].apply(get_age, axis=1 ) | Titanic - Machine Learning from Disaster |
8,151,668 | y_train = train[target_columns].copy()
x_train = train.drop(target_columns, axis=1)
del train
x_test = test.copy()
del test<import_modules> | df_train['Title'] = df_train['Name'].apply(lambda x: get_title(x))
df_test['Title'] = df_test['Name'].apply(lambda x: get_title(x)) | Titanic - Machine Learning from Disaster |
8,151,668 | import tensorflow_hub as hub
import tensorflow as tf<define_variables> | df_train['Title'].value_counts() | Titanic - Machine Learning from Disaster |
8,151,668 | copyfile(src = ".. /input/tf-bert-tokenization/tokenization.py", dst = ".. /working/tokenization.py")
<define_variables> | df_train.drop('Name', axis=1, inplace=True)
df_test.drop('Name', axis=1, inplace=True ) | Titanic - Machine Learning from Disaster |
8,151,668 | BERT = '.. /input/bert-model'
tokenizer = FullTokenizer(BERT + '/assets/vocab.txt', True )<string_transform> | for dataframe in [df_train, df_test]:
dataframe['Title'] = dataframe['Title'].replace(['Lady', 'Capt', 'Col','Don', 'Dr',
'Major', 'Rev', 'Sir', 'Dona', 'Countess', 'Jonkheer'], 'Other')
dataframe['Title'] = dataframe['Title'].replace('Mlle', 'Miss')
dataframe['Title'] = dataframe['Title'].replace('Ms', 'Miss')
data... | Titanic - Machine Learning from Disaster |
8,151,668 | tokenizer.tokenize('Hello world from BERT FullTokenizer!' )<categorify> | sex = pd.get_dummies(df_train['Sex'], prefix='Sex', drop_first=True)
embarked = pd.get_dummies(df_train['Embarked'], prefix='Embarked', drop_first=True)
pclass = pd.get_dummies(df_train['Pclass'], prefix='Pclass', drop_first=True)
title = pd.get_dummies(df_train['Title'], prefix='Title', drop_first=True)
df_train.d... | Titanic - Machine Learning from Disaster |
8,151,668 | 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... | sex = pd.get_dummies(df_test['Sex'], prefix='Sex', drop_first=True)
embarked = pd.get_dummies(df_test['Embarked'], prefix='Embarked',drop_first=True)
pclass = pd.get_dummies(df_test['Pclass'], prefix='Pclass',drop_first=True)
title = pd.get_dummies(df_test['Title'], prefix='Title', drop_first=True)
df_test.drop(['S... | Titanic - Machine Learning from Disaster |
8,151,668 | def trim_tokens(t, q, a, max_t, max_q, max_a):
if(len(t)+ len(q)+ len(a)) >(max_t + max_q + max_a):
_max_t = max_t
_max_q = max_q
_max_a = max_a
if len(t)> _max_t:
t = t[:_max_t]
else:
x =(_max_t - len(t)) / 2.
_max_q += math.ceil(x)
_max_a += math.floor(x)
if len(q)> _max_q:
q = q[:_max_q]
else:
_max_a +=(_max_q - ... | scaler = StandardScaler()
df_train[['Age', 'Fare']] = scaler.fit_transform(df_train[['Age', 'Fare']])
df_test[['Age', 'Fare']] = scaler.transform(df_test[['Age', 'Fare']] ) | Titanic - Machine Learning from Disaster |
8,151,668 | max_sequence_length = 512
<choose_model_class> | from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, make_scorer | Titanic - Machine Learning from Disaster |
8,151,668 | def make_model() :
input_word_ids = tf.keras.layers.Input(shape=(max_sequence_length,), dtype=tf.int32,
name="input_word_ids")
input_mask = tf.keras.layers.Input(shape=(max_sequence_length,), dtype=tf.int32,
name="input_mask")
segment_ids = tf.keras.layers.Input(shape=(max_sequence_length,), dtype=tf.int32,
name="seg... | X = df_train.drop('Survived', axis=1)
y = df_train['Survived'] | Titanic - Machine Learning from Disaster |
8,151,668 | def mean_spearmanr_correlation_score(y_true, y_pred):
return np.mean([spearmanr(y_pred[:, idx] + np.random.normal(0, 1e-7, y_pred.shape[0]),
y_true[:, idx] ).correlation for idx in range(len(target_columns)) ] )<define_variables> | X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.2, random_state=1 ) | Titanic - Machine Learning from Disaster |
8,151,668 | trained_estimators = []<train_model> | predictions = {} | Titanic - Machine Learning from Disaster |
8,151,668 | n_splits = 5
scores = []
cv = KFold(n_splits=n_splits, random_state=42)
idx = 1
for train_idx, valid_idx in cv.split(x_train, y_train, groups=x_train.question_body):
x_train_train = x_train.iloc[train_idx]
y_train_train = y_train.iloc[train_idx]
x_train_valid = x_train.iloc[valid_idx]
y_train_valid = y_train.iloc[vali... | from sklearn.linear_model import LogisticRegression | Titanic - Machine Learning from Disaster |
8,151,668 | y_pred = []
for estimator in trained_estimators:
y_pred.append(estimator.predict(make_bert_input(x_test)) )<concatenate> | logreg = LogisticRegression(random_state=121)
logreg.fit(X_train, y_train)
y_pred = logreg.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy ) | Titanic - Machine Learning from Disaster |
8,151,668 | def blend_by_ranking(data, weights):
out = np.zeros(data.shape[0])
for idx,column in enumerate(data.columns):
out += weights[idx] * rankdata(data[column].values)
out /= np.max(out)
return out<load_from_csv> | logreg = LogisticRegression(random_state=121)
param_grid = {
'penalty': ['l1', 'l2', 'elasticnet'],
'C': [0.01, 0.05, 0.1, 0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,16.5,17,18],
'solver': ['liblinear','saga']} | Titanic - Machine Learning from Disaster |
8,151,668 | submission = pd.read_csv(".. /input/google-quest-challenge/sample_submission.csv", index_col='qa_id')
out = pd.DataFrame(index=submission.index)
for column_idx,column in enumerate(target_columns):
column_data = pd.DataFrame(index=submission.index)
for prediction_idx,prediction in enumerate(y_pred):
column_data[str(p... | model = GridSearchCV(logreg, param_grid=param_grid, scoring='accuracy', cv=10, n_jobs=-1)
model.fit(X_train, y_train)
print('Best Params:', model.best_params_ ) | Titanic - Machine Learning from Disaster |
8,151,668 | out.to_csv("submission.csv" )<set_options> | best_lr = LogisticRegression(C=0.9, penalty='l1', solver='liblinear')
best_lr.fit(X_train, y_train)
y_pred = best_lr.predict(X_test ) | Titanic - Machine Learning from Disaster |
8,151,668 | SEED = 0
warnings.filterwarnings("ignore")
sns.set(font_scale=1.5)
plt.rcParams.update({'font.size': 16})
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
<load_from_csv> | print(f'Accuracy: {accuracy_score(y_test, y_pred)*100:.2f}%')
print('-'*55)
print(classification_report(y_test, y_pred))
print('-'*55)
print(confusion_matrix(y_test, y_pred)) | Titanic - Machine Learning from Disaster |
8,151,668 | train = pd.read_csv('/kaggle/input/google-quest-challenge/train.csv')
test = pd.read_csv('/kaggle/input/google-quest-challenge/test.csv')
train['set'] = 'train'
test['set'] = 'test'
complete_set = train.append(test)
print('Train samples: %s' % len(train))
print('Test samples: %s' % len(test))
display(train.head() )<... | from sklearn.neighbors import KNeighborsClassifier | Titanic - Machine Learning from Disaster |
8,151,668 | samp_id = 9
print('Question Title: %s
' % train['question_title'].values[samp_id])
print('Question Body: %s
' % train['question_body'].values[samp_id])
print('Answer: %s' % train['answer'].values[samp_id] )<define_variables> | from sklearn.neighbors import KNeighborsClassifier | Titanic - Machine Learning from Disaster |
8,151,668 | question_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_... | from sklearn.neighbors import KNeighborsClassifier | Titanic - Machine Learning from Disaster |
8,151,668 | train_users = set(train['question_user_page'].unique())
test_users = set(test['question_user_page'].unique())
print('Unique users in train set: %s' % len(train_users))
print('Unique users in test set: %s' % len(test_users))
print('Users in both sets: %s' % len(train_users & test_users))
print('What users are in both ... | error_rate = []
for i in range(1,40):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(X_train, y_train)
pred_i = knn.predict(X_test)
error_rate.append(np.mean(pred_i != y_test)) | Titanic - Machine Learning from Disaster |
8,151,668 | train_users = set(train['answer_user_page'].unique())
test_users = set(test['answer_user_page'].unique())
print('Unique users in train set: %s' % len(train_users))
print('Unique users in test set: %s' % len(test_users))
print('Users in both sets: %s' % len(train_users & test_users))<feature_engineering> | knn = KNeighborsClassifier(n_neighbors=25)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test ) | Titanic - Machine Learning from Disaster |
8,151,668 | complete_set['question_title_len'] = complete_set['question_title'].apply(lambda x : len(x))
complete_set['question_body_len'] = complete_set['question_body'].apply(lambda x : len(x))
complete_set['answer_len'] = complete_set['answer'].apply(lambda x : len(x))
complete_set['question_title_wordCnt'] = complete_set['ques... | print(f'Accuracy: {accuracy_score(y_test, y_pred)*100:.2f}%')
print('-'*55)
print(classification_report(y_test, y_pred))
print('-'*55)
print(confusion_matrix(y_test, y_pred)) | Titanic - Machine Learning from Disaster |
8,151,668 | eng_stopwords = stopwords.words('english')
complete_set['question_title'] = complete_set['question_title'].str.replace('[^a-z ]','')
complete_set['question_body'] = complete_set['question_body'].str.replace('[^a-z ]','')
complete_set['answer'] = complete_set['answer'].str.replace('[^a-z ]','')
complete_set['questio... | from sklearn.ensemble import RandomForestClassifier | Titanic - Machine Learning from Disaster |
8,151,668 | np.set_printoptions(suppress=True )<load_from_csv> | rf = RandomForestClassifier(random_state=121)
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy ) | Titanic - Machine Learning from Disaster |
8,151,668 | 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... | Titanic - Machine Learning from Disaster | |
8,151,668 | 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... | best_rf = RandomForestClassifier(random_state=121, criterion='entropy', max_depth=15, min_samples_leaf=5, min_samples_split=2, n_estimators=50)
best_rf.fit(X_train, y_train)
y_pred = best_rf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred ) | Titanic - Machine Learning from Disaster |
8,151,668 | 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... | print(f'Accuracy: {accuracy_score(y_test, y_pred)*100:.2f}%')
print('-'*55)
print(classification_report(y_test, y_pred))
print('-'*55)
print(confusion_matrix(y_test, y_pred)) | Titanic - Machine Learning from Disaster |
8,151,668 | gkf = GroupKFold(n_splits=5 ).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, MA... | from xgboost import XGBClassifier | Titanic - Machine Learning from Disaster |
8,151,668 | 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... | xgb = XGBClassifier(random_state=121)
xgb.fit(X_train, y_train)
y_pred = xgb.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy ) | Titanic - Machine Learning from Disaster |
8,151,668 | 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 )<... | classifiers = [('Logistic Regression', best_lr),
('KNN', knn),
('Random Forest', best_rf),
('Xgboost', xgb)]
for name_clf, clf in classifiers:
y_pred = clf.predict(X_test)
acc = accuracy_score(y_test, y_pred)
print(f'{name_clf} accuracy: {round(acc, 3)}%' ) | Titanic - Machine Learning from Disaster |
8,151,668 | !pip install.. /input/sacremoses/sacremoses-master/ > /dev/null<install_modules> | from sklearn.ensemble import VotingClassifier | Titanic - Machine Learning from Disaster |
8,151,668 | !pip install ".. /input/kerasswa/keras-swa-0.1.2" > /dev/null<feature_engineering> | vc = VotingClassifier(estimators=classifiers)
vc.fit(X_train, y_train)
y_pred = vc.predict(X_test)
acc_vc = accuracy_score(y_test, y_pred)
print(f'Ensembler Accuracy: {round(acc_vc, 3)}%' ) | Titanic - Machine Learning from Disaster |
8,151,668 | <define_variables><EOS> | vc.fit(X, y)
prediction = vc.predict(df_test)
submission['Survived'] = prediction
submission.to_csv('Submission.csv', index=False ) | Titanic - Machine Learning from Disaster |
581,073 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<load_from_csv> | %matplotlib inline
| Titanic - Machine Learning from Disaster |
581,073 | INPUT_PATH=".. /input/"
train = pd.read_csv(INPUT_PATH+'google-quest-challenge/train.csv')
test = pd.read_csv(INPUT_PATH+'google-quest-challenge/test.csv')
submission = pd.read_csv(INPUT_PATH+'google-quest-challenge/sample_submission.csv' )<define_variables> | train = pd.read_csv(".. /input/train.csv")
test = pd.read_csv(".. /input/test.csv")
train.head()
print(train['Embarked'].unique() , train['Pclass'].unique())
train[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False ).mean().sort_values(by='Survived', ascending=False)
| Titanic - Machine Learning from Disaster |
581,073 | 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... | for df in [train, test]:
df.drop(labels=["PassengerId", "Cabin", "Name", "Ticket"], axis=1, inplace=True ) | Titanic - Machine Learning from Disaster |
581,073 | puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '
'·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '\xa0', '\t',
'“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑',... | for df in [train, test]:
for col in ["Age", "Fare"]:
df[col] = df[col].fillna(np.mean(df[col])) | Titanic - Machine Learning from Disaster |
581,073 | train = clean_data(train, input_columns)
test = clean_data(test, input_columns )<string_transform> | min_max_scaler = preprocessing.MinMaxScaler()
for df in [train, test]:
for col in ["Age", "Fare"]:
x = df[[col]].values.astype(float)
df[col] = min_max_scaler.fit_transform(x ) | Titanic - Machine Learning from Disaster |
581,073 | def constructLabeledSentences(data):
sentences=[]
for index, row in data.iteritems() :
sentences.append(TaggedDocument(utils.to_unicode(row ).split() , ['Text' + '_%s' % str(index)]))
return sentences
def textClean(text):
text = re.sub(r"[^A-Za-z0-9^,!.\/'+-=]", " ", text)
text = text.lower().split()
stops = set(stopw... | for df in [train, test]:
df['is_male'] = np.where(df['Sex']=="male", 1, 0)
df['is_female'] = np.where(df['Sex']=="female", 1, 0)
df['EmbarkedS'] = np.where(df['Embarked']=="S", 1, 0)
df['EmbarkedC'] = np.where(df['Embarked']=="C", 1, 0)
df['EmbarkedQ'] = np.where(df['Embarked']=="Q", 1, 0)
df['Pclass1'] = np.where... | Titanic - Machine Learning from Disaster |
581,073 | all_sentences = train_question_body_sentences + \
train_answer_sentences + \
test_question_body_sentences + \
test_answer_sentences
Text_INPUT_DIM=128
text_model = Doc2Vec(min_count=1, window=5, vector_size=Text_INPUT_DIM, sample=1e-4, negative=5, workers=4, epochs=5,seed=1)
text_model.build_vocab(all_sentences)
text... | train_size = int(train.shape[0] * 0.85)
train_dataset = train[:train_size]
val_dataset = train[train_size:]
X_train = train_dataset.drop(labels=["Survived"], axis=1 ).values
Y_train = train_dataset["Survived"].values
X_val = val_dataset.drop(labels=["Survived"], axis=1 ).values
Y_val = val_dataset["Survived"].values
i... | Titanic - Machine Learning from Disaster |
581,073 | def normalize_sentence(tokens):
lemmatizer = WordNetLemmatizer()
lemmatized_sentence = []
for word, tag in pos_tag(tokens):
if tag.startswith('NN')or tag.startswith('PRP'):
pos = 'n'
elif tag.startswith('VB'):
pos = 'v'
else:
continue
pos = 'a'
lemmatized_sentence.append(lemmatizer.lemmatize(word, pos ).lower())
retur... | model = Sequential()
k_init = 'glorot_uniform'
optimizer = optimizers.Adam()
model.add(Dense(64,input_dim=input_size, kernel_initializer=k_init))
model.add(Activation("relu"))
model.add(Dropout(0.3))
model.add(Dense(64, kernel_initializer=k_init))
model.add(Activation("relu"))
model.add(Dropout(0.3))
model.add(Dense(1,... | Titanic - Machine Learning from Disaster |
581,073 | def normalize_vectorize(df, columns: list):
for col in columns:
print(col)
df[col+'_norm'] = df[col].apply(lambda x: ' '.join(set(normalize_sentence(word_tokenize(x)))))
df[col+'_vec'] = df[col].apply(lambda x: text_model.infer_vector([x]))
return df
train = normalize_vectorize(train, input_columns)
test = normalize... | y_final = model.predict_classes(test.values ).reshape(-1)
df_test = pd.read_csv(".. /input/test.csv")
output = pd.DataFrame({'PassengerId': df_test['PassengerId'], 'Survived': y_final})
surv_num = sum(output["Survived"] != 0)/ len(output)
print(f"Survive ratio: {surv_num}" ) | Titanic - Machine Learning from Disaster |
581,073 | try:
pbe = load_obj(".. /input/questembeddings/precomputed_bert_embeddings")
train_question_body_dense = pbe['train_question_body_dense']
train_answer_dense = pbe['train_answer_dense']
train_question_title_dense = pbe['train_question_title_dense']
test_question_body_dense = pbe['test_question_body_dense']
test_answer_... | output.to_csv('prediction-ann.csv', index=False)
output | Titanic - Machine Learning from Disaster |
4,549,939 | tfidf = TfidfVectorizer(ngram_range=(1, 3))
tsvd = TruncatedSVD(n_components = 128, n_iter=5)
tfquestion_title = tfidf.fit_transform(train["question_title"].values)
tfquestion_title_test = tfidf.transform(test["question_title"].values)
tfquestion_title = tsvd.fit_transform(tfquestion_title)
tfquestion_title_test = ... | from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import BatchNormalization
from keras.utils import np_utils
from keras.optimizers import Adam | Titanic - Machine Learning from Disaster |
4,549,939 | torch.cuda.empty_cache()<load_pretrained> | train_data=pd.read_csv('.. /input/train.csv' ).drop(columns=['PassengerId','Name','Ticket','Cabin'] ) | Titanic - Machine Learning from Disaster |
4,549,939 | try:
embeddings_train = load_obj(".. /input/questembeddings/use_embeddings_train")
embeddings_test = load_obj(".. /input/questembeddings/use_embeddings_test")
except:
print("Load failed, build embedding")
try:
module_url = INPUT_PATH+'universalsentenceencoderlarge4/'
embed = hub.load(module_url)
def UniversalEmbedd... | sum(train_data['Fare']==0 ) | Titanic - Machine Learning from Disaster |
4,549,939 | find = re.compile(r"^[^.]*")
train['netloc'] = train['url'].apply(lambda x: re.findall(find, urlparse(x ).netloc)[0])
test['netloc'] = test['url'].apply(lambda x: re.findall(find, urlparse(x ).netloc)[0])
features_lrg = ['category', 'netloc', 'question_user_name','answer_user_name','host']
features_sml = ['category'... | train_data.groupby(["Embarked", "Pclass"] ).Fare.mean() | Titanic - Machine Learning from Disaster |
4,549,939 | possible_features_train = [
[item for k, item in embeddings_train.items() ],
features_train,
features_train_lrg,
[ dist_features_train ],
[ [x for x in train.question_body_vec.values] ],
[ [x for x in train.question_title_vec.values] ],
[ [x for x in train.answer_vec.values] ],
[ train_question_body_dense ],
[ train_an... | train_data.loc[(train_data['Pclass'] == 1)&(train_data['Fare'] == 0.0),'Fare'] = 70.36
train_data.loc[(train_data['Pclass'] == 2)&(train_data['Fare'] == 0.0),'Fare'] = 20.33
train_data.loc[(train_data['Pclass'] == 3)&(train_data['Fare'] == 0.0),'Fare'] = 14.64 | Titanic - Machine Learning from Disaster |
4,549,939 | def bce(t,p):
return binary_crossentropy(t,p)
def custom_loss(true,pred):
bce = binary_crossentropy(true,pred)
return bce + logcosh(true,pred)
def swish(x):
return K.sigmoid(x)* x
def relu1(x):
return keras.activations.relu(x, alpha=0.0, max_value=1., threshold=0.0)
def create_model1(X_train):
input1 = Input(shape=... | train_data.Age.isna().sum() | Titanic - Machine Learning from Disaster |
4,549,939 | print(gc.collect() )<compute_test_metric> | means = train_data.groupby(['Sex', 'Pclass'] ).Age.mean()
train_data.Age = train_data.apply(lambda x: means[x.Sex][x.Pclass] if pd.isnull(x.Age)else x.Age, axis=1 ) | Titanic - Machine Learning from Disaster |
4,549,939 | def pearson_metric(y_true, y_pred):
y_true = K.clip(y_true, K.epsilon() , 1)
y_pred = K.clip(y_pred, K.epsilon() , 1)
y_true -= K.mean(y_true)
y_pred -= K.mean(y_pred)
y_true = K.l2_normalize(y_true, axis=-1)
y_pred = K.l2_normalize(y_pred, axis=-1)
pearson_correlation = K.sum(y_true * y_pred, axis=-1)
return 1-... | train_data['Sex'] = pd.Categorical(train_data['Sex'])
dfDummies = pd.get_dummies(train_data['Sex'], prefix = 'category')
train_data = pd.concat([train_data.drop(columns=['Sex']), dfDummies], axis=1)
train_data['Pclass'] = pd.Categorical(train_data['Pclass'])
dfDummies = pd.get_dummies(train_data['Pclass'], prefix =... | Titanic - Machine Learning from Disaster |
4,549,939 | error_pred_y = None
error_y = None
class SpearmanRhoCallback(Callback):
def __init__(self, training_data, validation_data, patience, model_name, reload=False):
global noise
self.x = training_data[0]
self.y = training_data[1]
self.x_val = validation_data[0]
self.y_val = validation_data[1]
self.patience = patience
self.v... | for i in range(len(train_data)) :
if train_data.loc[i, "SibSp"] + train_data.loc[i, "Parch"] == 0:
train_data.loc[i, "Alone"] = 1
else:
train_data.loc[i, "Alone"] = 0
train_data.Alone = train_data.Alone.astype(int ) | Titanic - Machine Learning from Disaster |
4,549,939 | all_predictions = []
model_idx =0
def run_model() :
global y_train,all_predictions, model_idx
X_train,X_test = get_train_test()
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1,
patience=7, min_lr=1e-6, verbose=1)
early_stop = EarlyStopping(monitor='val_loss',
min_delta=0,
patience=15,
mode='auto')
kf = K... | features = ['Age','SibSp','Parch','Fare','category_female','category_male','category_1','category_2','category_3','category_C','category_Q','category_S','Alone'] | Titanic - Machine Learning from Disaster |
4,549,939 | all_predictions = []
while len(all_predictions)< 20:
run_model()
<set_options> | y = train_data['Survived']
x = train_data.drop(columns=['Survived'] ) | Titanic - Machine Learning from Disaster |
4,549,939 | K.clear_session()
gc.collect()<prepare_output> | scaler = MinMaxScaler() | Titanic - Machine Learning from Disaster |
4,549,939 | test_preds = np.array([np.array([rankdata(c)for c in p.T] ).T for p in all_predictions] ).mean(axis=0)
max_val = test_preds.max() + 1
test_preds = test_preds/max_val + 1e-12<load_from_csv> | scaler.fit(x ) | Titanic - Machine Learning from Disaster |
4,549,939 | submission = pd.read_csv(INPUT_PATH+'google-quest-challenge/sample_submission.csv')
submission[targets] = test_preds
submission.head(20 )<save_to_csv> | x = scaler.transform(x ) | Titanic - Machine Learning from Disaster |
4,549,939 | submission.to_csv("submission.csv", index = False)
<import_modules> | x = pd.DataFrame(x, columns=features ) | Titanic - Machine Learning from Disaster |
4,549,939 | import numpy as np
import pandas as pd
from fastai import *
from fastai.vision import *<load_from_csv> | model = Sequential()
model.add(Dense(64, input_shape=(13,), activation='sigmoid'))
model.add(BatchNormalization())
model.add(Dropout(0.2))
model.add(Dense(64, activation='sigmoid'))
model.add(Dense(1, activation="sigmoid"))
model.compile(optimizer="adadelta", loss='binary_crossentropy', metrics=["binary_accuracy"])
| Titanic - Machine Learning from Disaster |
4,549,939 | data_folder = Path(".. /input/aerial-cactus-identification")
train_df = pd.read_csv(".. /input/aerial-cactus-identification/train.csv")
test_df = pd.read_csv(".. /input/aerial-cactus-identification/sample_submission.csv")
test_img = ImageList.from_df(test_df, path=data_folder/'test', folder='test')
trfm = get_trans... | model_result = model.fit(x, y, batch_size=100, epochs=200, validation_split= 0.2, shuffle = True ) | Titanic - Machine Learning from Disaster |
4,549,939 | learn = cnn_learner(train_img, models.resnet18, metrics=[error_rate, accuracy])
<train_model> | print("<-------Final Metrics------->")
print("Loss = ",model_result.history['val_loss'][199])
print("Accuracy = ",model_result.history['val_binary_accuracy'][199] ) | Titanic - Machine Learning from Disaster |
4,549,939 | lr = 3e-02
learn.fit_one_cycle(5, slice(lr))<save_to_csv> | test=pd.read_csv('.. /input/test.csv')
test_data=pd.read_csv('.. /input/test.csv' ).drop(columns=['PassengerId','Name','Ticket','Cabin'] ) | Titanic - Machine Learning from Disaster |
4,549,939 | preds,_ = learn.get_preds(ds_type=DatasetType.Test)
test_df.has_cactus = preds.numpy() [:, 0]
test_df.to_csv('submission.csv', index=False )<import_modules> | sum(test_data['Fare']==0 ) | Titanic - Machine Learning from Disaster |
4,549,939 | FileLink('submission.csv' )<load_from_csv> | test_data.groupby(["Embarked", "Pclass"] ).Fare.mean() | 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.