kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
14,271,675 |
__all__ = ['SENet', 'senet154', 'se_resnet50', 'se_resnet101', 'se_resnet152',
'se_resnext50_32x4d', 'se_resnext101_32x4d']
pretrained_settings = {
'senet154': {
'imagenet': {
'url': 'http://data.lip6.fr/cadene/pretrainedmodels/senet154-c7b49a05.pth',
'input_space': 'RGB',
'input_size': [3, 224, 224],
'input_range': ... | scaler = StandardScaler()
Xs_train = scaler.fit_transform(X_train)
Xs_test = scaler.transform(X_test ) | Titanic - Machine Learning from Disaster |
14,271,675 | sys.path.append('/kaggle/working/')
class GeM(nn.Module):
def __init__(self, p=3, eps=1e-6):
super(GeM,self ).__init__()
self.p = Parameter(torch.ones(1)*p)
self.eps = eps
def forward(self, x):
return gem(x, p=self.p, eps=self.eps)
def __repr__(self):
return self.__class__.__name__ + '(' + 'p=' + '{:.4f}'.format(sel... | logreg = LogisticRegression()
logreg.fit(Xs_train, y_train ) | Titanic - Machine Learning from Disaster |
14,271,675 | TEST_IMAGE_PATH = '/kaggle/input/aptos2019-blindness-detection/test_images'
device = torch.device("cuda")
test_images = glob(os.path.join(TEST_IMAGE_PATH, '*.png'))
<init_hyperparams> | Y_pred=logreg.predict(Xs_test ) | Titanic - Machine Learning from Disaster |
14,271,675 | def make_predictions(model, test_images, transforms, size=256, device=torch.device("cuda")) :
predictions = []
for i, im_path in enumerate(test_images):
image = Image.open(im_path)
image = image.resize(( size, size), resample=Image.BILINEAR)
image = transforms(image ).to(device)
output = model(image.unsqueeze(0))
ou... | logreg.score(Xs_train, y_train ) | Titanic - Machine Learning from Disaster |
14,271,675 | MODEL_PATH = '.. /input/densenet121/model_densenet121_bs64_30.pth'
model = get_densenet121_gem(pretrain=False)
model.to(device)
model.load_state_dict(torch.load(MODEL_PATH, map_location='cuda:0'))
model.eval()
norm = transforms.Compose([transforms.ToTensor() ])
<choose_model_class> | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": Y_pred
})
submission.to_csv('submission2_LG.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | MODEL_PATH = '.. /input/seresnet50testpseudo/model10.pth'
model = get_se_resnet50_gem(pretrain=False)
model.to(device)
model.load_state_dict(torch.load(MODEL_PATH, map_location='cuda:0'))
model.eval()
norm = transforms.Compose([transforms.ToTensor() ,
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])... | lr_pipe2 = Pipeline([
('sscaler2', StandardScaler()),
('logreg2', LogisticRegression(penalty='l1', C=0.1, solver='liblinear'))
])
| Titanic - Machine Learning from Disaster |
14,271,675 | MODEL_PATH = '.. /input/seresnet50pseudo-512/model30.pth'
model = get_se_resnet50_gem(pretrain=False)
model.to(device)
model.load_state_dict(torch.load(MODEL_PATH, map_location='cuda:0'))
model.eval()
norm = transforms.Compose([transforms.ToTensor() ,
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])... | pipe_2_params = {'sscaler2__with_mean': [True, False],
'sscaler2__with_std': [True, False],
'logreg2__C': [0.1, 0.2,0.3],
'logreg2__solver':['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'],
'logreg2__fit_intercept': [True, False],
'logreg2__penalty': ['l1', 'l2']} | Titanic - Machine Learning from Disaster |
14,271,675 | final_predictions = predictions_seresnet_512
<save_to_csv> | pipe_2_gridsearch = GridSearchCV(lr_pipe2,
pipe_2_params,
cv=5,
verbose=1 ) | Titanic - Machine Learning from Disaster |
14,271,675 | submission = pd.DataFrame(final_predictions)
submission.columns = ['id_code','diagnosis']
submission.loc[submission.diagnosis < 0.75, 'diagnosis'] = 0
submission.loc[(0.75 <= submission.diagnosis)&(submission.diagnosis < 1.5), 'diagnosis'] = 1
submission.loc[(1.5 <= submission.diagnosis)&(submission.diagnosis < 2.5), ... | pipe_2_gridsearch.fit(X_train, y_train);
| Titanic - Machine Learning from Disaster |
14,271,675 | !pip install.. /input/weights/timm-0.3.1-py3-none-any.whl<import_modules> | pipe_2_gridsearch.best_score_ | Titanic - Machine Learning from Disaster |
14,271,675 | device = "cuda:0"
<import_modules> | pipe_2_gridsearch.best_estimator_
| Titanic - Machine Learning from Disaster |
14,271,675 | FeaturePyramidNetwork,
LastLevelMaxPool,
)
def gem(x, p=3, eps=1e-6):
return F.avg_pool2d(x.clamp(min=eps ).pow(p),(x.size(-2), x.size(-1)) ).pow(1./p)
class GeM(nn.Module):
def __init__(self, p=3, eps=1e-6, flatten=False):
super(GeM,self ).__init__()
self.p = Parameter(torch.ones(1)*p)
self.eps = eps
self.flatten ... | pre = pipe_2_gridsearch.predict(X_test ) | Titanic - Machine Learning from Disaster |
14,271,675 | threshold = [0.75, 1.5, 2.5, 3.5]
def regress2class(out):
prediction = 0
for i in range(4):
prediction +=(out.data >= threshold[i] ).squeeze().cpu().item()
return prediction
def ordinal2class_prob(out):
pred_prob = torch.zeros(out.size(0), 5 ).cuda()
pred_prob[:, 0] =(1 - out[:, 0] ).squeeze()
pred_prob[:, 1] =(out[:, ... | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": pre
})
submission.to_csv('submission1_LG_pipline.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | def gem(x, p=3, eps=1e-6):
return F.avg_pool2d(x.clamp(min=eps ).pow(p),(x.size(-2), x.size(-1)) ).pow(1./p)
class GeM(nn.Module):
def __init__(self, p=3, eps=1e-6, flatten=False):
super(GeM,self ).__init__()
self.p = Parameter(torch.ones(1)*p)
self.eps = eps
self.flatten = flatten
def forward(self, x):
x = gem(x, p=... | lr_pipe2 = Pipeline([
('sscaler2', StandardScaler()),
('knn', KNeighborsClassifier())
])
pipe_2_params = {'sscaler2__with_mean': [True, False],
'sscaler2__with_std': [True, False],
'knn__n_neighbors': [3, 5, 7, 9, 11, 20, 50, 100],
'knn__weights': ['uniform', 'distance'],
'knn__metric': ['manhattan', 'euclidean']}
... | Titanic - Machine Learning from Disaster |
14,271,675 | test_ids = pd.read_csv('.. /input/aptos2019-blindness-detection/test.csv')
test_ids = np.squeeze(test_ids.values)
transform1 = transforms.Compose([
trim() ,
cropTo4_3() ,
transforms.Resize(( 288, 384)) ,
transforms.ToTensor() ,
transforms.Normalize(mean=[0.384, 0.258, 0.174], std=[0.124, 0.089, 0.094]),
])
transform... | pipe_2_gridsearch.fit(X_train, y_train);
| Titanic - Machine Learning from Disaster |
14,271,675 | df = pd.DataFrame(submission, columns=["id_code", "diagnosis"])
df.to_csv("submission.csv", index=False )<import_modules> | y_pre_GS_knn = pipe_2_gridsearch.predict(X_test ) | Titanic - Machine Learning from Disaster |
14,271,675 | from __future__ import print_function, absolute_import
import os
import sys
import time
import datetime
import argparse
import os.path as osp
import numpy as np
import random
from PIL import Image
import tqdm
import cv2
import csv
import math
import torchvision as tv
import torchvision
import torch.nn.functional as F
i... | pipe_2_gridsearch.best_score_ | Titanic - Machine Learning from Disaster |
14,271,675 | name_file='.. /input/aptos2019-blindness-detection/test.csv'
csv_file=csv.reader(open(name_file,'r'))
content=[]
for line in csv_file:
content.append(line[0]+'.png')
content=content[1:]<normalization> | pipe_2_gridsearch.best_estimator_
| Titanic - Machine Learning from Disaster |
14,271,675 | def gem(x, p=3, eps=1e-6):
return F.avg_pool2d(x.clamp(min=eps ).pow(p),(x.size(-2), x.size(-1)) ).pow(1./p)
class GeM(nn.Module):
def __init__(self, p=3, eps=1e-6):
super(GeM,self ).__init__()
self.p = Parameter(torch.ones(1)*p)
self.eps = eps
def forward(self, x):
return gem(x, p=self.p, eps=self.eps)
def __repr__... | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": y_pre_GS_knn
})
submission.to_csv('submission2_GS_knn.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | def cv_imread(file_path):
cv_img=cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
return cv_img
def change_size(image):
b=cv2.threshold(image,15,255,cv2.THRESH_BINARY)
binary_image=b[1]
binary_image=cv2.cvtColor(binary_image,cv2.COLOR_BGR2GRAY)
print(binary_image.shape)
x=binary_image.shape[0]
print... | knn = KNeighborsClassifier() | Titanic - Machine Learning from Disaster |
14,271,675 | def load_para_dict(model1):
state_dict_1=torch.load(model1)
new_state_dict = OrderedDict()
for k, v in state_dict_1.items() :
if 'module' in k:
name = k[7:]
else:
name=k
new_state_dict[name] = v
return new_state_dict<set_options> | knn.fit(Xs_train, y_train ) | Titanic - Machine Learning from Disaster |
14,271,675 | %reload_ext autoreload
%autoreload 2
%matplotlib inline
<import_modules> | knn.score(Xs_train, y_train ) | Titanic - Machine Learning from Disaster |
14,271,675 | from fastai import *
from fastai.vision import *
import pandas as pd
import matplotlib.pyplot as plt<set_options> | cross_val_score(knn, Xs_train, y_train, cv=5 ).mean() | Titanic - Machine Learning from Disaster |
14,271,675 | print('Make sure cudnn is enabled:', torch.backends.cudnn.enabled )<define_variables> | pre=knn.predict(X_test ) | Titanic - Machine Learning from Disaster |
14,271,675 | PATH = Path('.. /input/aptos2019-blindness-detection' )<load_from_csv> | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": pre
})
submission.to_csv('submission2_KNN.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | df = pd.read_csv(PATH/'train.csv')
df.head()<set_options> | model=RandomForestClassifier()
param={'n_estimators':[100,200,300],
'max_depth':[1,3,5,7],
'criterion':["gini"],
'max_features': [1,3,5],
"min_samples_split": [2,3,5]
}
clf=GridSearchCV(estimator=model,
param_grid=param,
scoring="accuracy",
verbose=1,
n_jobs=-1,
cv=5)
clf.fit(X_train, y_train)
clf.best_estimator_
clf... | Titanic - Machine Learning from Disaster |
14,271,675 | def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
SEED = 999
seed_everything(SEED )<feature_engineering> | pre=clf.predict(X_test)
| Titanic - Machine Learning from Disaster |
14,271,675 | base_image_dir = os.path.join('.. ', 'input/aptos2019-blindness-detection/')
train_dir = os.path.join(base_image_dir,'train_images/')
df = pd.read_csv(os.path.join(base_image_dir, 'train.csv'))
df['path'] = df['id_code'].map(lambda x: os.path.join(train_dir,'{}.png'.format(x)))
df = df.drop(columns=['id_code'])
df ... | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": pre
})
submission.to_csv('submission2_RF_GS.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | len_df = len(df)
len_df<set_options> | lr_pipe2 = Pipeline([
('sscaler2', StandardScaler()),
('rf', RandomForestClassifier()
)
])
pipe_2_params = {'sscaler2__with_mean': [True, False],
'sscaler2__with_std': [True, False],
'rf__bootstrap': [True],
'rf__max_depth': [1,3,5,7],
'rf__max_features': [1, 3,5],
'rf__criterion':["gini"],
'rf__min_samples_leaf':... | Titanic - Machine Learning from Disaster |
14,271,675 | im = Image.open(df['path'][1])
width, height = im.size
print(width,height)
im.show()<define_variables> | pipe_2_gridsearch.fit(X_train, y_train); | Titanic - Machine Learning from Disaster |
14,271,675 | bs = 64
sz=224<define_variables> | pipe_2_gridsearch.best_score_ | Titanic - Machine Learning from Disaster |
14,271,675 | data.show_batch(rows=3, figsize=(7,6))<compute_test_metric> | pre= pipe_2_gridsearch.predict(X_test ) | Titanic - Machine Learning from Disaster |
14,271,675 | def quadratic_kappa(y_hat, y):
return torch.tensor(cohen_kappa_score(torch.round(y_hat), y, weights='quadratic'),device='cuda:0' )<choose_model_class> | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": pre
})
submission.to_csv('submission2_RF_pip_GS.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | learn = cnn_learner(data, base_arch=models.resnet50, metrics = [quadratic_kappa] )<find_best_params> | lr_pipe3 = Pipeline([
('sscaler2', StandardScaler()),
('dt', DecisionTreeClassifier()
)
])
pipe_3_params = {'sscaler2__with_mean': [True, False],
'sscaler2__with_std': [True, False],
'dt__max_depth': [10],
'dt__random_state':[100],
'dt__max_features': [1, 3,5],
'dt__criterion':["gini"],
'dt__min_samples_leaf': [10... | Titanic - Machine Learning from Disaster |
14,271,675 | learn.lr_find()
<train_model> | pipe_3_gridsearch.fit(X_train, y_train); | Titanic - Machine Learning from Disaster |
14,271,675 | learn.fit_one_cycle(5,max_lr = 1e-2 )<train_model> | pipe_3_gridsearch.best_score_ | Titanic - Machine Learning from Disaster |
14,271,675 | learn.fit_one_cycle(6, max_lr=slice(1e-6,1e-3))<set_options> | pre= pipe_3_gridsearch.predict(X_test ) | Titanic - Machine Learning from Disaster |
14,271,675 | learn.export()
learn.save('stage-2' )<find_best_params> | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": pre
})
submission.to_csv('submission2_DT_pip_GS.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | interp = ClassificationInterpretation.from_learner(learn)
losses,idxs = interp.top_losses()
len(data.valid_ds)==len(losses)==len(idxs )<predict_on_test> | tree = DecisionTreeClassifier(criterion='gini',max_depth=10,random_state=100,min_samples_leaf=10)
tree.fit(X_train,y_train)
y_predicted = tree.predict(Xs_test)
| Titanic - Machine Learning from Disaster |
14,271,675 | valid_preds = learn.get_preds(ds_type=DatasetType.Valid )<import_modules> | tree.score(Xs_train, y_train ) | Titanic - Machine Learning from Disaster |
14,271,675 | import numpy as np
import pandas as pd
import os
import scipy as sp
from functools import partial
from sklearn import metrics
from collections import Counter
import json<compute_test_metric> | pre= tree.predict(X_test ) | Titanic - Machine Learning from Disaster |
14,271,675 | class OptimizedRounder(object):
def __init__(self):
self.coef_ = 0
def _kappa_loss(self, coef, X, y):
X_p = np.copy(X)
for i, pred in enumerate(X_p):
if pred < coef[0]:
X_p[i] = 0
elif pred >= coef[0] and pred < coef[1]:
X_p[i] = 1
elif pred >= coef[1] and pred < coef[2]:
X_p[i] = 2
elif pred >= coef[2] and pred < coe... | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": pre
})
submission.to_csv('submission2_DT.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | optR = OptimizedRounder()
optR.fit(valid_preds[0],valid_preds[1] )<load_from_csv> | SVM = SVC()
SVM.fit(Xs_train, y_train)
SVM_predictions = SVM.predict(Xs_test)
SVM.score(Xs_train, y_train ) | Titanic - Machine Learning from Disaster |
14,271,675 | sample_df = pd.read_csv('.. /input/aptos2019-blindness-detection/sample_submission.csv')
sample_df.head()<define_variables> | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": SVM_predictions
})
submission.to_csv('submission2_SVM.csv', index=False ) | Titanic - Machine Learning from Disaster |
14,271,675 | learn.data.add_test(ImageList.from_df(sample_df,'.. /input/aptos2019-blindness-detection',folder='test_images',suffix='.png'))<feature_engineering> | scores ={'LR_pip': 0.772,'LR': 0.770,'Knn_pip': 0.779, 'Knn': 0.669, 'RF_GS': 0.787,
'RF_pip_GS': 0.775, 'DT_pip_GS': 0.760, 'DT':0.779,
'SVM': 0.779} | Titanic - Machine Learning from Disaster |
14,301,061 | preds,y = learn.TTA(ds_type=DatasetType.Test )<predict_on_test> | !jupyter nbextension enable --py widgetsnbextension | Titanic - Machine Learning from Disaster |
14,301,061 | test_predictions = optR.predict(preds, coefficients )<data_type_conversions> | data = pd.read_csv("/kaggle/input/titanic/train.csv")
data.head(5 ) | Titanic - Machine Learning from Disaster |
14,301,061 | sample_df.diagnosis = test_predictions.astype(int)
sample_df.head()<save_to_csv> | data.groupby('Sex')['Survived'].mean() | Titanic - Machine Learning from Disaster |
14,301,061 | sample_df.to_csv('submission.csv',index=False )<set_options> | data.groupby(['Pclass', 'Sex'])['Survived'].mean() | Titanic - Machine Learning from Disaster |
14,301,061 | %pylab inline
<import_modules> | data['Initial']=0
for i in data:
data['Initial']=data.Name.str.extract('([A-Za-z]+)\.')
pd.crosstab(data.Initial,data.Sex ).T.style.background_gradient(cmap='summer_r' ) | Titanic - Machine Learning from Disaster |
14,301,061 | from sklearn.preprocessing import StandardScaler
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelEncoder<import_modules> | data['Initial'].replace(['Mlle','Mme','Ms','Dr','Major','Lady','Countess','Jonkheer','Col','Rev','Capt','Sir','Don'],
['Miss','Miss','Miss','Mr','Mr','Mrs','Mrs','Other','Other','Other','Mr','Mr','Mr'],inplace=True)
data.groupby('Initial')['Age'].mean() | Titanic - Machine Learning from Disaster |
14,301,061 | from keras.models import Sequential
from keras.layers import Dense,Dropout,Activation
from keras.utils.np_utils import to_categorical<import_modules> | data.loc[(data.Age.isnull())&(data.Initial=='Mr'),'Age']=33
data.loc[(data.Age.isnull())&(data.Initial=='Mrs'),'Age']=36
data.loc[(data.Age.isnull())&(data.Initial=='Master'),'Age']=5
data.loc[(data.Age.isnull())&(data.Initial=='Miss'),'Age']=22
data.loc[(data.Age.isnull())&(data.Initial=='Other'),'Age']=46
data.Age.is... | Titanic - Machine Learning from Disaster |
14,301,061 | print(sys.version )<import_modules> | data['Embarked'] = data['Embarked'].fillna('S' ) | Titanic - Machine Learning from Disaster |
14,301,061 | pd.__version__<set_options> | data['Age_band']=0
data.loc[(data['Age']>16)&(data['Age']<=32),'Age_band']=1
data.loc[(data['Age']>32)&(data['Age']<=48),'Age_band']=2
data.loc[(data['Age']>48),'Age_band']=3
| Titanic - Machine Learning from Disaster |
14,301,061 | rcParams['figure.figsize'] = 8,8<load_from_csv> | data['FamilySize'] = data['SibSp'] + data['Parch'] + 1
data['IsAlone'] = 1
data['IsAlone'].loc[data['FamilySize'] > 1] = 0 | Titanic - Machine Learning from Disaster |
14,301,061 | data = pd.read_csv('.. /input/train.csv')
parent_data = data.copy()
ID = data.pop('id' )<categorify> | data['Sex'] = data['Sex'].map({'female': 0, 'male': 1} ).astype(int)
data['Embarked'] = data['Embarked'].map({'S': 0, 'C': 1, 'Q': 2} ).astype(int ) | Titanic - Machine Learning from Disaster |
14,301,061 | y = data.pop('species')
y = LabelEncoder().fit(y ).transform(y)
print(y.shape )<normalization> | from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import KFold
... | Titanic - Machine Learning from Disaster |
14,301,061 | X = StandardScaler().fit(data ).transform(data)
print(X.shape )<categorify> | train,val=train_test_split(data,test_size=0.3,random_state=42,stratify=data['Survived'])
train_X=train[train.columns[1:]]
train_Y=train[train.columns[:1]]
val_X=val[val.columns[1:]]
val_Y=val[val.columns[:1]] | Titanic - Machine Learning from Disaster |
14,301,061 | y_cat = to_categorical(y)
print(y_cat.shape )<choose_model_class> | model = LogisticRegression()
model.fit(train_X,train_Y)
prediction=model.predict(val_X)
print('The accuracy of the Logistic Regression is',metrics.accuracy_score(prediction,val_Y)) | Titanic - Machine Learning from Disaster |
14,301,061 | model = Sequential()
model.add(Dense(2048,input_dim=192, init='uniform', activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(1024, activation='sigmoid'))
model.add(Dropout(0.3))
model.add(Dense(99, activation='softmax'))<choose_model_class> | X=data[data.columns[1:]]
Y=data['Survived']
kfold = KFold(n_splits=10, random_state=22 ) | Titanic - Machine Learning from Disaster |
14,301,061 | model.compile(loss='categorical_crossentropy',optimizer='Adamax', metrics = ["accuracy"] )<train_model> | logistic_cv_result = cross_val_score(LogisticRegression() ,X,Y, cv = kfold,scoring = "accuracy")
print('The mean accuracy of the Logistic Regression under 10-fold validation is: ', np.mean(logistic_cv_result),
'std is: ', np.std(logistic_cv_result)) | Titanic - Machine Learning from Disaster |
14,301,061 | start = time.time()
history = model.fit(X,y_cat,batch_size=100,
nb_epoch=125,verbose=0, validation_split=0.1)
end = time.time()
print('runtime: ',"%.3f" %(end-start),' [sec]' )<train_model> | tree_cv_result = cross_val_score(DecisionTreeClassifier() ,X,Y, cv = kfold,scoring = "accuracy")
print('The mean accuracy of the decision tree under 10-fold validation is: ', np.mean(tree_cv_result),
'std is: ', np.std(tree_cv_result)) | Titanic - Machine Learning from Disaster |
14,301,061 | print('---------------------------------------')
print('acc: ',max(history.history['acc']))
print('loss: ',min(history.history['loss']))
print('---------------------------------------')
print('val_acc: ',max(history.history['val_acc']))
print('val_loss: ',min(history.history['val_loss']))<load_from_csv> | forest_cv_result = cross_val_score(RandomForestClassifier(n_estimators=100),X,Y, cv = kfold,scoring = "accuracy")
print('The mean accuracy of the random forest under 10-fold validation is: ', np.mean(forest_cv_result),
'std is: ', np.std(forest_cv_result)) | Titanic - Machine Learning from Disaster |
14,301,061 | test = pd.read_csv('.. /input/test.csv')
index = test.pop('id')
test = StandardScaler().fit(test ).transform(test)
yPred = model.predict_proba(test )<create_dataframe> | forest = RandomForestClassifier(n_estimators=100, min_samples_leaf=1, min_samples_split=10)
forest.fit(train_X,train_Y)
prediction=forest.predict(val_X)
print('The accuracy is',metrics.accuracy_score(prediction,val_Y)) | Titanic - Machine Learning from Disaster |
14,301,061 | yPred = pd.DataFrame(yPred,index=index,columns=sort(parent_data.species.unique()))<save_to_csv> | import xgboost as xgb | Titanic - Machine Learning from Disaster |
14,301,061 | fp = open('submission_nn_kernel.csv','w')
fp.write(yPred.to_csv() )<define_variables> | gbm = xgb.XGBClassifier(
n_estimators= 2000,
max_depth= 4,
min_child_weight= 2,
gamma=0.9,
subsample=0.8,
colsample_bytree=0.8,
objective= 'binary:logistic',
scale_pos_weight=1 ).fit(train_X, train_Y)
predictions = gbm.predict(val_X)
print('The accuracy of XG Boost is',metrics.accuracy_score(predictions,val_Y)) | Titanic - Machine Learning from Disaster |
14,301,061 | DEBUG = False<define_variables> | from catboost import CatBoostClassifier, Pool, cv | Titanic - Machine Learning from Disaster |
14,301,061 | sys.path = [
'.. /input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master',
] + sys.path<import_modules> | Titanic - Machine Learning from Disaster | |
14,301,061 | import skimage.io
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from efficientnet_pytorch import model as enet
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqdm
<load_from_csv> | cat = CatBoostClassifier(
l2_leaf_reg=1,
learning_rate=0.003842420425736234,
iterations=500,
eval_metric='Accuracy',
random_seed=42,
verbose=False,
loss_function='Logloss',
)
cv_data = cv(Pool(X, Y, cat_features=range(train_X.shape[1])) , cat.get_params() ) | Titanic - Machine Learning from Disaster |
14,301,061 | data_dir = '.. /input/prostate-cancer-grade-assessment'
df_train = pd.read_csv(os.path.join(data_dir, 'train.csv'))
df_test = pd.read_csv(os.path.join(data_dir, 'test.csv'))
df_sub = pd.read_csv(os.path.join(data_dir, 'sample_submission.csv'))
model_dir = '.. /input/panda-public-models'
image_folder = os.path.join(data... | print('Precise validation accuracy score: {}'.format(np.max(cv_data['test-Accuracy-mean'])) ) | Titanic - Machine Learning from Disaster |
14,301,061 | class enetv2(nn.Module):
def __init__(self, backbone, out_dim):
super(enetv2, self ).__init__()
self.enet = enet.EfficientNet.from_name(backbone)
self.myfc = nn.Linear(self.enet._fc.in_features, out_dim)
self.enet._fc = nn.Identity()
def extract(self, x):
return self.enet(x)
def forward(self, x):
x = self.extract(x)... | test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
test_data.head() | Titanic - Machine Learning from Disaster |
14,301,061 | def get_tiles(img, mode=0):
result = []
h, w, c = img.shape
pad_h =(tile_size - h % tile_size)% tile_size +(( tile_size * mode)// 2)
pad_w =(tile_size - w % tile_size)% tile_size +(( tile_size * mode)// 2)
img2 = np.pad(img,[[pad_h // 2, pad_h - pad_h // 2], [pad_w // 2,pad_w - pad_w//2], [0,0]], constant_values=255)... | test_data['Sex'] = test_data['Sex'].map({'female': 0, 'male': 1} ).astype(int)
test_data['Embarked'] = test_data['Embarked'].map({'S': 0, 'C': 1, 'Q': 2} ).astype(int)
test_data['Age_band']=0
test_data.loc[(test_data['Age']>16)&(test_data['Age']<=32),'Age_band']=1
test_data.loc[(test_data['Age']>32)&(test_data['Age']... | Titanic - Machine Learning from Disaster |
14,301,061 | dataset = PANDADataset(df, image_size, n_tiles, 0)
loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False)
dataset2 = PANDADataset(df, image_size, n_tiles, 2)
loader2 = DataLoader(dataset2, batch_size=batch_size, num_workers=num_workers, shuffle=False )<save_to_csv> | features = ['Pclass', 'Sex', 'Embarked', 'Age_band', 'IsAlone']
X_test = pd.get_dummies(test_data[features])
| Titanic - Machine Learning from Disaster |
14,301,061 | LOGITS = []
LOGITS2 = []
with torch.no_grad() :
for data in tqdm(loader):
data = data.to(device)
logits = models[0](data)
LOGITS.append(logits)
for data in tqdm(loader2):
data = data.to(device)
logits = models[0](data)
LOGITS2.append(logits)
LOGITS =(torch.cat(LOGITS ).sigmoid().cpu() + torch.cat(LOGITS2 ).sigmoi... | Titanic - Machine Learning from Disaster | |
14,301,061 | DEBUG = False<define_variables> | cat = CatBoostClassifier(
l2_leaf_reg=1,
learning_rate=0.003842420425736234,
iterations=500,
eval_metric='Accuracy',
random_seed=42,
verbose=False,
loss_function='Logloss',
)
forest = RandomForestClassifier(n_estimators=100, min_samples_leaf=1, min_samples_split=10 ) | Titanic - Machine Learning from Disaster |
14,301,061 | sys.path = [
'.. /input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master',
] + sys.path<import_modules> | gbm = xgb.XGBClassifier(
n_estimators= 2000,
max_depth= 4,
min_child_weight= 2,
gamma=0.9,
subsample=0.8,
colsample_bytree=0.8,
objective= 'binary:logistic',
scale_pos_weight=1 ) | Titanic - Machine Learning from Disaster |
14,301,061 | import skimage.io
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from efficientnet_pytorch import model as enet
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqdm<load_from_csv> | from sklearn.ensemble import VotingClassifier | Titanic - Machine Learning from Disaster |
14,301,061 | data_dir = '.. /input/prostate-cancer-grade-assessment'
df_train = pd.read_csv(os.path.join(data_dir, 'train.csv'))
df_test = pd.read_csv(os.path.join(data_dir, 'test.csv'))
df_sub = pd.read_csv(os.path.join(data_dir, 'sample_submission.csv'))
model_dir = '.. /input/ck-epoch6/'
image_folder = os.path.join(data_dir, 'te... | votingC = VotingClassifier(estimators=[('rfc', forest),('xgb', gbm),('cat', cat)], voting='soft', n_jobs=4)
votingC = votingC.fit(X, Y ) | Titanic - Machine Learning from Disaster |
14,301,061 | class enetv2(nn.Module):
def __init__(self, backbone, out_dim):
super(enetv2, self ).__init__()
self.enet = enet.EfficientNet.from_name(backbone)
self.myfc = nn.Linear(self.enet._fc.in_features, out_dim)
self.enet._fc = nn.Identity()
def extract(self, x):
return self.enet(x)
def forward(self, x):
x = self.extract(x)... | predictions = votingC.predict(X_test)
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions})
output.to_csv('my_submission.csv', index=False)
print("Your submission was successfully saved!" ) | Titanic - Machine Learning from Disaster |
14,301,061 | <load_pretrained><EOS> | Titanic - Machine Learning from Disaster | |
14,255,995 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<save_to_csv> | !pip uninstall -y dataclasses | Titanic - Machine Learning from Disaster |
14,255,995 | LOGITS = []
LOGITS2 = []
with torch.no_grad() :
for data in tqdm(loader):
data = data.to(device)
logits = models[0](data)
LOGITS.append(logits)
for data in tqdm(loader2):
data = data.to(device)
logits = models[0](data)
LOGITS2.append(logits)
LOGITS =(torch.cat(LOGITS ).sigmoid().cpu() + torch.cat(LOGITS2 ).sigmoi... | train_data = pd.read_csv("/kaggle/input/titanic/train.csv")
train_data.head()
test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
| Titanic - Machine Learning from Disaster |
14,255,995 | warnings.filterwarnings("ignore")
sys.path.insert(0, '.. /input/semisupervised-imagenet-models/semi-supervised-ImageNet1K-models-master/')
<define_variables> | features = ["Pclass", "Sex", "SibSp", "Parch", "Fare", "Embarked", "Age"]
label = ["Survived"]
X_train = pd.get_dummies(train_data[features + label])
X_test = pd.get_dummies(test_data[features])
X_train.head() | Titanic - Machine Learning from Disaster |
14,255,995 | DATA = '.. /input/prostate-cancer-grade-assessment/test_images'
TEST = '.. /input/prostate-cancer-grade-assessment/test.csv'
SAMPLE = '.. /input/prostate-cancer-grade-assessment/sample_submission.csv'
MODELS = [f'.. /input/panda-init-class-model1/RNXT50_128krnew1_3featureB_{i}.pth' for i in range(4)] + \
[f'.. /input/p... | X_train.isna().sum() | Titanic - Machine Learning from Disaster |
14,255,995 | class Modelm1(nn.Module):
def __init__(self, arch='resnext50_32x4d', n=6, pre=True):
super().__init__()
m = _resnext(semi_supervised_model_urls[arch], Bottleneck, [3, 4, 6, 3], False, progress=False,\
groups=32,width_per_group=4)
self.enc = nn.Sequential(*list(m.children())[:-2])
nc = list(m.children())[-1].in_featur... | X_test.isna().sum() | Titanic - Machine Learning from Disaster |
14,255,995 | class AdaptiveConcatPool2dm1(Module):
"Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`."
def __init__(self, sz:Optional[int]=None):
"Output will be 2*sz or 2 if sz is None"
self.output_size = sz or 1
self.ap = nn.AdaptiveAvgPool2d(self.output_size)
self.mp = nn.AdaptiveMaxPool2d(self.output_size)
def f... | X_train = X_train.fillna(X_train.mean())
X_test = X_test.fillna(X_train.mean() ) | Titanic - Machine Learning from Disaster |
14,255,995 | class AdaptiveConcatPool2dm(Module):
"Layer that concats `AdaptiveAvgPool2d` and `AdaptiveMaxPool2d`."
def __init__(self, sz:Optional[int]=None):
"Output will be 2*sz or 2 if sz is None"
self.output_size = sz or 1
self.ap = nn.AdaptiveAvgPool2d(self.output_size)
self.mp = nn.AdaptiveMaxPool2d(self.output_size)
def fo... | y = X_train[label].values.ravel()
X_train = X_train.drop(label, axis=1 ) | Titanic - Machine Learning from Disaster |
14,255,995 | models = []
for path in MODELS[:-4]:
state_dict = torch.load(path,map_location=torch.device('cpu'))
model = Model(n=1+10)
model.load_state_dict(state_dict)
model.float()
model.eval()
model.cuda()
models.append(model)
for path in MODELS[-4:]:
state_dict = torch.load(path,map_location=torch.device('cpu'))
model = Mode... | dt_config = {
"class": DecisionTreeClassifier,
"criterion": tune.choice(['gini', 'entropy']),
"max_depth": tune.randint(2, 8),
"min_samples_split": tune.randint(2, 10),
'min_samples_leaf': tune.randint(1, 10),
"random_state": 1
}
rf_config = {
"class": RandomForestClassifier,
"max_depth": tune.randint(2, 8),
"n_estimat... | Titanic - Machine Learning from Disaster |
14,255,995 | sub_df = pd.read_csv(SAMPLE)
if os.path.exists(DATA):
ds = PandaDataset(DATA,TEST)
dl = DataLoader(ds, batch_size=bs, num_workers=nworkers, shuffle=False)
names,preds = [],[]
with torch.no_grad() :
for x,x2,y in tqdm(dl):
x = x.cuda()
x = torch.stack([x,x.flip(-1),x.flip(-2),x.flip(-1,-2),x.transpose(-1,-2),\
x.tran... | methods = {"rf": rf_config, "xgb": xgb_config, "svm": svm_config, "dt": dt_config}
def export_csv(predictions, name:str):
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions})
filename = f'{name}_submission.csv'
output.to_csv(filename, index=False)
print(f"Your submission({name})was s... | Titanic - Machine Learning from Disaster |
14,255,995 | sub_df.to_csv("submission.csv", index=False)
sub_df.head()<define_variables> | def run_experiment(method: str, num_samples: int=50)-> Dict[str, Any]:
result = run_tune(method, num_samples ).get_best_trial(metric="mean_accuracy", mode="max")
_config = deepcopy(result.config)
model_class = _config["class"]
_config.pop("class")
model = model_class(**_config)
model.fit(X_train, y)
predictions = ... | Titanic - Machine Learning from Disaster |
14,255,995 | package_path = '/kaggle/input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master'
sys.path.append(package_path)
<define_variables> | dt = run_experiment(method="dt", num_samples=100)
print(f"result {dt.last_result}")
print(f"{dt.config}" ) | Titanic - Machine Learning from Disaster |
14,255,995 |
<define_variables> | rf = run_experiment(method="rf", num_samples=100)
print(f"result {rf.last_result}")
print(f"{rf.config}" ) | Titanic - Machine Learning from Disaster |
14,255,995 | mean_224 = torch.tensor([1.0-0.82097102, 1.0-0.63302738, 1.0-0.75392824])
std_224 = torch.tensor([0.37723779, 0.49839178, 0.4015415])
first_resnext_pth_path_224 = ".. /input/lb91-224tile/LB91_224tile_best_resnext50_X20_30e_0.pth"
ensemble_1 ={"mean":mean_224,"std":std_224,"tileSize":224,"isExpandTile":False,"arch":"r... | xgb = run_experiment("xgb", num_samples=100)
print(f"result {xgb.last_result}")
print(f"{xgb.config}" ) | Titanic - Machine Learning from Disaster |
14,255,995 | <choose_model_class><EOS> | svm = run_experiment(method="svm", num_samples=8)
print(f"result {svm.last_result}")
print(f"{svm.config}" ) | Titanic - Machine Learning from Disaster |
14,242,857 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<choose_model_class> | %matplotlib inline
titanic_df = pd.read_csv('.. /input/titanic/train.csv')
titanic_df.head(5 ) | Titanic - Machine Learning from Disaster |
14,242,857 | segmmodel = timm.create_model('mixnet_xl', pretrained=False)
for param in segmmodel.parameters() :
param.requires_grad = False
segmmodel.classifier=nn.Linear(1536, 1)
segmmodel.fc = nn.Linear(1536, 1 )<normalization> | titanic_df['Age'].fillna(titanic_df['Age'].mean() , inplace=True)
titanic_df['Cabin'].fillna('N',inplace=True)
titanic_df['Embarked'].fillna('N',inplace=True)
titanic_df.isnull().sum() | Titanic - Machine Learning from Disaster |
14,242,857 | checkpoint = torch.load(mixnet_pth, map_location=device)
segmmodel.load_state_dict(checkpoint)
segmmodel.eval()
segmmodel.cuda()
del checkpoint<load_pretrained> | print('Sex
','--------------
', titanic_df['Sex'].value_counts() ,'
')
print('Cabin
','--------------
', titanic_df['Cabin'].value_counts() ,'
')
print('Embarked
','--------------
', titanic_df['Embarked'].value_counts() ,'
' ) | Titanic - Machine Learning from Disaster |
14,242,857 | aknell_models = []
for model_index, path in enumerate(MODELS):
print("path",path)
state_dict = torch.load(path,map_location=torch.device(device))
model = Model(arch=ensemble_list[model_index]['arch'])
model.load_state_dict(state_dict)
model.float()
model.eval()
model.cuda()
aknell_models.append(model)
del state_dic... | titanic_df['Cabin'] = titanic_df['Cabin'].str[:1]
print(titanic_df['Cabin'].value_counts() ) | Titanic - Machine Learning from Disaster |
14,242,857 | test=pd.read_csv(TEST)
if chk:
pass
test=test[:][:nchk]<define_variables> | titanic_df.groupby(['Sex','Survived'])['Survived'].count() | Titanic - Machine Learning from Disaster |
14,242,857 | test_image_dir='/kaggle/input/prostate-cancer-grade-assessment/test_images'
if os.path.exists(test_image_dir):
print('test set exist')
chk=False
mode='test'
test_image_dir='/kaggle/input/prostate-cancer-grade-assessment/{}_images'.format(mode)
csv_path='/kaggle/input/prostate-cancer-grade-assessment/{}.csv'.format(mo... | def encode_feature(dataDF):
features = ['Cabin','Sex','Embarked']
for feature in features:
le = preprocessing.LabelEncoder()
le = le.fit(dataDF[feature])
dataDF[feature] = le.transform(dataDF[feature])
return dataDF
titanic_df = encode_feature(titanic_df)
titanic_df.head() | 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.