kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
6,670,250 | submission_1 = pd.read_csv('.. /input/siim-isic-melanoma-classification/sample_submission.csv')
submission_1[LABELS] = predictions
submission_2 = pd.read_csv('.. /input/siim-isic-melanoma-classification/sample_submission.csv')
submission_2[LABELS] = predictions_2
submission = pd.read_csv('.. /input/siim-isic-melanoma... | X_test = test.drop('Survived', axis=1 ).values
| Titanic - Machine Learning from Disaster |
6,670,250 | !pip install -q efficientnet >> /dev/null
<define_variables> | log_params = dict(
C = np.logspace(-5, 8, 15),
penalty = ['l1', 'l2']
) | Titanic - Machine Learning from Disaster |
6,670,250 | DEVICE = "TPU"
SEED = 42
FOLDS = 5
IMG_SIZES = [256]*FOLDS
DROP_FREQ = [0.5]*FOLDS
DROP_CT = [10]*FOLDS
DROP_SIZE = [0.1]*FOLDS
INC2019 = [0]*FOLDS
INC2018 = [1]*FOLDS
M1 = [1]*FOLDS
M2 = [1]*FOLDS
M3 = [0]*FOLDS
M4 = [1]*FOLDS
BATCH_SIZES = [32]*FOLDS
EPOCHS = [12]*FOLDS
EFF_NETS = [6]*FOLDS
WGTS = [1/FOLDS]*FOLDS
TTA... | log = LogisticRegression()
logreg_cv = GridSearchCV(estimator=log, param_grid=log_params, cv=5)
logreg_cv.fit(X, y ) | Titanic - Machine Learning from Disaster |
6,670,250 | if 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.exp... | print("Tuned Logistic Regression Parameters: {}".format(logreg_cv.best_params_))
print("Best score is {}".format(logreg_cv.best_score_)) | Titanic - Machine Learning from Disaster |
6,670,250 | GCS_PATH = [None]*FOLDS; GCS_PATH2 = [None]*FOLDS; GCS_PATH3 = [None]*FOLDS
for i,k in enumerate(IMG_SIZES[:FOLDS]):
GCS_PATH[i] = KaggleDatasets().get_gcs_path('melanoma-%ix%i'%(k,k))
GCS_PATH2[i] = KaggleDatasets().get_gcs_path('isic2019-%ix%i'%(k,k))
GCS_PATH3[i] = KaggleDatasets().get_gcs_path('malignant-v2-%ix%i'%... | log_pred = logreg_cv.predict(X_test ) | Titanic - Machine Learning from Disaster |
6,670,250 | ROT_ = 180.0; SHR_ = 2.0
HZOOM_ = 8.0; WZOOM_ = 8.0
HSHIFT_ = 8.0; WSHIFT_ = 8.0
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
shear = math.pi * shear / 180.
def get_3x3_mat(lst):
return tf.reshape(tf.concat([lst],axis=0), [3,3])
c1 = tf.math.c... | forrest_params = dict(
max_depth = [n for n in range(9, 14)],
min_samples_split = [n for n in range(4, 11)],
min_samples_leaf = [n for n in range(2, 5)],
n_estimators = [n for n in range(10, 60, 10)],
) | Titanic - Machine Learning from Disaster |
6,670,250 | 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... | forrest = RandomForestClassifier() | Titanic - Machine Learning from Disaster |
6,670,250 | def read_labeled_tfrecord(example):
tfrec_format = {
'image' : tf.io.FixedLenFeature([], tf.string),
'image_name' : tf.io.FixedLenFeature([], tf.string),
'patient_id' : tf.io.FixedLenFeature([], tf.int64),
'sex' : tf.io.FixedLenFeature([], tf.int64),
'age_approx' : tf.io.FixedLenFeature([], tf.int64),
'anatom_site_gene... | forest_cv = GridSearchCV(estimator=forrest, param_grid=forrest_params, cv=5)
forest_cv.fit(X, y ) | Titanic - Machine Learning from Disaster |
6,670,250 | def get_dataset(files, augment = False, shuffle = False, repeat = False,
labeled=True, return_image_names=True, batch_size=16, dim=256,
droprate=0, dropct=0, dropsize=0):
ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)
ds = ds.cache()
if repeat:
ds = ds.repeat()
if shuffle:
ds = ds.shuffle(1024*2)
opt = ... | print("Best score: {}".format(forest_cv.best_score_))
print("Optimal params: {}".format(forest_cv.best_estimator_)) | Titanic - Machine Learning from Disaster |
6,670,250 | 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... | forrest_pred = forest_cv.predict(X_test)
print(forrest_pred ) | Titanic - Machine Learning from Disaster |
6,670,250 | EFNS = [efn.EfficientNetB0, efn.EfficientNetB1, efn.EfficientNetB2, efn.EfficientNetB3,
efn.EfficientNetB4, efn.EfficientNetB5, efn.EfficientNetB6]
def build_model(dim=128, ef=0):
inp = tf.keras.layers.Input(shape=(dim,dim,3))
base = EFNS[ef](input_shape=(dim,dim,3),weights='imagenet',include_top=False)
x = base(inp)
... | kaggle = pd.DataFrame({'PassengerId': passengerId, 'Survived': forrest_pred} ) | Titanic - Machine Learning from Disaster |
6,670,250 | def get_lr_callback(batch_size=8):
lr_start = 0.000005
lr_max = 0.00000125 * REPLICAS * batch_size
lr_min = 0.000001
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_m... | filename = 'submit.csv'
kaggle.to_csv(filename, index=False ) | Titanic - Machine Learning from Disaster |
847,197 | %.2f'%y,size=14)
\
<define_variables> | train=pd.read_csv('.. /input/train.csv')
test=pd.read_csv('.. /input/test.csv' ) | Titanic - Machine Learning from Disaster |
847,197 | VERBOSE = 0
DISPLAY_PLOT = True
oof_pred = []; oof_tar = []; oof_val = []; oof_names = []; oof_folds = []
preds = np.zeros(( count_data_items(files_test),1))
skf = KFold(n_splits=FOLDS,shuffle=True,random_state=SEED)
oof_pred = []; oof_tar = []; oof_val = []; oof_names = []; oof_folds = []
preds = np.zeros(( count_dat... | train.drop(labels='Cabin',inplace=True,axis=1)
test.drop(labels='Cabin',inplace=True,axis=1)
| Titanic - Machine Learning from Disaster |
847,197 | oof = np.concatenate(oof_pred); true = np.concatenate(oof_tar);
names = np.concatenate(oof_names); folds = np.concatenate(oof_folds)
auc = roc_auc_score(true,oof)
print('Overall OOF AUC with TTA = %.3f'%auc)
df_oof = pd.DataFrame(dict(
image_name = names, target=true, pred = oof, fold=folds))
df_oof.to_csv('oof.csv... | def check_class(x):
if pd.isnull(x['Age']):
return pmean[x['Pclass']]
return x['Age']
pmean=train.groupby('Pclass' ).mean() ['Age']
train['Age']=train.apply(check_class,axis=1)
test['Age']=test.apply(check_class,axis=1)
| Titanic - Machine Learning from Disaster |
847,197 | if INFER_TEST:
ds = get_dataset(files_test, augment=False, repeat=False, dim=IMG_SIZES[fold],
labeled=False, return_image_names=True)
image_names = np.array([img_name.numpy().decode("utf-8")
for img, img_name in iter(ds.unbatch())])
submission = pd.DataFrame(dict(image_name=image_names, target=preds[:,0]))
submissio... | test['Fare']=test['Fare'].fillna(np.mean(test['Fare'])).astype(float)
| Titanic - Machine Learning from Disaster |
847,197 | train = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/train.csv')
test = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/test.csv')
sub = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/sample_submission.csv')
<define_variables> | vtrain=train
vtest=test | Titanic - Machine Learning from Disaster |
847,197 | models = [ "getting-started-with-tfrecords", "melanoma-efficientnetb6-with-attention-mechanism", "triple-stratified-kfold-with-tfrecords"]
models = ["384-E6-with-2018","512-E6","768-E2","512-E5","effb3-fulldata-upsample","effb2-fulldata-upsample"]
models = ["effb0-fulldata-upsample","effb1-fulldata-upsample","effb2-512... | train=train.loc[:,['Pclass','Survived','Sex','Age','SibSp','Parch','Fare','Embarked']]
test=test.loc[:,['Pclass','Sex','Age','SibSp','Parch','Fare','Embarked']] | Titanic - Machine Learning from Disaster |
847,197 | train["pred_rank"] = 0
train["pred_power"] = 0
train["pred_avg"] = 0
for c in models:
train["pred_rank"] += train[c].rank() / train[c].rank().max()
train["pred_power"] += np.power(train[c],2)/np.power(train[c],2 ).max()
train["pred_avg"] += train [c]/train [c].max()
train["pred_rank"] = train["pred_rank"]/len(models)
... | pc=pd.get_dummies(train['Pclass'],drop_first=True,prefix='pclass')
pctest=pd.get_dummies(test['Pclass'],drop_first=True,prefix='pclass')
sex=pd.get_dummies(train['Sex'],drop_first=True,prefix='sex')
sextest=pd.get_dummies(test['Sex'],drop_first=True,prefix='sex')
em=pd.get_dummies(train['Embarked'],drop_first=True)... | Titanic - Machine Learning from Disaster |
847,197 | test["target"] = 0.0
for c in models:
test["target"] += test[c].rank() / test[c].rank().max()
test["target"] = test["target"]/len(models)
sub = test[["image_name","target"]]
sub.to_csv("submission_rank.csv",index=False)
sub.head()<save_to_csv> | def fill(x):
for i in range(len(unique_surnames_train)) :
if unique_surnames_train[i] in x:
return i
extratrain=pd.get_dummies(vtrain["Name"].apply(fill ).replace(np.arange(len(unique_surnames_train)) ,unique_surnames_train),drop_first=True)
extratest=pd.get_dummies(vtest["Name"].apply(fill ).replace(np.arange(len(uni... | Titanic - Machine Learning from Disaster |
847,197 | test["target"] = 0.0
for c in models:
test["target"] += np.power(test[c],2)/np.power(test[c],2 ).max()
test["target"] = test["target"]/len(models)
sub = test[["image_name","target"]]
sub.to_csv("submission_pow.csv",index=False)
sub.head()<save_to_csv> | temp=pd.concat([extratest,pd.DataFrame(np.zeros(( test.shape[0],9)) ,columns=['Col.','Don.','Jonkheer.','Lady.','Major.','Mlle.','Mme.','Sir.', 'the'] ).astype('int')],axis=1)
| Titanic - Machine Learning from Disaster |
847,197 | test["target"] = 0.0
for c in models:
test["target"] += test[c]/test[c].max()
test["target"] = test["target"]/len(models)
sub = test[["image_name","target"]]
sub.to_csv("submission_avg.csv",index=False)
sub.head()<compute_train_metric> | def hasalpha(x):
for i in x:
if str.isalpha(i):
return i
return 'non'
extr=pd.get_dummies(vtrain['Ticket'].apply(hasalpha)).iloc[:,:-1]
exte=pd.get_dummies(vtest['Ticket'].apply(hasalpha)).iloc[:,:-1].loc[:,extr.columns] | Titanic - Machine Learning from Disaster |
847,197 | def dim_optimizer(df_oof, features, init_points = 20, n_iter = 30):
pbounds = {'c0':(0.0, 1.0), 'c1':(0.0, 1.0), 'c2':(0.0, 1.0),'c3':(0.0, 1.0),'c4':(0.0, 1.0),'c5':(0.0, 1.0)}
features = features
def dim_opt(df_oof, c0,c1,c2,c3,c4,c5):
x = c0*df_oof[ features[0] ] + c1*df_oof[ features[1]] + c2*df_oof[ features[2]] +... | train=pd.concat([train,pc,sex,em],axis=1 ).drop(['Pclass','Sex','Embarked'],axis=1)
test=pd.concat([test,pctest,sextest,emtest],axis=1 ).drop(['Pclass','Sex','Embarked'],axis=1 ) | Titanic - Machine Learning from Disaster |
847,197 | def bo_pred(df):
x = c0*df[ models[0] ] + c1*df[ models[1]] + c2*df[ models[2]] + c3*df[ models[3]] + c4*df[ models[4]] + c5*df[ models[5]]
return x
train["pred"] = bo_pred(train)
score = metrics.roc_auc_score(train['target'], train['pred'])
print(f"auc bo:{score}")
<save_to_csv> | dftr=pd.read_csv('.. /input/train.csv')
dfte=pd.read_csv('.. /input/test.csv')
def app(x):
if pd.notnull(x):
return x[0]
return
xx=pd.get_dummies(dftr['Cabin'].apply(app)).iloc[:,:-2]
xte=pd.get_dummies(dfte['Cabin'].apply(app))
xte['T']=np.zeros(( len(xte),1)).astype('int')
xte=xte.iloc[:,:-2] | Titanic - Machine Learning from Disaster |
847,197 | test["target"] = bo_pred(test)
sub = test[["image_name","target"]]
sub.to_csv("submission_bo.csv",index=False)
sub.head()<import_modules> | train=pd.concat([train,extratrain,extr,xx],axis=1)
test=pd.concat([test,extratest,exte,xte],axis=1)
| Titanic - Machine Learning from Disaster |
847,197 | !pip install -q efficientnet
<load_from_csv> | xtrain=train.iloc[:,1:].values
xtest=test.values
ytrain=train.iloc[:,0].values
| Titanic - Machine Learning from Disaster |
847,197 | 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')
train.head()<set_options> | sc_x=StandardScaler()
xtrain=sc_x.fit_transform(xtrain)
xtest=sc_x.transform(xtest)
| Titanic - Machine Learning from Disaster |
847,197 | AUTO = tf.data.experimental.AUTOTUNE
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
strategy = tf.distribute.experimental.TPUStrat... | regressor=LogisticRegression(C=1,solver='saga')
regressor.fit(xtrain,ytrain ) | Titanic - Machine Learning from Disaster |
847,197 | SEED = 42
FOLDS=3
EFF_NETS = [6]*FOLDS
BATCH_SIZES = [bs * strategy.num_replicas_in_sync for bs in [32]*FOLDS]
IMG_SIZES = [512]*FOLDS
EPOCHS = [10]*FOLDS
DROPOUT = 0.25
LR = 0.00004
WARMUP = 5
CLASS_WEIGHT = {0: train['benign_malignant'].value_counts().malignant/len(train),
1: train['benign_malignant'].value_counts().... | regressor2=SVC(C=1,gamma=0.01,kernel='rbf')
regressor2.fit(xtrain,ytrain ) | Titanic - Machine Learning from Disaster |
847,197 | DATASET = {512: '512x512-melanoma-tfrecords-70k-images',
384: 'melanoma-384x384',
192: 'melanoma-192x192'}
GCS_PATH = [None]*FOLDS; GCS_PATH2 = [None]*FOLDS
for i,k in enumerate(IMG_SIZES):
GCS_PATH[i] = KaggleDatasets().get_gcs_path(DATASET[IMG_SIZES[0]])
GCS_PATH2[i] = KaggleDatasets().get_gcs_path('isic2019-%ix%i'%... | regressor3=RandomForestClassifier(criterion='entropy',n_estimators=500)
regressor3.fit(xtrain,ytrain ) | Titanic - Machine Learning from Disaster |
847,197 | 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_ep - lr_sus_ep)+ lr_min
return lr
def get_lr_callback(batch_size=8):
lr_start = 0.000005
lr_max = 0.000003 * batch_size
... | regressor3.score(xtrain,ytrain ) | Titanic - Machine Learning from Disaster |
847,197 | lr_start = 0.000005
lr_max = 0.000003 * BATCH_SIZES[0]
lr_min = 0.000001
lr_ramp_ep = 5
lr_sus_ep = 0
lr_decay = 0.3
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_ep ... | test['Survived']=regressor.predict(xtest ) | Titanic - Machine Learning from Disaster |
847,197 | ROT_ = 180.0
SHR_ = 2.0
HZOOM_ = 8.0
WZOOM_ = 8.0
HSHIFT_ = 8.0
WSHIFT_ = 8.0
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
shear = math.pi * shear / 180.
def get_3x3_mat(lst):
return tf.reshape(tf.concat([lst],axis=0), [3,3])
c1 = tf.math.cos(... | param_svm=[
{
'kernel':['rbf'],
'C':[0.1,0.01,1,5,10],
'gamma':[1,0.1,0.01]
},
{
'kernel':['linear'],
'C':[0.1,0.01,1,5,10],
'gamma':[1,0.1,0.01,5,10]
},
{
'kernel':['sigmoid'],
'C':[0.1,0.01,1,5,10],
'gamma':[1,0.1,0.01]
}
]
param_rf=[
{ 'n_estimators':[10,100,300,600,500], 'criterion':['gini'],'max_depth':[2,5,10,20,... | Titanic - Machine Learning from Disaster |
847,197 | def decode_image(image):
image = tf.image.decode_jpeg(image, channels=3)
image = tf.cast(image, tf.float32)/255.0
image = tf.reshape(image, [*IMG_SIZES[0:2], 3])
return image
def read_tfrecord(example, labeled, return_imgname=False):
tfrecord_format = {
"image": tf.io.FixedLenFeature([], tf.string),
"target": tf.io.F... | print("SVM")
print(gc_svm.best_params_)
print('-----------------------------------------------------------------------------------')
print('logistic regression')
print(gc_logistic.best_params_)
print('-----------------------------------------------------------------------------------')
print('random forest')
pri... | Titanic - Machine Learning from Disaster |
847,197 | 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... | print("SVM")
print(gc_svm.best_score_)
print('-----------------------------------------------------------------------------------')
print('logistic regression')
print(gc_logistic.best_score_)
print('-----------------------------------------------------------------------------------')
print('random forest')
print... | Titanic - Machine Learning from Disaster |
847,197 | plot_transform(7 )<define_variables> | output_train=pd.DataFrame([regressor.predict(xtrain),regressor2.predict(xtrain)] ).apply(lambda x: x.mode() ).iloc[0].values
output=pd.DataFrame([regressor.predict(xtest),regressor2.predict(xtest)] ).apply(lambda x: x.mode() ) | Titanic - Machine Learning from Disaster |
847,197 | VERBOSE = 2
DISPLAY_PLOT = True
skf = KFold(n_splits=FOLDS,shuffle=True,random_state=SEED)
oof_pred = []; oof_tar = []; oof_val = []; oof_names = []; oof_folds = []
preds = np.zeros(( count_data_items(test_filenames),1))
for fold,(idxT,idxV)in enumerate(skf.split(np.arange(15))):
if tpu: tf.tpu.experimental.initialize... | print(classification_report(ytrain,output_train))
| Titanic - Machine Learning from Disaster |
847,197 | oof = np.concatenate(oof_pred); true = np.concatenate(oof_tar);
names = np.concatenate(oof_names); folds = np.concatenate(oof_folds)
auc = roc_auc_score(true,oof)
print('Overall OOF AUC with TTA = %.3f'%auc)
df_oof = pd.DataFrame(dict(
image_name = names, target=true, pred = oof, fold=folds))
df_oof.to_csv('oof.csv... | submission=pd.read_csv('.. /input/gender_submission.csv')
submission['Survived']=output.iloc[0].values
| Titanic - Machine Learning from Disaster |
847,197 | <save_to_csv><EOS> | submission.to_csv('finaloutput.csv',index=False ) | Titanic - Machine Learning from Disaster |
10,022,452 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<load_from_csv> | %matplotlib inline
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
| Titanic - Machine Learning from Disaster |
10,022,452 | train = pd.read_csv('/kaggle/input/melanomaextendedtabular/external_upsampled_tabular.csv')
train.head()<categorify> | sns.set(style="darkgrid")
train_full = pd.read_csv('.. /input/titanic/train.csv', index_col='PassengerId')
test_full = pd.read_csv('.. /input/titanic/test.csv', index_col='PassengerId')
train_NA = train_full.isna().sum()
test_NA = test_full.isna().sum()
pd.concat([train_NA, test_NA], axis=1, sort = False, keys=['Tra... | Titanic - Machine Learning from Disaster |
10,022,452 | train['anatom_site_general_challenge'].replace(['anterior torso','lateral torso','posterior torso'],
'torso', inplace=True )<count_missing_values> | null_fare = test_full[test_full.Fare.isnull() ].index[0]
test_full.loc[null_fare, 'Fare'] = 0 | Titanic - Machine Learning from Disaster |
10,022,452 | train.isnull().sum()<count_missing_values> | y = train_full.Survived
train_X_full = train_full[train_full.columns.drop('Survived')]
combined = pd.concat([train_full, test_full], axis=0 ) | Titanic - Machine Learning from Disaster |
10,022,452 | train.isnull().sum()<data_type_conversions> | def alone(df):
if('SibSp' in df.columns)and('Parch' in df.columns):
df['Family'] = df['SibSp'] + df['Parch'] + 1
le = LabelEncoder()
df['le_Ticket'] = le.fit_transform(df['Ticket'])
df['Same_Ticket'] = df.duplicated(['le_Ticket'])
df['Alone'] = np.where(( df['Family'] > 1)|(df['Same_Ticket']), False, True)
plt.figur... | Titanic - Machine Learning from Disaster |
10,022,452 | def fillna(df, column):
na_idx = df[df[column].isnull() ].index.tolist()
prob = df[column].value_counts(normalize=True ).sort_index().tolist()
for i in na_idx:
df.iloc[i, df.columns.get_loc(column)] = choices(sorted(df[column].dropna().unique().tolist()), prob)[0]
train.sex.replace('unknown', np.nan, inplace=True)
fil... | combined = alone(combined)
train_X_full = combined[combined.Survived.notnull() ]
test_full = combined[combined.Survived.isnull() ] | Titanic - Machine Learning from Disaster |
10,022,452 | train = pd.get_dummies(train, columns=["anatom_site_general_challenge"], prefix='site',
drop_first=True)
train.replace({'sex': {'female':0, 'male': 1}}, inplace=True)
train.head()<categorify> | def fix_cabin(df):
t = df.Cabin.fillna('U')
df['Cabin'] = t.str.slice(0,1)
plt.figure(figsize=(20, 15))
sns.catplot(x="Cabin", kind="count", palette="ch:.25", data=df)
plt.title('Number of passengers per cabin')
| Titanic - Machine Learning from Disaster |
10,022,452 | test = pd.get_dummies(test, columns=["anatom_site_general_challenge"], prefix='site',
drop_first=True)
test.replace({'sex': {'female':0, 'male': 1}}, inplace=True)
test.head()<normalization> | fix_cabin(combined)
train_X_full = combined[combined.Survived.notnull() ]
test_full = combined[combined.Survived.isnull() ] | Titanic - Machine Learning from Disaster |
10,022,452 | y_train = train['target']
X_train = train.drop(['image_name','height','width','target'],
axis=1)
X_test = test.drop(['image_name','patient_id'],axis=1)
scaler = StandardScaler()
X_train_s = X_train.copy()
X_train_s[['age_approx']] = scaler.fit_transform(X_train_s[['age_approx']])
X_test_s = X_test.copy()
X_test_s[['... | fix_embark(combined)
train_X_full = combined[combined.Survived.notnull() ]
test_full = combined[combined.Survived.isnull() ] | Titanic - Machine Learning from Disaster |
10,022,452 | lr = LogisticRegression(penalty='l2', class_weight='balanced', random_state=SEED)
nb = GaussianNB()
rf = RandomForestClassifier(n_estimators=1000, max_depth=2, class_weight='balanced',
n_jobs=-1, random_state=SEED)
estimators = [lr, rf, nb]
cv = StratifiedKFold(5, shuffle=True, random_state=SEED)
def model_cv(X_trai... | Titanic - Machine Learning from Disaster | |
10,022,452 | def model_blend(X_train, y_train, X_test, estimators):
mean_prob = 0
for est in estimators:
est.fit(X_train, y_train)
mean_prob += est.predict_proba(X_test)[:,1]
return mean_prob/len(estimators)
meta_df = pd.DataFrame(columns=['image_name', 'target'])
meta_df['image_name'] = sample['image_name']
meta_df['target'] = ... | def extract_title(df):
if 'Name' in df.columns:
df['Title'] = df['Name'].str.split(',', expand=True)[1].str.split('.', expand=True)[0].str.strip()
df = df[df.columns.drop('Name')]
df['Title'] = df['Title'].replace({'Ms': 'Miss', 'Mlle': 'Miss',
'Mme': 'Mrs', 'Lady': 'Mrs', 'the Countess': 'Mrs', 'Dona': 'Mrs',
'Don': '... | Titanic - Machine Learning from Disaster |
10,022,452 | submission_effnet_ensemble = pd.read_csv('.. /input/effnet-ensemble/submission_effnet_ensemble.csv')
submission.target =(submission_effnet_ensemble.target)+(meta_df.target * 0.1)
submission.to_csv('submission.csv', index=False)
submission.head()<import_modules> | temp = train_X_full.copy()
temp['Survived'] = y
print(temp['Title'].unique())
| Titanic - Machine Learning from Disaster |
10,022,452 | import numpy as np
import pandas as pd
import numpy as np
import pandas as pd
import os
<load_from_csv> | def extract_ticket(df):
df['Ticket_Letters'] = df['Ticket'].str.replace('\d+', '')
df.loc[df['Ticket_Letters']=='','Ticket_Letters'] = 'NA'
df.drop(columns=['Ticket'], inplace=True)
return df | Titanic - Machine Learning from Disaster |
10,022,452 | test = pd.read_csv('.. /input/siim-isic-melanoma-classification/test.csv')
first = pd.read_csv('.. /input/output-of-best-public-submission/submission_best.csv')
second = pd.read_csv('.. /input/output-of-best-public-submission/submission_first.csv')
third = pd.read_csv('.. /input/output-of-best-public-submission/subm... | combined = extract_ticket(combined)
train_X_full = combined[combined.Survived.notnull() ]
test_full = combined[combined.Survived.isnull() ]
train_X_full.head() | Titanic - Machine Learning from Disaster |
10,022,452 | arg1 =(2/3)*first['target']
arg2 =(1/6)*second['target']
arg3 =(1/6)*third['target']
submission['target'] = arg1 + arg2 + arg3
submission.to_csv('submission.csv', index=False)
submission.head()<install_modules> | train_X_full = combined[combined.Survived.notnull() ]
test_full = combined[combined.Survived.isnull() ] | Titanic - Machine Learning from Disaster |
10,022,452 | !pip install -q efficientnet >> /dev/null<import_modules> | temp = combined.copy()
to_one_hot = ['Sex', 'Embarked', 'Ticket_Letters', 'Cabin', 'Title', 'Alone', 'FareBin']
temp = pd.concat([temp, pd.get_dummies(temp[to_one_hot])], axis=1)
temp.drop(columns=to_one_hot, axis=1, inplace=True)
combined = temp
combined.head() | Titanic - Machine Learning from Disaster |
10,022,452 | import json
import pandas as pd, numpy as np
from kaggle_datasets import KaggleDatasets
import tensorflow as tf, re, math
import tensorflow.keras.backend as K
import efficientnet.tfkeras as efn
from sklearn.model_selection import KFold
from sklearn.metrics import roc_auc_score
import matplotlib.pyplot as plt<define_sea... | train_X_full = combined[combined.Survived.notnull() ]
test_full = combined[combined.Survived.isnull() ] | Titanic - Machine Learning from Disaster |
10,022,452 | DEVICE = "TPU"
SEED = 27
FOLDS = 5
IMG_SIZES = [512,512,512,512,512]
INC2019 = [1,1,1,1,1]
INC2018 = [1,1,1,1,1]
BATCH_SIZES = [32]*FOLDS
EPOCHS = [20]*FOLDS
EFF_NETS = [6,6,6,6,6]
WGTS = [1/FOLDS]*FOLDS
TTA = 11<choose_model_class> | def convert_cat(df):
le = LabelEncoder()
le_train_X = df.copy()
s = df.dtypes=='object'
cat_features = list(s[s].index)
for col in cat_features:
le_train_X[col] = le.fit_transform(df[col])
return le_train_X | Titanic - Machine Learning from Disaster |
10,022,452 | if 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.exp... | without_survived = combined.copy()
without_survived.drop(columns=['Survived'], inplace=True)
without_survived.head() | Titanic - Machine Learning from Disaster |
10,022,452 | GCS_PATH = [None]*FOLDS; GCS_PATH2 = [None]*FOLDS
for i,k in enumerate(IMG_SIZES):
GCS_PATH[i] = KaggleDatasets().get_gcs_path('melanoma-%ix%i'%(k,k))
GCS_PATH2[i] = KaggleDatasets().get_gcs_path('isic2019-%ix%i'%(k,k))
print(GCS_PATH)
print()
print(GCS_PATH2)
files_train = np.sort(np.array(tf.io.gfile.glob(GCS_PATH[... | missing_age_model = predict_age(without_survived ) | Titanic - Machine Learning from Disaster |
10,022,452 | ROT_ = 180.0
SHR_ = 2.0
HZOOM_ = 8.0
WZOOM_ = 8.0
HSHIFT_ = 8.0
WSHIFT_ = 8.0<normalization> | missing_age = without_survived[without_survived.Age.isnull() ]
missing_age = missing_age[missing_age.columns.drop('Age')]
pred_age = missing_age_model.predict(missing_age)
output_age = pd.DataFrame({'Age': pred_age}, index=missing_age.index)
output_age.transpose() | Titanic - Machine Learning from Disaster |
10,022,452 | def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
shear = math.pi * shear / 180.
def get_3x3_mat(lst):
return tf.reshape(tf.concat([lst],axis=0), [3,3])
c1 = tf.math.cos(rotation)
s1 = tf.math.sin(rotation)
one = tf.constant([1],dtype='float32')
... | test = combined.copy()
test = test.combine_first(output_age)
pd.DataFrame(test.Age ).transpose() | Titanic - Machine Learning from Disaster |
10,022,452 | def read_labeled_tfrecord(example):
tfrec_format = {
'image' : tf.io.FixedLenFeature([], tf.string),
'image_name' : tf.io.FixedLenFeature([], tf.string),
'patient_id' : tf.io.FixedLenFeature([], tf.int64),
'sex' : tf.io.FixedLenFeature([], tf.int64),
'age_approx' : tf.io.FixedLenFeature([], tf.int64),
'anatom_site_gene... | combined = test
train_X_full = combined[combined.Survived.notnull() ]
test_full = combined[combined.Survived.isnull() ] | Titanic - Machine Learning from Disaster |
10,022,452 | def get_dataset(files, augment = False, shuffle = False, repeat = False,
labeled=True, return_image_names=True, batch_size=16, dim=256):
ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)
ds = ds.cache()
if repeat:
ds = ds.repeat()
if shuffle:
ds = ds.shuffle(1024*8)
opt = tf.data.Options()
opt.experimental... | y = train_X_full.Survived
train_X_full = train_X_full.drop(columns=['Survived'], axis=1)
train_X, valid_X, train_y, valid_y = train_test_split(train_X_full, y, random_state=5 ) | Titanic - Machine Learning from Disaster |
10,022,452 | EFNS = [efn.EfficientNetB0, efn.EfficientNetB1, efn.EfficientNetB2, efn.EfficientNetB3,
efn.EfficientNetB4, efn.EfficientNetB5, efn.EfficientNetB6]
def build_model(dim=128, ef=6):
inp = tf.keras.layers.Input(shape=(dim,dim,3))
base = EFNS[ef](input_shape=(dim,dim,3),weights='imagenet',include_top=False)
x = base(inp)
... | def scores(results):
key_min = min(results.keys() , key=(lambda k: results[k]))
key_max = max(results.keys() , key=(lambda k: results[k]))
print('Highest score at %d of %.4f' %(key_max, results[key_max]))
print('Lowest score at %d of %.4f' %(key_min, results[key_min]))
return key_max, key_min | Titanic - Machine Learning from Disaster |
10,022,452 | def get_lr_callback(batch_size=8):
lr_start = 0.000005
lr_max = 0.00000125 * REPLICAS * batch_size
lr_min = 0.000001
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_m... | print('Number of trees: ')
high, low = scores(results ) | Titanic - Machine Learning from Disaster |
10,022,452 | fold = 3
VERBOSE = 2
DISPLAY_PLOT = True
skf = KFold(n_splits=FOLDS,shuffle=True,random_state=SEED)
oof_pred = []; oof_tar = []; oof_val = []; oof_names = []; oof_folds = []
preds = np.zeros(( count_data_items(files_test),1))
if DEVICE=='TPU':
if tpu: tf.tpu.experimental.initialize_tpu_system(tpu)
print('
print('
(I... | best_rf_model = RandomForestClassifier(n_estimators=high,random_state=0 ).fit(train_X, train_y)
pred_valid1 = best_rf_model.predict(valid_X)
print('Mean absolute error: \t%.4f' %mean_absolute_error(pred_valid1, valid_y))
print('Accuracy score: \t%.4f' %accuracy_score(valid_y, pred_valid1)) | Titanic - Machine Learning from Disaster |
10,022,452 | ds = get_dataset(files_test, augment=False, repeat=False, dim=IMG_SIZES[fold],
labeled=False, return_image_names=True)
image_names = np.array([img_name.numpy().decode("utf-8")
for img, img_name in iter(ds.unbatch())])
submission = pd.DataFrame(dict(image_name=image_names, target=preds[:,0]))
submission = submission.... | perm = PermutationImportance(best_rf_model, random_state=1 ).fit(valid_X, valid_y)
eli5.show_weights(perm, feature_names=valid_X.columns.tolist() ) | Titanic - Machine Learning from Disaster |
10,022,452 | warnings.filterwarnings('ignore' )<load_from_csv> | results1 = {}
for i in range(1, len(train_X.columns)) :
selector = SelectKBest(f_classif, k=i)
X_new = selector.fit_transform(train_X[feature_cols], train_y)
selected_features = pd.DataFrame(selector.inverse_transform(X_new),
index=train_X.index,
columns=feature_cols)
selected_cols = selected_features.columns[select... | Titanic - Machine Learning from Disaster |
10,022,452 | 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" )<install_modules> | high1, low1 = scores(results1 ) | Titanic - Machine Learning from Disaster |
10,022,452 | !pip install -q efficientnet<import_modules> | results2 = {}
for i in range(1, len(train_X.columns)) :
selector = SelectKBest(f_classif, k=i)
X_new = selector.fit_transform(train_X[feature_cols], train_y)
selected_features = pd.DataFrame(selector.inverse_transform(X_new),
index=train_X.index,
columns=feature_cols)
selected_cols = selected_features.columns[select... | Titanic - Machine Learning from Disaster |
10,022,452 | import tensorflow as tf
import tensorflow.keras.backend as K
import efficientnet.tfkeras as efn
from kaggle_datasets import KaggleDatasets<define_variables> | high2, low2 = scores(results2 ) | Titanic - Machine Learning from Disaster |
10,022,452 | GCS_PATH = KaggleDatasets().get_gcs_path('melanoma-512x512')
GCS_PATH2 = KaggleDatasets().get_gcs_path('malignant-v2-512x512')
GCS_PATH3 = KaggleDatasets().get_gcs_path('isic2019-512x512')
filenames_train1 = tf.io.gfile.glob(GCS_PATH + '/train*.tfrec')
filenames_train2 = tf.io.gfile.glob(GCS_PATH2 + '/train%.2i*.tf... | results3 = {}
for i in range(1, len(train_X.columns)) :
selector = SelectKBest(f_classif, k=i)
X_new = selector.fit_transform(train_X[feature_cols], train_y)
selected_features = pd.DataFrame(selector.inverse_transform(X_new),
index=train_X.index,
columns=feature_cols)
selected_cols = selected_features.columns[select... | Titanic - Machine Learning from Disaster |
10,022,452 | filenames_train = np.array(filenames_train1+filenames_train2+filenames_train3)
np.random.shuffle(filenames_train)
np.random.shuffle(filenames_train )<feature_engineering> | high3, low3 = scores(results3 ) | Titanic - Machine Learning from Disaster |
10,022,452 | AUTO = tf.data.experimental.AUTOTUNE<set_options> | xg_model = xgb.XGBClassifier()
results4 = {}
for i in range(1, len(train_X.columns)) :
selector = SelectKBest(f_classif, k=i)
X_new = selector.fit_transform(train_X[feature_cols], train_y)
selected_features = pd.DataFrame(selector.inverse_transform(X_new),
index=train_X.index,
columns=feature_cols)
selected_cols = s... | Titanic - Machine Learning from Disaster |
10,022,452 | cfg = dict(
batch_size=32,
img_size=512,
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> | high4, low4 = scores(results4 ) | Titanic - Machine Learning from Disaster |
10,022,452 | 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(... | feature_cols = train_X.columns
selector = SelectKBest(f_classif, k=high1)
X_new = selector.fit_transform(train_X[feature_cols], train_y)
selected_features = pd.DataFrame(selector.inverse_transform(X_new),
index=train_X.index,
columns=feature_cols)
selected_cols = selected_features.columns[selected_features.var() != ... | Titanic - Machine Learning from Disaster |
10,022,452 | 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_... | feature_cols = train_X.columns
selector = SelectKBest(f_classif, k=high4)
X_new = selector.fit_transform(train_X[feature_cols], train_y)
selected_features = pd.DataFrame(selector.inverse_transform(X_new),
index=train_X.index,
columns=feature_cols)
selected_cols2 = selected_features.columns[selected_features.var() !=... | Titanic - Machine Learning from Disaster |
10,022,452 | def dropout(image, DIM=512, 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... | cv_results = {}
for i in range(2, 10):
cv_score = cross_val_score(xg_best_model, cv_X, cv_y, cv=i)
cv_results[i] = cv_score.mean() | Titanic - Machine Learning from Disaster |
10,022,452 | 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... | cv_high, cv_low = scores(cv_results ) | Titanic - Machine Learning from Disaster |
10,022,452 | 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']... | cv_score = cross_val_score(best_k_model, cv_X, cv_y, cv=cv_high)
print('Mean cross-validation score: %.2f' %(cv_score.mean() *100)) | Titanic - Machine Learning from Disaster |
10,022,452 | 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> | feature_cols = train_X.columns
selector = SelectKBest(f_classif, k=high3)
X_new = selector.fit_transform(train_X[feature_cols], train_y)
selected_features = pd.DataFrame(selector.inverse_transform(X_new),
index=train_X.index,
columns=feature_cols)
selected_cols1 = selected_features.columns[selected_features.var() !=... | Titanic - Machine Learning from Disaster |
10,022,452 | 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> | cv_high, cv_low = scores(cv_results ) | Titanic - Machine Learning from Disaster |
10,022,452 | 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... | cv_score = cross_val_score(best_k_model1, cv_X, cv_y, cv=cv_high)
print('Mean cross-validation score: %.2f' %(cv_score.mean() *100)) | Titanic - Machine Learning from Disaster |
10,022,452 | 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... | test_full.drop(columns=['Survived'], axis=0, inplace=True ) | Titanic - Machine Learning from Disaster |
10,022,452 | 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... | ktest_X = test_full[selected_cols]
selected_cols | Titanic - Machine Learning from Disaster |
10,022,452 | 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='imagenet',
input_shape=(cfg['img_size'], cfg['img_size'], 3),
pooling='avg' )(du... | pred = best_k_model.predict(ktest_X ).astype('int')
pred | Titanic - Machine Learning from Disaster |
10,022,452 | 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> | output = pd.DataFrame({'PassengerId': test_full.index,
'Survived': pred})
output.to_csv('survived.csv', index=False ) | Titanic - Machine Learning from Disaster |
10,022,452 | history = model.fit(ds_train,
validation_data = None,
verbose=1,
steps_per_epoch = stepsTrain,
validation_steps = 0,
epochs=14,
callbacks=callbacks )<create_dataframe> | ktest_X1 = test_full[selected_cols1]
pred1 = best_k_model1.predict(ktest_X1 ).astype('int')
output = pd.DataFrame({'PassengerId': test_full.index,
'Survived': pred1})
output.to_csv('survived1.csv', index=False ) | Titanic - Machine Learning from Disaster |
10,022,452 | <predict_on_test><EOS> | ktest_X2 = test_full[selected_cols2]
pred2 = xg_best_model.predict(ktest_X2 ).astype('int')
output = pd.DataFrame({'PassengerId': test_full.index,
'Survived': pred2})
output.to_csv('survived2.csv', index=False ) | Titanic - Machine Learning from Disaster |
5,201,782 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<save_to_csv> | %matplotlib inline
data_train = pd.read_csv('.. /input/train.csv')
data_test = pd.read_csv('.. /input/test.csv' ) | Titanic - Machine Learning from Disaster |
5,201,782 | 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... | data_train = data_train.drop(columns=['Name', 'Ticket', 'Fare', 'Cabin'])
data_test = data_test.drop(columns=['Name', 'Ticket', 'Fare', 'Cabin'])
| Titanic - Machine Learning from Disaster |
5,201,782 | !gzip submission_model_0.csv
!gzip submission_model_1.csv
!gzip submission_model_2.csv
!gzip blended_effnets.csv<load_from_csv> | display(data_train.Age.value_counts(dropna=False ).sort_index())
display(data_test.Age.value_counts(dropna=False ).sort_index() ) | Titanic - Machine Learning from Disaster |
5,201,782 | def MinMaxBestBaseStacking(input_folder, best_base, output_path):
sub_base = pd.read_csv(best_base)
all_files = os.listdir(input_folder)
outs = [pd.read_csv(os.path.join(input_folder, f), index_col=0)for f in all_files]
concat_sub = pd.concat(outs, axis=1)
cols = list(map(lambda x: "target" + str(x), range(len(conca... | data_train.Age = data_train.Age.fillna(data_train.Age.mean())
data_test.Age = data_test.Age.fillna(data_test.Age.mean())
| Titanic - Machine Learning from Disaster |
5,201,782 | MinMaxBestBaseStacking('.. /input/melanoma-ensemble-files/', '.. /input/melanoma-ensemble-files/blend_sub.csv', 'submission.csv' )<load_from_csv> | display(data_train.Embarked.value_counts(dropna=False))
display(data_test.Embarked.value_counts(dropna=False))
| Titanic - Machine Learning from Disaster |
5,201,782 | !ls /kaggle/input/20201124-ensemble-1-testcsv<import_modules> | data_train.Embarked = data_train.Embarked.fillna('S')
| Titanic - Machine Learning from Disaster |
5,201,782 | warnings.filterwarnings("ignore" )<import_modules> | b = data_train.pop('Survived')
data_train = pd.concat([data_train, b], axis=1)
display(data_train.head())
| Titanic - Machine Learning from Disaster |
5,201,782 | l5kit.__version__<set_options> | display(data_train.Age.value_counts(dropna=False ).sort_index())
display(data_test.Age.value_counts(dropna=False ).sort_index() ) | Titanic - Machine Learning from Disaster |
5,201,782 | def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
set_seed(42 )<init_hyperparams> | display(data_train.Sex.value_counts(dropna=False ).sort_index())
display(data_test.Sex.value_counts(dropna=False ).sort_index() ) | Titanic - Machine Learning from Disaster |
5,201,782 | cfg = {
'format_version': 4,
'data_path': "/kaggle/input/lyft-motion-prediction-autonomous-vehicles",
'model_params': {
'model_architecture': 'resnet50',
'history_num_frames': 10,
'history_step_size': 1,
'history_delta_time': 0.1,
'future_num_frames': 50,
'future_step_size': 1,
'future_delta_time': 0.1,
'model_name': "... | display(( data_train.Pclass.value_counts(dropna=False ).sort_index()))
display(( data_test.Pclass.value_counts(dropna=False ).sort_index())) | Titanic - Machine Learning from Disaster |
5,201,782 | DIR_INPUT = cfg["data_path"]
os.environ["L5KIT_DATA_FOLDER"] = DIR_INPUT
dm = LocalDataManager(None )<create_dataframe> | display(data_train.Survived.value_counts(dropna=False ).sort_index())
| 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.