kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
11,847,709 | model = XGBRegressor(
max_depth=10,
booster='gbtree',
n_estimators=1000,
min_child_weight=0.5,
subsample=0.8,
sampling_method="uniform",
colsample_bynode=1,
colsample_bytree=0.8,
eta=0.1,
tree_method='gpu_hist',
seed=42)
model.fit(
X_train,
Y_train,
eval_metric="rmse",
eval_set=[(X_train, Y_train),(X_val, Y_val)],
v... | train.loc[train['PassengerId'] == 631, 'Age'] = 48
train.loc[train['PassengerId'] == 69, ['SibSp', 'Parch']] = [0,0]
test.loc[test['PassengerId'] == 1106, ['SibSp', 'Parch']] = [0,0] | Titanic - Machine Learning from Disaster |
11,847,709 | pickle.dump(model, open("model.pkl", "wb"))<load_pretrained> | train[["Sex", "Survived"]].groupby(['Sex'], as_index=False ).mean().sort_values(by='Survived', ascending=False ) | Titanic - Machine Learning from Disaster |
11,847,709 | loaded_model = pickle.load(open("model.pkl", "rb"))<load_from_csv> | def detect_outliers(df,n,features):
outlier_indices = []
for col in features:
Q1 = np.percentile(df[col], 25)
Q3 = np.percentile(df[col],75)
IQR = Q3 - Q1
outlier_step = 1.7 * IQR
outlier_list_col = df[(df[col] < Q1 - outlier_step)|(df[col] > Q3 + outlier_step)].index
outlier_indices.extend(outlier_list_col)
outli... | Titanic - Machine Learning from Disaster |
11,847,709 | test = pd.read_csv('.. /input/competitive-data-science-predict-future-sales/test.csv')
Y_test = loaded_model.predict(X_test ).clip(0, 20)
submission = pd.DataFrame({
"ID": test.index,
"item_cnt_month": Y_test
} )<load_from_csv> | df = pd.concat(( train.loc[:,'Pclass':'Embarked'], test.loc[:,'Pclass':'Embarked'])).reset_index(drop=True ) | Titanic - Machine Learning from Disaster |
11,847,709 | items=pd.read_csv("/kaggle/input/competitive-data-science-predict-future-sales/items.csv")
item_categories=pd.read_csv("/kaggle/input/competitive-data-science-predict-future-sales/item_categories.csv" )<merge> | survived = train.drop(train[train['Survived'] != 1].index)
not_survived = train.drop(train[train['Survived'] != 0].index)
basic_analysis(survived,not_survived ) | Titanic - Machine Learning from Disaster |
11,847,709 | df = pd.merge(items, item_categories)
df<save_to_csv> | def basic_details(df):
b = pd.DataFrame()
b['Missing value, %'] = round(df.isnull().sum() /df.shape[0]*100)
b['N unique value'] = df.nunique()
b['dtype'] = df.dtypes
return b
basic_details(df ) | Titanic - Machine Learning from Disaster |
11,847,709 | submission.to_csv('my_submission.csv', index=False )<import_modules> | df['Title'] = df.Name.str.extract('([A-Za-z]+)\.', expand=False)
df['Title'] = df['Title'].replace(['Lady', 'Countess','Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
df['Title'] = df['Title'].replace('Mlle', 'Miss')
df['Title'] = df['Title'].replace('Ms', 'Miss')
df['Title'] = df['T... | Titanic - Machine Learning from Disaster |
11,847,709 | import psutil
import joblib
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader<split> | def des_stat_feat(df):
df = pd.DataFrame(df)
dcol= [c for c in df.columns if df[c].nunique() >=10]
d_median = df[dcol].median(axis=0)
d_mean = df[dcol].mean(axis=0)
q1 = df[dcol].apply(np.float32 ).quantile(0.25)
q3 = df[dcol].apply(np.float32 ).quantile(0.75)
for c in dcol:
df[c+str('_median_range')] =(df[c].asty... | Titanic - Machine Learning from Disaster |
11,847,709 | env = riiideducation.make_env()
iter_test = env.iter_test()<define_variables> | def basic_details(df):
b = pd.DataFrame()
b['Missing value'] = df.isnull().sum()
b['N unique value'] = df.nunique()
b['dtype'] = df.dtypes
return b
basic_details(df ) | Titanic - Machine Learning from Disaster |
11,847,709 | MAX_SEQ = 100<define_search_model> | df = df.loc[:,~df.columns.duplicated() ] | Titanic - Machine Learning from Disaster |
11,847,709 | class FFN(nn.Module):
def __init__(self, state_size=200):
super(FFN, self ).__init__()
self.state_size = state_size
self.lr1 = nn.Linear(state_size, state_size)
self.relu = nn.ReLU()
self.lr2 = nn.Linear(state_size, state_size)
self.dropout = nn.Dropout(0.2)
def forward(self, x):
x = self.lr1(x)
x = self.relu(x)
x... | df.apply(lambda x: sum(x.isnull()),axis=0 ) | Titanic - Machine Learning from Disaster |
11,847,709 | skills = joblib.load("/kaggle/input/riiid-sakt-model-dataset-public/skills.pkl.zip")
n_skill = len(skills)
group = joblib.load("/kaggle/input/riiid-sakt-model-dataset-public/group.pkl.zip" )<load_pretrained> | from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import RobustScaler, StandardScaler
from sklearn.model_selection import train_test_split | Titanic - Machine Learning from Disaster |
11,847,709 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = SAKTModel(n_skill, embed_dim=128)
try:
model.load_state_dict(torch.load("/kaggle/input/riiid-sakt-model-dataset-public/sakt_model.pt"))
except:
model.load_state_dict(torch.load("/kaggle/input/riiid-sakt-model-dataset-public/sakt_model.pt", ... | le = LabelEncoder()
for col in df.select_dtypes('object' ).columns:
df[col] = le.fit_transform(df[col] ) | Titanic - Machine Learning from Disaster |
11,847,709 | prev_test_df = None
for(test_df, sample_prediction_df)in iter_test:
if(prev_test_df is not None)&(psutil.virtual_memory().percent < 90):
prev_test_df['answered_correctly'] = eval(test_df['prior_group_answers_correct'].iloc[0])
prev_test_df = prev_test_df[prev_test_df.content_type_id == False]
prev_group = prev_test_df... | X_train = df[:train.shape[0]]
X_test_fin = df[train.shape[0]:]
y = train.Survived
X_train['Y'] = y
df = X_train
df.head(20)
X = df.drop('Y', axis=1)
y = df.Y | Titanic - Machine Learning from Disaster |
11,847,709 | import gc
import random
from tqdm import tqdm
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
import seaborn as sns
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn_utils
from torch.autograd import Variable
from torch.util... | x_train, x_valid, y_train, y_valid = train_test_split(X, y, test_size=0.1, random_state=2020 ) | Titanic - Machine Learning from Disaster |
11,847,709 | MAX_SEQ = 160
<load_from_csv> | d_train = xgb.DMatrix(x_train, label=y_train)
d_valid = xgb.DMatrix(x_valid, label=y_valid)
d_test = xgb.DMatrix(X_test_fin)
params = {
'objective':'binary:logistic',
'max_depth':10,
'learning_rate':0.1,
'eval_metric':'auc',
'min_child_weight':1,
'subsample':0.64,
'colsample_bytree':0.4,
'seed':45,
'reg_lambda':2.79... | Titanic - Machine Learning from Disaster |
11,847,709 | %%time
dtype = {'timestamp':'int64',
'user_id':'int32' ,
'content_id':'int16',
'content_type_id':'int8',
'answered_correctly':'int8'}
train_df = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/train.csv', usecols=[1, 2, 3, 4, 7], dtype=dtype)
train_df.head()<sort_values> | accuracy = pd.DataFrame()
accuracy['predict'] = model.predict(d_valid)
accuracy['predict'] = accuracy['predict'].apply(lambda x: 1 if x>0.6 else 0)
accuracy_score(y_valid, accuracy['predict'] ) | Titanic - Machine Learning from Disaster |
11,847,709 | train_df = train_df[train_df.content_type_id == False]
train_df = train_df.sort_values(['timestamp'], ascending=True ).reset_index(drop = True )<count_unique_values> | sub = pd.DataFrame()
sub['PassengerId'] = test['PassengerId']
sub['Survived'] = model.predict(d_test)
sub['Survived'] = sub['Survived'].apply(lambda x: 1 if x>0.6 else 0 ) | Titanic - Machine Learning from Disaster |
11,847,709 | skills = train_df["content_id"].unique()
n_skill = len(skills)
print("number skills", len(skills))<groupby> | leaks = {
897:1,
899:1,
930:1,
932:1,
949:1,
987:1,
995:1,
998:1,
999:1,
1016:1,
1047:1,
1083:1,
1097:1,
1099:1,
1103:1,
1115:1,
1118:1,
1135:1,
1143:1,
1152:1,
1153:1,
1171:1,
1182:1,
1192:1,
1203:1,
1233:1,
1250:1,
1264:1,
1286:1,
935:0,
957:0,
972:0,
988:0,
1004:0,
1006:0,
1011:0,
1105:0,
1130:0,
1138:0,
1173:0,
128... | Titanic - Machine Learning from Disaster |
11,847,709 | <define_variables><EOS> | sub['Survived'] = sub.apply(lambda r: leaks[int(r['PassengerId'])] if int(r['PassengerId'])in leaks else r['Survived'], axis=1)
sub.to_csv('submission.csv', index=False)
sub.head() | Titanic - Machine Learning from Disaster |
10,773,116 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<define_variables> | warnings.filterwarnings("ignore" ) | Titanic - Machine Learning from Disaster |
10,773,116 | class SAKTDataset(Dataset):
def __init__(self, group, n_skill, max_seq=MAX_SEQ):
super(SAKTDataset, self ).__init__()
self.max_seq = max_seq
self.n_skill = n_skill
self.samples = group
self.user_ids = []
for user_id in group.index:
q, qa = group[user_id]
if len(q)< 2:
continue
self.user_ids.append(user_id)
def __len__... | df1 = pd.read_csv(".. /input/titanic/train.csv")
tf1 = pd.read_csv(".. /input/titanic/test.csv")
result = pd.read_csv(".. /input/titanic/gender_submission.csv" ) | Titanic - Machine Learning from Disaster |
10,773,116 | dataset = SAKTDataset(group, n_skill)
dataloader = DataLoader(dataset, batch_size=2048, shuffle=True, num_workers=8)
item = dataset.__getitem__(5)
<define_search_model> | df.isnull().sum() | Titanic - Machine Learning from Disaster |
10,773,116 | class FFN(nn.Module):
def __init__(self, state_size=200):
super(FFN, self ).__init__()
self.state_size = state_size
self.lr1 = nn.Linear(state_size, state_size)
self.relu = nn.ReLU()
self.lr2 = nn.Linear(state_size, state_size)
self.dropout = nn.Dropout(0.2)
def forward(self, x):
x = self.lr1(x)
x = self.relu(x)
x... | tf.isnull().sum() | Titanic - Machine Learning from Disaster |
10,773,116 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = SAKTModel(n_skill, embed_dim=128)
optimizer = torch.optim.Adam(model.parameters() , lr=1e-3)
criterion = nn.BCEWithLogitsLoss()
model.to(device)
criterion.to(device )<train_model> | df['Survived'].value_counts() | Titanic - Machine Learning from Disaster |
10,773,116 | def train_epoch(model, train_iterator, optim, criterion, device="cpu"):
model.train()
train_loss = []
num_corrects = 0
num_total = 0
labels = []
outs = []
tbar = tqdm(train_iterator)
for item in tbar:
x = item[0].to(device ).long()
target_id = item[1].to(device ).long()
label = item[2].to(device ).float()
optim.zero_g... | final = pd.concat([df,tf],axis = 0)
final.drop(['Survived'],axis = 1,inplace = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | epochs = 35
for epoch in range(epochs):
loss, acc, auc = train_epoch(model, dataloader, optimizer, criterion, device)
print("epoch - {} train_loss - {:.2f} acc - {:.3f} auc - {:.3f}".format(epoch, loss, acc, auc))<save_model> | index_NaN_age = list(final["Age"][final["Age"].isnull() ].index)
for i in index_NaN_age :
age_med = final["Age"].median()
age_pred = final["Age"][(( final['SibSp'] == final.iloc[i]["SibSp"])&(final['Parch'] == final.iloc[i]["Parch"])&(final['Pclass'] == final.iloc[i]["Pclass"])) ].median()
if not np.isnan(age_pred):
f... | Titanic - Machine Learning from Disaster |
10,773,116 | torch.save(model.state_dict() , "SAKT-HDKIM.pt" )<set_options> | final['Age'].isnull().sum() | Titanic - Machine Learning from Disaster |
10,773,116 | del dataset
gc.collect()<split> | final['Age'].fillna(final['Age'].median() ,inplace = True)
| Titanic - Machine Learning from Disaster |
10,773,116 | env = riiideducation.make_env()
iter_test = env.iter_test()<feature_engineering> | final['Fare'].isnull().sum() | Titanic - Machine Learning from Disaster |
10,773,116 | model.eval()
prev_test_df = None
for(test_df, sample_prediction_df)in tqdm(iter_test):
if(prev_test_df is not None)&(psutil.virtual_memory().percent<90):
print(psutil.virtual_memory().percent)
prev_test_df['answered_correctly'] = eval(test_df['prior_group_answers_correct'].iloc[0])
prev_test_df = prev_test_df[prev_te... | final["Fare"] = final["Fare"].fillna(final["Fare"].median())
| Titanic - Machine Learning from Disaster |
10,773,116 | import gc
import joblib
import pandas as pd
import numpy as np
import lightgbm as lgb<feature_engineering> | final["Fare"] = final["Fare"].map(lambda n: np.log(n)if n > 0 else 0)
| Titanic - Machine Learning from Disaster |
10,773,116 | def add_user_feats_without_update(df, answered_correctly_sum_u_dict, count_u_dict):
acsu = np.zeros(len(df), dtype=np.int32)
cu = np.zeros(len(df), dtype=np.int32)
for cnt,row in enumerate(df[['user_id']].values):
acsu[cnt] = answered_correctly_sum_u_dict[row[0]]
cu[cnt] = count_u_dict[row[0]]
user_feats_df = pd.Data... | new = final['Name'].str.split('.', n=1, expand = True)
final['First'] = new[0]
final['Last'] = new[1]
new1 = final['First'].str.split(',', n=1, expand = True)
final['Last Name'] = new1[0]
final['Title'] = new1[1]
new2 = final['Title'].str.split('', n=1, expand = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | answered_correctly_sum_u_dict = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/answered_correctly_sum_u_dict.pkl.zip")
count_u_dict = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/count_u_dict.pkl.zip")
questions_df = pd.read_feather('.. /input/lgbm-with-loop-feature-engineering... | final['Title'].value_counts() | Titanic - Machine Learning from Disaster |
10,773,116 | TARGET = 'answered_correctly'
FEATS = ['answered_correctly_avg_u', 'answered_correctly_sum_u', 'count_u',
'answered_correctly_avg_c', 'part', 'prior_question_had_explanation',
'prior_question_elapsed_time'
]<load_pretrained> | final.drop(['First','Last','Name','Last Name'],axis = 1,inplace = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | model = lgb.Booster(model_file=".. /input/lgbm-with-loop-feature-engineering-dataset/fold0_lgb_model.txt")
model.best_iteration = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/fold0_lgb_model_best_iteration.pkl.zip" )<load_pretrained> | final.replace(to_replace = [ ' Don', ' Rev', ' Dr', ' Mme',
' Major', ' Sir', ' Col', ' Capt',' Jonkheer'], value = ' Honorary(M)', inplace = True)
final.replace(to_replace = [ ' Ms', ' Lady', ' Mlle',' the Countess', ' Dona'], value = ' Honorary(F)', inplace = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | optimized_weights = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/optimized_weights.pkl.zip" )<feature_engineering> | df3 = final.copy()
df3 = df3[:891]
df3 = pd.concat([df3,df1['Survived']],axis = 1)
df3.head() | Titanic - Machine Learning from Disaster |
10,773,116 | class Iter_Valid(object):
def __init__(self, df, max_user=1000):
df = df.reset_index(drop=True)
self.df = df
self.user_answer = df['user_answer'].astype(str ).values
self.answered_correctly = df['answered_correctly'].astype(str ).values
df['prior_group_responses'] = "[]"
df['prior_group_answers_correct'] = "[]"
self.s... | final['Title'].value_counts() | Titanic - Machine Learning from Disaster |
10,773,116 | env = riiideducation.make_env()
iter_test = env.iter_test()
set_predict = env.predict<merge> | final = pd.get_dummies(final, columns = ["Title"] ) | Titanic - Machine Learning from Disaster |
10,773,116 | previous_test_df = None
for(test_df, sample_prediction_df)in iter_test:
if previous_test_df is not None:
previous_test_df[TARGET] = eval(test_df["prior_group_answers_correct"].iloc[0])
update_user_feats(previous_test_df, answered_correctly_sum_u_dict, count_u_dict)
previous_test_df = test_df.copy()
test_df = test_df[... | final["Family"] = final["SibSp"] + final["Parch"] + 1 | Titanic - Machine Learning from Disaster |
10,773,116 | import glob
import pandas as pd<define_variables> | final['Single'] = final['Family'].map(lambda s: 1 if s == 1 else 0)
final['SmallF'] = final['Family'].map(lambda s: 1 if s == 2 else 0)
final['MedF'] = final['Family'].map(lambda s: 1 if 3 <= s <= 4 else 0)
final['LargeF'] = final['Family'].map(lambda s: 1 if s >= 5 else 0 ) | Titanic - Machine Learning from Disaster |
10,773,116 | FILES = glob.glob('.. /input/*/prediction_*.csv', recursive=True)
FILES = [
'.. /input/mysample/tabular_6928.csv',
'.. /input/sub-blend/submission_945_15_folds.csv',
'.. /input/sub-blend/submission_945_5_folds.csv',
'.. /input/melanoma-sub-single-9516/submission_comb(1 ).csv',
'.. /input/train-cv-melanoma/submission.c... | final['Embarked'].fillna("S",inplace = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | sub = pd.read_csv(".. /input/siim-isic-melanoma-classification/sample_submission.csv")
del sub['target']
w = [0.05, 0.1, 0.1, 0.1, 0.15, 0.15, 0.15, 0.2]
<define_variables> | final = pd.get_dummies(final, columns = ["Embarked"], prefix="Embarked_from_" ) | Titanic - Machine Learning from Disaster |
10,773,116 | for counter, f in enumerate(FILES):
print(counter)
print(f )<load_from_csv> | final.Cabin.isnull().sum() | Titanic - Machine Learning from Disaster |
10,773,116 | df = pd.read_csv(f )<feature_engineering> | final.Cabin.value_counts() | Titanic - Machine Learning from Disaster |
10,773,116 | df.columns = ['image_name', str(counter)]
df[str(counter)] *= w[counter]
df.head()<merge> | final['Cabin_final'] = df['Cabin'].str[0] | Titanic - Machine Learning from Disaster |
10,773,116 | for counter, f in enumerate(FILES):
df = pd.read_csv(f)
df.columns = ['image_name', str(counter)]
df[str(counter)] *= w[counter]
sub = sub.merge(df, on="image_name" )<prepare_x_and_y> | final['Cabin_final'].fillna('Unknown',inplace = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | image_name = sub.image_name
sub = sub.drop(columns = ["image_name"])
target = sub.sum(axis = 1 )<save_to_csv> | final['Cabin_final'].value_counts() | Titanic - Machine Learning from Disaster |
10,773,116 | pd.DataFrame({
'image_name' : image_name,
'target' : target
} ).to_csv('submission_b.csv', index=False )<set_options> | final.drop(['Cabin'],axis = 1,inplace = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | warnings.filterwarnings('ignore' )<install_modules> | final = pd.get_dummies(final, columns = ["Cabin_final"],prefix="Cabin_" ) | Titanic - Machine Learning from Disaster |
10,773,116 | !pip install -q efficientnet<import_modules> | final.Ticket.value_counts() | Titanic - Machine Learning from Disaster |
10,773,116 | import tensorflow as tf
import tensorflow.keras.backend as K
import efficientnet.tfkeras as efn
from kaggle_datasets import KaggleDatasets<load_from_csv> | final['Ticket'] = final['Ticket'].astype(str)
final['Ticket_length'] = final.Ticket.apply(len)
final['Ticket_length'].astype(int)
final['Ticket_length'].unique() | Titanic - Machine Learning from Disaster |
10,773,116 | train = pd.read_csv("/kaggle/input/siim-isic-melanoma-classification/train.csv")
test = pd.read_csv("/kaggle/input/siim-isic-melanoma-classification/test.csv")
sample = pd.read_csv("/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv" )<define_variables> | final['Ticket_length'] = np.where(((final.Ticket_length == 3)|(final.Ticket_length == 4)|(final.Ticket_length == 5)) ,4,final.Ticket_length)
final['Ticket_length'] = np.where(((final.Ticket_length == 6)) ,5,final.Ticket_length)
final['Ticket_length'] = np.where(((final.Ticket_length == 7)|(final.Ticket_length == 8)|(... | Titanic - Machine Learning from Disaster |
10,773,116 | GCS_PATH = KaggleDatasets().get_gcs_path('melanoma-384x384')
GCS_PATH2 = KaggleDatasets().get_gcs_path('malignant-v2-384x384')
GCS_PATH3 = KaggleDatasets().get_gcs_path('isic2019-384x384')
filenames_train1 = tf.io.gfile.glob(GCS_PATH + '/train*.tfrec')
filenames_train2 = tf.io.gfile.glob(GCS_PATH2 + '/train%.2i*.tf... | final['Ticket_length'].value_counts() | Titanic - Machine Learning from Disaster |
10,773,116 | filenames_train = np.array(filenames_train1+filenames_train2+filenames_train3)
np.random.shuffle(filenames_train )<feature_engineering> | final['Ticket_length'] = final['Ticket_length'].astype(str)
final['Ticket_length'] = np.where(((final.Ticket_length == '4')) ,'Below 6',final.Ticket_length)
final['Ticket_length'] = np.where(((final.Ticket_length == '5')) ,'At 6',final.Ticket_length)
final['Ticket_length'] = np.where(((final.Ticket_length == '12')) ... | Titanic - Machine Learning from Disaster |
10,773,116 | AUTO = tf.data.experimental.AUTOTUNE<set_options> | conversion = pd.get_dummies(final.Ticket_length, prefix = 'Ticket Length')
final = pd.concat([final , conversion], axis = 1)
final.drop(['Ticket','Ticket_length'],axis = 1, inplace = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | cfg = dict(
batch_size=32,
img_size=384,
lr_start=0.000005,
lr_max=0.00000125,
lr_min=0.000001,
lr_rampup=5,
lr_sustain=0,
lr_decay=0.8,
epochs=12,
transform_prob=1.0,
rot=180.0,
shr=2.0,
hzoom=8.0,
wzoom=8.0,
hshift=8.0,
wshift=8.0,
optimizer='adam',
label_smooth_fac=0.05,
tta_steps=20
)<normalization> | final = pd.get_dummies(final, columns = ["Sex"],prefix="Gender_" ) | Titanic - Machine Learning from Disaster |
10,773,116 | def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
shear = math.pi * shear / 180.
c1 = tf.math.cos(rotation)
s1 = tf.math.sin(rotation)
one = tf.constant([1], dtype='float32')
zero = tf.constant([0], dtype='float32')
rotation_matrix = tf.reshape(... | final.head()
final.drop(['PassengerId'],axis = 1,inplace = True)
final.drop(['SibSp','Parch','Family'],axis = 1,inplace = True ) | Titanic - Machine Learning from Disaster |
10,773,116 | def transform(image, cfg):
DIM = cfg['img_size']
XDIM = DIM % 2
rot = cfg['rot'] * tf.random.normal([1], dtype='float32')
shr = cfg['shr'] * tf.random.normal([1], dtype='float32')
h_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ cfg['hzoom']
w_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ cfg['wzoom']
h_... | final.isnull().sum() | Titanic - Machine Learning from Disaster |
10,773,116 | def dropout(image, DIM=384, PROBABILITY = 0.75, CT = 8, SZ = 0.2):
P = tf.cast(tf.random.uniform([],0,1)<PROBABILITY, tf.int32)
if(P==0)|(CT==0)|(SZ==0): return image
for k in range(CT):
x = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
y = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
WIDTH = tf.cast(SZ*DIM,tf.int3... | correlation = final.copy()
sur = pd.concat([df['Survived'],result['Survived']],axis = 0)
correlation = pd.concat([correlation,sur],axis = 1 ) | Titanic - Machine Learning from Disaster |
10,773,116 | def prepare_image(img, cfg=None,droprate=0.5,dropct=8,dropsize=0.2):
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, [cfg['img_size'], cfg['img_size']],
antialias=True)
img = tf.cast(img, tf.float32)/ 255.0
if cfg['transform_prob'] > tf.random.uniform([1], minval=0, maxval=1):
img = transform(i... | from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn import svm
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import MultinomialNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble... | Titanic - Machine Learning from Disaster |
10,773,116 | def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'image_name': tf.io.FixedLenFeature([], tf.string),
'target': tf.io.FixedLenFeature([], tf.int64)
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
return example['image'], example['target']... | x_train = final[:891]
feature_scaler = MinMaxScaler()
x_train = feature_scaler.fit_transform(x_train ) | Titanic - Machine Learning from Disaster |
10,773,116 | def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'image_name': tf.io.FixedLenFeature([], tf.string)
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
return example['image'], example['image_name']
<count_values> | y_train = final[891:]
feature_scaler = MinMaxScaler()
y_train = feature_scaler.fit_transform(y_train ) | Titanic - Machine Learning from Disaster |
10,773,116 | def count_data_items(filenames):
n = [
int(re.compile(r'-([0-9]*)\.' ).search(filename ).group(1))
for filename in filenames
]
return np.sum(n )<create_dataframe> | x_test = df1['Survived'] | Titanic - Machine Learning from Disaster |
10,773,116 | def getTrainDataset(files, cfg):
ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)
ds = ds.cache()
opt = tf.data.Options()
opt.experimental_deterministic = False
ds = ds.with_options(opt)
ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)
ds = ds.repeat()
ds = ds.shuffle(2048)
ds = ds.map(lambda... | y_test = result['Survived'] | Titanic - Machine Learning from Disaster |
10,773,116 | def getTestDataset(files, cfg, augment=False, repeat=False):
ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)
ds = ds.cache()
if repeat:
ds = ds.repeat()
ds = ds.map(read_unlabeled_tfrecord, num_parallel_calls=AUTO)
ds = ds.map(lambda img, idnum:
(prepare_image(img, cfg=cfg), idnum),
num_parallel_calls=A... | accuracy = []
estimator = [] | Titanic - Machine Learning from Disaster |
10,773,116 | def getLearnRateCallback(cfg):
lr_start = cfg['lr_start']
lr_max = cfg['lr_max'] * strategy.num_replicas_in_sync * cfg['batch_size']
lr_min = cfg['lr_min']
lr_rampup = cfg['lr_rampup']
lr_sustain = cfg['lr_sustain']
lr_decay = cfg['lr_decay']
def lrfn(epoch):
if epoch < lr_rampup:
lr =(lr_max - lr_start)/ lr_rampup * e... | LR = LogisticRegression()
estimator.append(( 'LR',LogisticRegression()))
cv = cross_val_score(LR,x_train,x_test,cv=10)
accuracy1 = cv.mean()
accuracy.append(accuracy1)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | with strategy.scope() :
model_input = tf.keras.Input(shape=(cfg['img_size'], cfg['img_size'], 3),
name='img_input')
dummy = tf.keras.layers.Lambda(lambda x: x )(model_input)
outputs = []
x = efn.EfficientNetB3(include_top=False,
weights='noisy-student',
input_shape=(cfg['img_size'], cfg['img_size'], 3),
pooling='avg'... | LR.fit(x_train,x_test)
model1pred = LR.predict(y_train)
submission1 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission1['PassengerId'] = result['PassengerId']
submission1['Survived'] = model1pred
submission1.to_csv('LogisticRegression(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | ds_train = getTrainDataset(filenames_train, cfg ).map(lambda img, label:(img,(label, label, label)))
stepsTrain = count_data_items(filenames_train)/(cfg['batch_size'] * strategy.num_replicas_in_sync )<train_model> | LR.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | callbacks = [getLearnRateCallback(cfg)]
history = model.fit(ds_train,
validation_data=None,
verbose=1,
steps_per_epoch=stepsTrain,
validation_steps=0,
epochs=10,
callbacks=callbacks )<predict_on_test> | SVC = LinearSVC()
cv = cross_val_score(SVC,x_train,x_test,cv=10)
accuracy2 = cv.mean()
accuracy.append(accuracy2)
print(cv)
print(cv.mean())
| Titanic - Machine Learning from Disaster |
10,773,116 | steps = count_data_items(filenames_test)/(cfg['batch_size'] * strategy.num_replicas_in_sync)
z = np.zeros(( cfg['batch_size'] * strategy.num_replicas_in_sync))
ds_testAug = getTestDataset(filenames_test, cfg, augment=True,
repeat=True ).map(lambda img, label:(img,(z, z, z)))
probs = model.predict(ds_testAug, verbose=... | SVC.fit(x_train,x_test)
SVC.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | probs = np.stack(probs)
probs = probs[:, :count_data_items(filenames_test)* cfg['tta_steps']]
probs = np.stack(np.split(probs, cfg['tta_steps'], axis=1), axis=1)
probs = np.mean(probs, axis=1 )<save_to_csv> | SVC.fit(x_train,x_test)
model2pred = SVC.predict(y_train)
submission2 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission2['PassengerId'] = result['PassengerId']
submission2['Survived'] = model2pred
submission2.to_csv('LinearSVC(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | y_test_sorted = np.zeros(( 3, probs.shape[1]))
test = test.reset_index()
test = test.set_index('image_name')
i = 0
ds_test = getTestDataset(filenames_test, cfg)
for img, imgid in tqdm(iter(ds_test.unbatch())) :
imgid = imgid.numpy().decode('utf-8')
y_test_sorted[:, test.loc[imgid]['index']] = probs[:, i, 0]
i += 1
f... | poly = svm.SVC(kernel = 'poly', gamma = 'scale')
cv = cross_val_score(poly,x_train,x_test,cv=10)
accuracy3 = cv.mean()
accuracy.append(accuracy3)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | !gzip model_0.csv
!gzip model_1.csv
!gzip model_2.csv
!gzip ensembled.csv<import_modules> | poly.fit(x_train,x_test)
poly.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | import numpy as np
import pandas as pd<load_from_csv> | model3pred = poly.predict(y_train)
submission3 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission3['PassengerId'] = result['PassengerId']
submission3['Survived'] = model3pred
submission3.to_csv('PolynomialSVC(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | data1 = pd.read_csv('.. /input/minmax-ensemble-0-9526-lb/submission.csv')
data2 = pd.read_csv('.. /input/stacking-ensemble-on-my-submissions/submission_mean.csv')
data3 = pd.read_csv('.. /input/stacking-ensemble-on-my-submissions/submission_median.csv')
data4 = pd.read_csv('.. /input/analysis-of-melanoma-metadata-an... | DT = DecisionTreeClassifier(random_state = 5)
estimator.append(( 'DT',DecisionTreeClassifier(random_state = 5)))
cv = cross_val_score(DT,x_train,x_test,cv=10)
accuracy4 = cv.mean()
accuracy.append(accuracy4)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | submission['target'] = 2/6 * data1['target'] + 1/6 * data2['target'] + 1/6 * data3['target'] + 1/6 * data4['target'] + 1/6 * data5['target']<save_to_csv> | DT.fit(x_train,x_test)
DT.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | submission.to_csv('submission.csv', index=False, float_format='%.6f' )<install_modules> | model4pred = DT.predict(y_train)
submission4 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission4['PassengerId'] = result['PassengerId']
submission4['Survived'] = model4pred
submission4.to_csv('Decision Tree(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | !pip install -q efficientnet
!pip install -q git+https://github.com/AmedeoBiolatti/dsqol<import_modules> | GNB = GaussianNB()
estimator.append(( 'GNB',GaussianNB()))
cv = cross_val_score(GNB,x_train,x_test,cv=10)
accuracy5 = cv.mean()
accuracy.append(accuracy5)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | import os, re, time, tqdm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import metrics, model_selection
import tensorflow as tf
import tensorflow_addons as tfa
from tensorflow import keras
from tensorflow.keras import backend as K
from efficientnet import tfkeras as efnet
from kagg... | GNB.fit(x_train,x_test)
GNB.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | from dsqol.tf import imgaug
from dsqol.tf.data import balance
from dsqol.tf.utils import average
from dsqol.tf import losses<init_hyperparams> | model5pred = GNB.predict(y_train)
submission5 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission5['PassengerId'] = result['PassengerId']
submission5['Survived'] = model5pred
submission5.to_csv('Gaussian NB(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | SEED = 42
tf.random.set_seed(SEED)
np.random.seed(SEED)
TIME_BUDGET = 2.5 * 3600
FOLDS = 5
INCLUDE_2019 = 0
INCLUDE_2018 = 1
INCLUDE_MALIGNANT = 0
IMG_READ_SIZE = 512
IMG_SIZE = 512
BALANCE_POS_RATIO = 0.08
EFF_NET = 5
LOSS_TYPE = 'BCE'
LOSS_PARAMS = dict(label_smoothing=0.05)
BATCH_SIZE = 32
EPOCHS = 20
TBM = 6
TTA... | MNB = MultinomialNB()
estimator.append(( 'MNB',MultinomialNB()))
cv = cross_val_score(MNB,x_train,x_test,cv=10)
accuracy6 = cv.mean()
accuracy.append(accuracy6)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | DEVICE = "TPU"
print("connecting to TPU...")
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
except ValueError:
print("Could not connect to TPU")
tpu = None
if tpu:
try:
print("initializing TPU...")
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experime... | MNB.fit(x_train,x_test)
MNB.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | GCS_PATH1 = KaggleDatasets().get_gcs_path('melanoma-%ix%i' %(IMG_READ_SIZE, IMG_READ_SIZE))
GCS_PATH2 = KaggleDatasets().get_gcs_path('isic2019-%ix%i' %(IMG_READ_SIZE, IMG_READ_SIZE))
GCS_PATH3 = KaggleDatasets().get_gcs_path('malignant-v2-%ix%i' %(IMG_READ_SIZE, IMG_READ_SIZE))<load_from_csv> | MNB.fit(x_train,x_test)
model6pred = MNB.predict(y_train)
submission6 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission6['PassengerId'] = result['PassengerId']
submission6['Survived'] = model6pred
submission6.to_csv('MultinomialNB(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | df_base_train = pd.read_csv(".. /input/siim-isic-melanoma-classification/train.csv")
df_base_test = pd.read_csv(".. /input/siim-isic-melanoma-classification/test.csv" )<define_variables> | RF = RandomForestClassifier(random_state = 5)
estimator.append(( 'RF',RandomForestClassifier(random_state = 5)))
cv = cross_val_score(RF,x_train,x_test,cv=10)
accuracy7 = cv.mean()
accuracy.append(accuracy7)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | train_files = tf.io.gfile.glob(os.path.join(GCS_PATH1, "train*.tfrec"))
if INCLUDE_2019:
train_files += tf.io.gfile.glob([os.path.join(GCS_PATH2, "train%.2i*.tfrec" % i)for i in range(1, 30, 2)])
if INCLUDE_2018:
train_files += tf.io.gfile.glob([os.path.join(GCS_PATH2, "train%.2i*.tfrec" % i)for i in range(0, 30, 2)])... | RF.fit(x_train,x_test)
RF.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | test_files = tf.io.gfile.glob(os.path.join(GCS_PATH1, "test*.tfrec"))
print("%d test files found" % len(test_files))<prepare_x_and_y> | RF.fit(x_train,x_test)
model7pred = RF.predict(y_train)
submission7 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission7['PassengerId'] = result['PassengerId']
submission7['Survived'] = model7pred
submission7.to_csv('RandomForest(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | def read_labeled_tfrecord(example):
tfrec_format = {
'image' : tf.io.FixedLenFeature([], tf.string),
'image_name' : tf.io.FixedLenFeature([], tf.string),
'target' : tf.io.FixedLenFeature([], tf.int64)
}
example = tf.io.parse_single_example(example, tfrec_format)
return example['image'], example['target']
def read_unl... | GBC = GradientBoostingClassifier(random_state = 5)
estimator.append(( 'GBC',GradientBoostingClassifier(random_state = 5)))
cv = cross_val_score(GBC,x_train,x_test,cv=10)
accuracy8 = cv.mean()
accuracy.append(accuracy8)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | def dropout(image, DIM=256, PROBABILITY = 0.75, CT = 8, SZ = 0.2):
P = tf.cast(tf.random.uniform([],0,1)<PROBABILITY, tf.int32)
if(P==0)|(CT==0)|(SZ==0):
return image
for k in range(CT):
x = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
y = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
WIDTH = tf.cast(SZ*DIM,tf.int3... | GBC.fit(x_train,x_test)
GBC.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | AUG_BS = 64
def base_aug(img):
img = tf.image.random_flip_left_right(img)
img = tf.image.random_saturation(img, 0.7, 1.3)
img = tf.image.random_contrast(img, 0.8, 1.2)
img = tf.image.random_brightness(img, 0.1)
return img
dropout_aug = lambda img, o: dropout(img, DIM=IMG_READ_SIZE, PROBABILITY=0.75, CT=8, SZ=0.15)
... | GBC.fit(x_train,x_test)
model8pred = GBC.predict(y_train)
submission8 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission8['PassengerId'] = result['PassengerId']
submission8['Survived'] = model8pred
submission8.to_csv('GradientBoosting(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | def get_dataset(files, augment=False, repeat=False, shuffle=False, labeled=True, batch_size=16, drop_remainder=False,
dim=256, read_dim=None
)-> tf.data.Dataset:
if read_dim is None:
read_dim = dim
ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)
ds = ds.cache()
if repeat:
ds = ds.repeat()
if shuffle:
ds ... | XGB = XGBClassifier(random_state = 5)
estimator.append(( 'XGB', XGBClassifier(random_state = 5)))
cv = cross_val_score(XGB,x_train,x_test,cv=10)
accuracy9 = cv.mean()
accuracy.append(accuracy9)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | def show_dataset(thumb_size, cols, rows, ds):
mosaic = PIL.Image.new(mode='RGB', size=(thumb_size*cols +(cols-1),
thumb_size*rows +(rows-1)))
for idx, data in enumerate(iter(ds)) :
img, target_or_imgid = data
ix = idx % cols
iy = idx // cols
img = np.clip(img.numpy() * 255, 0, 255 ).astype(np.uint8)
img = PIL.Image.f... | XGB.fit(x_train,x_test)
XGB.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | show_dataset(128, 8, 2, get_balanced_dataset(train_files, augment=[dropout_aug], cw_augment=[cw_mixup_aug] ).take(10 ).unbatch() )<choose_model_class> | XGB.fit(x_train,x_test)
model9pred = XGB.predict(y_train)
submission9 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission9['PassengerId'] = result['PassengerId']
submission9['Survived'] = model9pred
submission9.to_csv('XGBoosting(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | def build_model(dim=128, ef=0):
inp = keras.layers.Input(shape=(dim,dim,3))
base = getattr(efnet, 'EfficientNetB%d' % ef )(input_shape=(dim, dim, 3), weights='imagenet', include_top=False)
x = base(inp)
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dense(1 )(x)
x = keras.layers.Activation('sigmoid',... | KNN = KNeighborsClassifier(n_neighbors = 11)
estimator.append(( 'KNN',KNeighborsClassifier(n_neighbors = 11)))
cv = cross_val_score(KNN,x_train,x_test,cv=10)
accuracy10 = cv.mean()
accuracy.append(accuracy10)
print(cv)
print(cv.mean() ) | Titanic - Machine Learning from Disaster |
10,773,116 | mult = 1
lr_start = 5e-6
lr_max = 1.25e-6 * GLOBAL_BATCH_SIZE
lr_min = 1e-6
lr_ramp_ep = 5
lr_sus_ep = 0
lr_decay = 0.8
def lrfn(epoch):
if epoch < lr_ramp_ep:
lr =(lr_max - lr_start)/ lr_ramp_ep * epoch + lr_start
elif epoch < lr_ramp_ep + lr_sus_ep:
lr = lr_max
else:
lr =(lr_max - lr_min)* lr_decay**(epoch - lr_ramp_... | KNN.fit(x_train,x_test)
KNN.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | CKPT_FOLDER = ".. /working/ckpt"
if not os.path.exists(CKPT_FOLDER):
os.mkdir(CKPT_FOLDER)
folds = list(model_selection.KFold(n_splits=FOLDS, shuffle=True, random_state=SEED ).split(np.arange(15)))
testiness = pd.read_csv(".. /input/spicv-spicy-vi-make-your-cv-more-testy/testiness.csv")
TOTAL_POS = 581 + 2858 * INCL... | KNN.fit(x_train,x_test)
model10pred = KNN.predict(y_train)
submission10 = pd.DataFrame(columns = ['PassengerId','Survived'])
submission10['PassengerId'] = result['PassengerId']
submission10['Survived'] = model10pred
submission10.to_csv('KNN(No HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | VERBOSE = 1
PLOT = 1
histories = []
df_oof = pd.DataFrame() ; df_res = pd.DataFrame()
t_start = time.time()
for fold,(idTrain, idValid)in enumerate(folds):
print("
print(( "
print("
if DEVICE == 'TPU':
if tpu:
tf.tpu.experimental.initialize_tpu_system(tpu)
fold_valid_files = [f for f in train_files if any([int(re.matc... | Models = ['Logistic Regression','Linear SVM','Polynomial SVM','Decision Tree','Gaussian NB','Multinomial NB','Random Forest Classifier','Gradient Boost Classifier','XG Boosting','K-Nearest Neighbors']
total = list(zip(Models,accuracy))
output1 = pd.DataFrame(total, columns = ['Models','Accuracy'])
| Titanic - Machine Learning from Disaster |
10,773,116 |
<merge> | vot_soft = VotingClassifier(estimators = estimator, voting ='soft')
vot_soft.fit(x_train, x_test)
y_pred = vot_soft.predict(y_train)
vot_soft.score(y_train,y_test ) | Titanic - Machine Learning from Disaster |
10,773,116 | xxx = df_oof.groupby('image_name' ).mean().reset_index().merge(df_base_train, on='image_name')
print("OOF AUC(TTA %d)= %.4f" %(TTA, metrics.roc_auc_score(xxx.target, xxx.pred)) )<save_to_csv> | modelpred1 = vot_soft.predict(y_train)
sub1 = pd.DataFrame(columns = ['PassengerId','Survived'])
sub1['PassengerId'] = result['PassengerId']
sub1['Survived'] = modelpred1
sub1.to_csv('SoftVoting(NO HT ).csv',index = False ) | Titanic - Machine Learning from Disaster |
10,773,116 | df_res.to_csv('.. /working/test_res_all.csv', index=False)
df_oof.to_csv('.. /working/oof_res_all.csv', index=False )<save_to_csv> | vot_hard = VotingClassifier(estimators = estimator, voting ='hard')
vot_hard.fit(x_train, x_test)
y_pred = vot_hard.predict(y_train)
vot_hard.score(y_train,y_test ) | 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.