kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
13,921,351 | def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTOTUNE)
dataset = dataset.with_options(ignore_order)
dataset = dataset.map(partial(read_tfrecord,... | train.drop('Sex', axis = 1, inplace = True)
test.drop('Sex', axis = 1, inplace = True)
| Titanic - Machine Learning from Disaster |
13,921,351 | def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n )<categorify> | train = pd.concat([train, sex1], axis=1)
test = pd.concat([test, sex2], axis=1 ) | Titanic - Machine Learning from Disaster |
13,921,351 | def read_tfrecord(example, labeled):
tfrecord_format = {
"image": tf.io.FixedLenFeature([], tf.string),
"target": tf.io.FixedLenFeature([], tf.int64)
} if labeled else {
"image": tf.io.FixedLenFeature([], tf.string),
"image_name": tf.io.FixedLenFeature([], tf.string)
}
example = tf.io.parse_single_example(example, tf... | train.drop('female', axis = 1, inplace = True)
test.drop('female', axis = 1, inplace = True ) | Titanic - Machine Learning from Disaster |
13,921,351 | test_ds = get_test_dataset(ordered=True)
print('Computing predictions...')
test_images_ds = test_ds.map(lambda image, idnum: image)
probabilities = trained_model.predict(test_images_ds)
predictions = np.argmax(probabilities, axis=-1)
print(predictions )<save_to_csv> | Embarked1 = pd.get_dummies(train['Embarked'])
Embarked2 = pd.get_dummies(test['Embarked'])
train.drop(['Embarked'], axis = 1, inplace = True)
test.drop(['Embarked'], axis = 1, inplace = True)
train = pd.concat([train, Embarked1], axis=1)
test = pd.concat([test, Embarked2], axis=1 ) | Titanic - Machine Learning from Disaster |
13,921,351 | print('Generating submission.csv file...')
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['... | def family(x):
if x['SibSp'] + x['Parch'] > 1:
return 1
else:
return 0
train['Family'] = train.apply(family, axis=1)
test['Family'] =test.apply(family, axis = 1 ) | Titanic - Machine Learning from Disaster |
13,921,351 | warnings.simplefilter(action = 'ignore', category = FutureWarning)
print("Tensorflow version " + tf.__version__ )<define_variables> | train.drop(['SibSp','Parch'], axis=1, inplace=True)
test.drop(['SibSp','Parch'], axis=1, inplace=True)
| Titanic - Machine Learning from Disaster |
13,921,351 | def seed_everything(seed=0):
random.seed(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
os.environ['TF_DETERMINISTIC_OPS'] = '1'
SEED = 414
seed_everything(SEED )<set_options> | train['Cabin'] = pd.Series(i[0] if not pd.isnull(i)else 'X' for i in train['Cabin'])
test['Cabin'] = pd.Series(i[0] if not pd.isnull(i)else 'X' for i in test['Cabin'] ) | Titanic - Machine Learning from Disaster |
13,921,351 | 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.TPUStrategy(tpu)
else:
strategy = tf.distrib... | train['Cabin'] = train['Cabin'].map({
'X': 0,
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
'F': 6,
'G': 7,
'T': 0
})
train['Cabin'] = train['Cabin'].astype(int)
test['Cabin'] = test['Cabin'].map({
'X': 0,
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5,
'F': 6,
'G': 7,
'T': 0
})
test['Cabin'] = test['Cabin'].astype(int ) | Titanic - Machine Learning from Disaster |
13,921,351 | GCS_DS_PATH = '.. /input/cassava-leaf-disease-classification'
print(GCS_DS_PATH )<define_variables> | train_title = [i.split(",")[1].split(".")[0].strip() for i in train["Name"]]
train["Title"] = pd.Series(train_title)
test_title = [i.split(",")[1].split(".")[0].strip() for i in test["Name"]]
test["Title"] = pd.Series(test_title ) | Titanic - Machine Learning from Disaster |
13,921,351 | BATCH_SIZE = 16 * REPLICAS
WARMUP_EPOCHS = 3
WARMUP_LEARNING_RATE = 1e-4 * REPLICAS
EPOCHS = 20
LEARNING_RATE = 5e-5 * REPLICAS
ES_PATIENCE = 5
CHANNELS = 3
N_CLASSES = 5
DIM = 512
HEIGHT = 512
WIDTH = 512
CLASSES = ['0', '1', '2', '3', '4']
AUTO = tf.data.experimental.AUTOTUNE<define_variables> | train = train.drop(['Name'], axis = 1)
test = test.drop(['Name'], axis = 1 ) | Titanic - Machine Learning from Disaster |
13,921,351 | ROT_ = 180.0
SHR_ = 2.0
HZOOM_ = 8.0
WZOOM_ = 8.0
HSHIFT_ = 8.0
WSHIFT_ = 8.0<normalization> | train["Title"] = train["Title"].replace(['Lady', 'the Countess','Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
train["Title"] = train["Title"].map({"Master":0, "Miss":1, "Ms" : 1 , "Mme":1, "Mlle":1, "Mrs":1, "Mr":2, "Rare":3})
train["Title"] = train["Title"].astype(int)
te... | Titanic - Machine Learning from Disaster |
13,921,351 | 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(tf... | Ticket1 = []
for i in list(train.Ticket):
if not i.isdigit() :
Ticket1.append(i.replace(".","" ).replace("/","" ).strip().split(' ')[0])
else:
Ticket1.append("X")
train["Ticket"] = Ticket1
Ticket2 = []
for j in list(test.Ticket):
if not j.isdigit() :
Ticket2.append(j.replace(".","" ).replace("/","" ).strip().split(' ... | Titanic - Machine Learning from Disaster |
13,921,351 | def transform(image, DIM=512):
XDIM = DIM%2
rot = ROT_ * tf.random.normal([1], dtype='float32')
shr = SHR_ * tf.random.normal([1], dtype='float32')
h_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ HZOOM_
w_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ WZOOM_
h_shift = HSHIFT_ * tf.random.normal([1], dtyp... | train= pd.get_dummies(train, columns = ["Ticket"], prefix="T")
test = pd.get_dummies(test, columns = ["Ticket"], prefix="T" ) | Titanic - Machine Learning from Disaster |
13,921,351 | def read_labeled_tfrecord(example):
tfrec_format = {
'image' : 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_unlabeled_tfrecord(example, return_image_name):
tfrec_fo... | train = train.drop(['T_SP','T_SOP','T_Fa','T_LINE','T_SWPP','T_SCOW','T_PPP','T_AS','T_CASOTON'],axis = 1)
test = test.drop(['T_SCA3','T_STONOQ','T_AQ4','T_A','T_LP','T_AQ3'],axis = 1 ) | Titanic - Machine Learning from Disaster |
13,921,351 | def get_dataset(files, augment = False, shuffle = False, repeat = False,
labeled=True, return_image_names=True, batch_size=BATCH_SIZE, dim=512):
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.expe... | train.drop(['Survived'],axis=1,inplace=True ) | Titanic - Machine Learning from Disaster |
13,921,351 | TEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/test_tfrecords/*.tfrec')
<define_variables> | train.isnull().sum()
| Titanic - Machine Learning from Disaster |
13,921,351 | NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
print('Dataset: {} unlabeled test images'.format(NUM_TEST_IMAGES))<install_modules> | test.isnull().sum() | Titanic - Machine Learning from Disaster |
13,921,351 | sys.path.append('/kaggle/input/efficientnet-keras-dataset/efficientnet_kaggle')
! pip install /kaggle/input/efficientnet-keras-dataset/efficientnet_kaggle<import_modules> | test.isnull().sum() | Titanic - Machine Learning from Disaster |
13,921,351 | import efficientnet.keras as efn
<choose_model_class> | scaler = StandardScaler()
train2 = scaler.fit_transform(train)
test2 = scaler.fit_transform(test ) | Titanic - Machine Learning from Disaster |
13,921,351 | def create_model_efnB6() :
base_model = efn.EfficientNetB6(weights=None,
include_top=False,
input_shape=[HEIGHT, WIDTH, 3])
model = tf.keras.Sequential([
base_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Flatten() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
])
return model<choose... | KFold_Score = pd.DataFrame()
classifiers = ['Linear SVM', 'Radial SVM', 'LogisticRegression',
'RandomForestClassifier', 'AdaBoostClassifier',
'XGBoostClassifier', 'KNeighborsClassifier','GradientBoostingClassifier']
models = [svm.SVC(kernel='linear'),
svm.SVC(kernel='rbf'),
LogisticRegression(max_iter = 1000),
RandomFo... | Titanic - Machine Learning from Disaster |
13,921,351 | with strategy.scope() :
model_efnB6 = create_model_efnB6()<load_from_csv> | mean = pd.DataFrame(KFold_Score.mean() , index= classifiers)
KFold_Score = pd.concat([KFold_Score,mean.T])
KFold_Score.index=['Fold 1','Fold 2','Fold 3','Fold 4','Fold 5','Mean']
KFold_Score.T.sort_values(by=['Mean'], ascending = False ) | Titanic - Machine Learning from Disaster |
13,921,351 | TTA = 1
print('Predicting Test with TTA...')
test_ds = get_dataset(TEST_FILENAMES,labeled=False,return_image_names=False,augment=False,
repeat=False,shuffle=False)
test_ct = count_data_items(TEST_FILENAMES);
STEPS = TTA * test_ct/BATCH_SIZE/REPLICAS
if STEPS < 1:
STEPS = 1
test_df = pd.read_csv('.. /input/cassava-lea... | col_name1[0],col_name1[2] = col_name1[2],col_name1[0]
col_name2[0],col_name2[2] = col_name2[2],col_name2[0] | Titanic - Machine Learning from Disaster |
13,921,351 | print('Generating submission.csv file...')
ds = get_dataset(TEST_FILENAMES,labeled=False,return_image_names=True,augment=False,
repeat=False,shuffle=False)
test_ids = np.array([img_name.numpy().decode("utf-8")
for img, img_name in iter(ds.unbatch())])
np.savetxt(
'submission.csv',
np.rec.fromarrays([test_ids, pred... | train_new = train[col_name1]
test_new = test[col_name2] | Titanic - Machine Learning from Disaster |
13,921,351 | !pip install --no-deps.. /input/pretrined-models/timm-0.3.3-py3-none-any.whl<import_modules> | train_new = train_new.drop(['Cabin'],axis = 1)
test_new = test_new.drop(['Cabin'],axis = 1 ) | Titanic - Machine Learning from Disaster |
13,921,351 | import os
import pandas as pd
import timm
from PIL import Image, ImageDraw, ImageChops
import matplotlib.pyplot as plt
from torchvision.utils import make_grid
from tqdm import tqdm<load_from_csv> | sc = StandardScaler()
train3 = sc.fit_transform(train_new)
test3 = sc.transform(test_new ) | Titanic - Machine Learning from Disaster |
13,921,351 | df = pd.read_csv(path + "/train.csv" )<drop_column> | clf = RandomForestClassifier(random_state=0)
param_grid={
'n_estimators': [200,300],
'max_features': ['auto', 'sqrt'],
'max_depth': [6,7,8],
'criterion':['gini','entropy']
} | Titanic - Machine Learning from Disaster |
13,921,351 | df["path"] = df["image_id"].map(lambda x: path + "/train_images/" + x)
df = df.drop(columns=["image_id"])
df = df.sample(frac=1 ).reset_index(drop=True )<split> | CV_clf = GridSearchCV(estimator=clf, param_grid=param_grid, cv=5)
CV_clf.fit(train3, pred)
CV_clf.best_params_ | Titanic - Machine Learning from Disaster |
13,921,351 | train_df, valid_df = model_selection.train_test_split(
df, test_size=0.2, random_state=42, stratify=df.label.values
)<drop_column> | clf1 = RandomForestClassifier(random_state=0, n_estimators=200, criterion='gini', max_features='auto', max_depth=8)
clf1.fit(train3, pred ) | Titanic - Machine Learning from Disaster |
13,921,351 | train_df = train_df.reset_index().drop(columns=["index"])
train_df.head()<drop_column> | pred3 = clf1.predict(test3 ) | Titanic - Machine Learning from Disaster |
13,921,351 | valid_df = valid_df.reset_index().drop(columns=["index"])
valid_df.head()<load_pretrained> | pred_test = pred3
output = pd.DataFrame({
'PassengerId': test_data.PassengerId,
'Survived': pred_test
})
output.to_csv('submission1.csv', index=False ) | Titanic - Machine Learning from Disaster |
12,472,732 | im = Image.open(train_df["path"][0] )<import_modules> | train_data = pd.read_csv("/kaggle/input/titanic/train.csv")
train_data | Titanic - Machine Learning from Disaster |
12,472,732 | import torch
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.dataset import Subset
from sklearn.model_selection import KFold
import matplotlib.image as img<categorify> | t = train_data.loc[:, ['Cabin', 'Survived', 'PassengerId']]
t['initial'] = t['Cabin'].str[0]
t.groupby(['initial', 'Survived'] ).agg('count' ) | Titanic - Machine Learning from Disaster |
12,472,732 | class CassavaDataset(Dataset):
def __init__(self, dataframe, transform=None):
super().__init__()
self.df = dataframe
self.transform = transform
def __len__(self):
return len(self.df["path"])
def __getitem__(self, index):
path = self.df["path"][index]
label = self.df["label"][index]
with open(path, "rb")as f:
image = I... | train_data = train_data.loc[:,['PassengerId', 'Survived', 'Pclass', 'Sex', 'Age', 'Parch', 'SibSp', 'Cabin']]
train_data | Titanic - Machine Learning from Disaster |
12,472,732 | import random<normalization> | train_data.loc[:, ['Parch', 'Survived', 'PassengerId']].groupby(['Parch', 'Survived'] ).agg('count' ) | Titanic - Machine Learning from Disaster |
12,472,732 | image_size = 512
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_transform = transforms.Compose(
[
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomVerticalFlip(p=0.5),
transforms.RandomResizedCrop(image_size),
make_mask_image(p=0.5, mask_size=50),
transforms.ToTensor() ,
transforms.Normalize(me... | t = train_data.loc[:, ['Age', 'Survived', 'PassengerId']]
t['age_group'] = t['Age'] // 10
t.groupby(['age_group', 'Survived'] ).agg('count' ) | Titanic - Machine Learning from Disaster |
12,472,732 | dataset = CassavaDataset(train_df, train_transform )<load_from_disk> | train_data.loc[:, ['SibSp', 'Survived', 'PassengerId']].groupby(['SibSp', 'Survived'] ).agg('count' ) | Titanic - Machine Learning from Disaster |
12,472,732 | path = '.. /input/cassava-leaf-disease-classification/label_num_to_disease_map.json'
with open(path, mode = 'r')as f:
label_to_name = json.load(f )<normalization> | sex_age_ave = train_data.loc[:, ['Sex', 'Age']].groupby(['Sex'] ).agg({'Age':'mean'})
male_age_ave = sex_age_ave.loc['male'].values[0]
female_age_ave = sex_age_ave.loc['female'].values[0]
print(male_age_ave, female_age_ave ) | Titanic - Machine Learning from Disaster |
12,472,732 | class Unnormalize(object):
def __init__(self, mean, std):
self.mean = mean
self.std = std
def __call__(self, tensor):
for t, m, s in zip(tensor, self.mean, self.std):
t.mul_(s ).add_(m)
return tensor<normalization> | def create_age_group(df):
df.loc[(df['Age'] >= 0)&(df['Age'] < 15), ['age_group']] = 0
df.loc[(df['Age'] >= 15)&(df['Age'] < 25), ['age_group']] = 1
df.loc[(df['Age'] >= 25)&(df['Age'] < 65), ['age_group']] = 2
df.loc[(df['Age'] >= 65), ['age_group']] = 3 | Titanic - Machine Learning from Disaster |
12,472,732 | unnorm = Unnormalize(mean, std )<load_pretrained> | def create_sibsp_group(df):
df.loc[(df['SibSp'] >= 0)&(df['SibSp'] <= 2), ['sibsp_group']] = 0
df.loc[(df['SibSp'] > 2), ['sibsp_group']] = 1 | Titanic - Machine Learning from Disaster |
12,472,732 | loader = DataLoader(dataset, 16, shuffle = True)
display_batch(next(iter(loader)) )<import_modules> | def create_parch_group(df):
df['parch_group'] = df['Parch']
| Titanic - Machine Learning from Disaster |
12,472,732 | import torch
import torch.nn as nn
import torch.nn.functional as F<set_options> | def create_cabin_group(df):
df.loc[(df['Cabin'].isnull())&(df['Pclass'] == 1), ['Cabin']] = 'D'
df.loc[(df['Cabin'].isnull())&(df['Pclass'] >= 2), ['Cabin']] = 'F'
df.loc[:, ['cabin_group']] = df['Cabin'].str[0] | Titanic - Machine Learning from Disaster |
12,472,732 | epoch = 3
batch_size = 16
num_classes = 5
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )<choose_model_class> | train_data.loc[:, ['age_group', 'Survived']].groupby('age_group' ).agg({'Survived':'sum'} ) | Titanic - Machine Learning from Disaster |
12,472,732 | resNet = timm.create_model("resnet50", pretrained=False)
resNet.load_state_dict(torch.load(".. /input/pretrined-models/models/models/pretrained_resNet.pth"))
resNet.fc = nn.Linear(resNet.fc.in_features, num_classes)
resNet = resNet.to(device )<load_pretrained> | train_data.loc[:, ['parch_group', 'Survived']].groupby('parch_group' ).agg({'Survived':'sum'} ) | Titanic - Machine Learning from Disaster |
12,472,732 | ef_model = timm.create_model("tf_efficientnet_b2_ns", pretrained=False)
ef_model.load_state_dict(torch.load(".. /input/pretrined-models/models/models/pretrained_ef_model.pth"))
ef_model.classifier = nn.Linear(ef_model.classifier.in_features, num_classes)
ef_model = ef_model.to(device )<choose_model_class> | train_data = pd.get_dummies(train_data, columns=['Pclass'], prefix='P')
train_data = pd.get_dummies(train_data, columns=['age_group'], prefix='AG')
train_data = pd.get_dummies(train_data, columns=['Sex'], prefix='S')
train_data = pd.get_dummies(train_data, columns=['parch_group'], prefix='PA')
train_data = pd.get_d... | Titanic - Machine Learning from Disaster |
12,472,732 | ef_optimizer = torch.optim.AdamW(ef_model.parameters() , lr=1e-4, weight_decay=0.0001)
ef_scheduler = torch.optim.lr_scheduler.StepLR(ef_optimizer, step_size=2, gamma=0.1)
resNet_optimizer = torch.optim.AdamW(resNet.parameters() , lr=1e-4, weight_decay=0.0001)
resNet_scheduler = torch.optim.lr_scheduler.StepLR(resNe... | print(train_data.isnull().sum())
print(len(train_data)) | Titanic - Machine Learning from Disaster |
12,472,732 | def calc_correction(model, df):
model.eval()
path = df["path"]
label = df["label"]
count = 0
pred_list = [0, 0, 0, 0, 0]
for i in tqdm(range(len(path))):
image_path = path[i]
image_label = label[i]
image = Image.open(image_path)
image = valid_transform(image)
image = image.unsqueeze(0 ).to(device)
model = model.to(d... | test_data = pd.read_csv("/kaggle/input/titanic/test.csv" ) | Titanic - Machine Learning from Disaster |
12,472,732 | def train_model(model, dataset, batch_size, optimizer, criterion, scheduler, epoch, model_title):
best_model = None
best_loss = float("inf")
train_losses, valid_losses = [], []
kf = KFold(n_splits = 5)
for fold,(train_index, valid_index)in enumerate(kf.split(dataset)) :
print("fold: ", fold)
train_dataset = Subset(d... | test_data = test_data.loc[:,['PassengerId', 'Pclass', 'Sex', 'Age','Parch', 'SibSp', 'Cabin']] | Titanic - Machine Learning from Disaster |
12,472,732 | train_models(resNet, ef_model )<load_pretrained> | test_data = pd.get_dummies(test_data, columns=['Pclass'], prefix='P')
test_data = pd.get_dummies(test_data, columns=['age_group'], prefix='AG')
test_data = pd.get_dummies(test_data, columns=['Sex'], prefix='S')
test_data = pd.get_dummies(test_data, columns=['parch_group'], prefix='PA')
test_data = pd.get_dummies(te... | Titanic - Machine Learning from Disaster |
12,472,732 | ef_model.load_state_dict(torch.load(".. /input/models/ef_model.pth", map_location = device))
resNet.load_state_dict(torch.load(".. /input/models/res_model.pth", map_location = device))<choose_model_class> | print(test_data.isnull().sum())
print(len(test_data)) | Titanic - Machine Learning from Disaster |
12,472,732 | class CassaveClassifier(nn.Module):
def __init__(self, model, ef_model):
super().__init__()
self.model = model
self.ef_model = ef_model
def forward(self, x):
x1 = self.model(x)
x2 = self.ef_model(x)
return(0.5 * x1 + 0.5 * x2)
def test(self, x, rate):
x1 = self.model(x)
x2 = self.ef_model(x)
p = rate * x1 +(1 - ra... | Titanic - Machine Learning from Disaster | |
12,472,732 | classifier = CassaveClassifier(resNet, ef_model)
classifier = classifier.to(device )<define_search_space> | y = train_data["Survived"]
features = ['P_1','P_2','P_3','AG_0.0','AG_1.0','AG_2.0','AG_3.0','S_0', 'S_1']
X = train_data.loc[:, features]
X_train, X_test, y_train, y_test = train_test_split(X, y)
| Titanic - Machine Learning from Disaster |
12,472,732 | def test_rate() :
for rate in range(1, 10):
classifier.eval()
path = valid_df["path"]
label = valid_df["label"]
count = 0
pred_list = [0, 0, 0, 0, 0]
for i in tqdm(range(len(path))):
image_path = path[i]
image_label = label[i]
image = Image.open(image_path)
image = valid_transform(image)
image = image.unsqueeze(0 ).t... | ss = StandardScaler()
ss.fit_transform(X_train)
ss.transform(X_test ) | Titanic - Machine Learning from Disaster |
12,472,732 | path = ".. /input/cassava-leaf-disease-classification/test_images/"<define_variables> | model_lr = LogisticRegression(solver='liblinear', max_iter=1000)
model_lr.fit(X_train, y_train)
predictions_lr = model_lr.predict(X_test ) | Titanic - Machine Learning from Disaster |
12,472,732 | image_path = []
image_id = []
for i in os.listdir(path):
image_id.append(str(i))
image_path.append(path + str(i))<categorify> | score_train = model_lr.score(X_train, y_train)
score_test = model_lr.score(X_test, y_test)
print(score_train, score_test ) | Titanic - Machine Learning from Disaster |
12,472,732 | pred = []
for path in image_path:
image = Image.open(path)
image = valid_transform(image)
image = image.unsqueeze(0 ).to(device)
predict = resNet(image ).argmax(1 ).item()
pred.append(predict )<create_dataframe> | thresholds = model_lr.decision_function(X_train)
fpr, tpr, thresholds = roc_curve(y_train, thresholds ) | Titanic - Machine Learning from Disaster |
12,472,732 | sub = pd.DataFrame({"image_id": image_id, "label": pred} )<save_to_csv> | print(precision_score(y_test, predictions_lr))
print(recall_score(y_test, predictions_lr)) | Titanic - Machine Learning from Disaster |
12,472,732 | sub.to_csv("submission.csv", index=False )<categorify> | model_knn = KNeighborsClassifier(n_neighbors = 10, p = 1)
model_knn.fit(X_train, y_train)
predictions_knn = model_knn.predict(X_test ) | Titanic - Machine Learning from Disaster |
12,472,732 | warnings.filterwarnings(action="ignore")
class CategoricalFeatures:
def __init__(self,df,categorical_features, encoding_type,handle_na=False):
self.df = df
self.cat_feats = categorical_features
self.enc_type = encoding_type
self.handle_na = handle_na
self.label_encoders = dict()
self.binary_encoders = dict()
self.ohe ... | probabilities = model_knn.predict_proba(X_train)
fpr, tpr, threshold = roc_curve(y_train, probabilities[:, 1] ) | Titanic - Machine Learning from Disaster |
12,472,732 | sample.loc[:,"target"] = preds
sample.to_csv("submission_csv", index=False)
<save_to_csv> | score_train = model_knn.score(X_train, y_train)
score_test = model_knn.score(X_test, y_test)
print(score_train, score_test ) | Titanic - Machine Learning from Disaster |
12,472,732 | print(sample.to_csv )<load_from_csv> | model = model_knn
X_test = test_data.loc[:, features]
predictions = model.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,407,320 | df = pd.read_csv("/kaggle/input/cat-in-the-dat-ii/train.csv", index_col="id")
df_test = pd.read_csv("/kaggle/input/cat-in-the-dat-ii/test.csv", index_col="id")
y = df["target"]
D = df.drop(columns="target")
features = D.columns
test_ids = df_test.index
D_all = pd.concat([D, df_test])
num_train = len(D)
print(f"D_a... | train_data = pd.read_csv("/kaggle/input/titanic/train.csv")
train_data.head() | Titanic - Machine Learning from Disaster |
14,407,320 | ord_maps = {
"ord_0": {val: i for i, val in enumerate([1, 2, 3])},
"ord_1": {
val: i
for i, val in enumerate(
["Novice", "Contributor", "Expert", "Master", "Grandmaster"]
)
},
"ord_2": {
val: i
for i, val in enumerate(
["Freezing", "Cold", "Warm", "Hot", "Boiling Hot", "Lava Hot"]
)
},
**{col: {val: i for i, val ... | avg_mean = train_data["Age"].astype('float' ).mean(axis=0 ) | Titanic - Machine Learning from Disaster |
14,407,320 | oh_cols = D_all.columns.difference(ord_maps.keys() - {"day", "month"})
print(f"OneHot encoding {len(oh_cols)} columns")
one_hot = pd.get_dummies(
D_all[oh_cols],
columns=oh_cols,
drop_first=True,
dummy_na=True,
sparse=True,
dtype="int8",
).sparse.to_coo()<data_type_conversions> | train_data.drop("Cabin", axis = 1, inplace=True ) | Titanic - Machine Learning from Disaster |
14,407,320 | ord_cols = pd.concat([D_all[col].map(ord_map ).fillna(max(ord_map.values())//2 ).astype("float32")for col, ord_map in ord_maps.items() ], axis=1)
ord_cols /= ord_cols.max()
ord_cols_sqr = 4*(ord_cols - 0.5)**2<split> | train_data.drop("Name", axis = 1, inplace=True ) | Titanic - Machine Learning from Disaster |
14,407,320 | X = scipy.sparse.hstack([one_hot, ord_cols, ord_cols_sqr] ).tocsr()
print(f"X.shape = {X.shape}")
X_train, X_test, y_train, y_test = train_test_split(X[:num_train], y, test_size=0.1, random_state=42, shuffle=False)
X_train = X_train[:10000]
y_train = y_train[:10000]
X_test = X_test[:2000]
y_test = y_test[:2000]<choos... | train_data["Embarked"].replace(np.nan, 'S', inplace=True ) | Titanic - Machine Learning from Disaster |
14,407,320 | log = LogisticRegression(C=0.05, solver="lbfgs", max_iter=5000)
dtree = DecisionTreeClassifier(random_state=4)
rtree = RandomForestClassifier(n_estimators=100, random_state=4)
svm = SVC(random_state=4, probability=True)
nb = GaussianNB()
gbc = GradientBoostingClassifier()
knn = KNeighborsClassifier(n_neighbors=400)... | train_data["Age"] = train_data["Age"].astype("int" ) | Titanic - Machine Learning from Disaster |
14,407,320 | model_algorithm(log, X_train, y_train, X_test, y_test, 'LogisticRegression', labels, features )<compute_test_metric> | test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
test_data.head() | Titanic - Machine Learning from Disaster |
14,407,320 | model_algorithm(svm, X_train, y_train, X_test, y_test, 'SVM', labels, features )<compute_test_metric> | avg_mean = test_data["Age"].astype('float' ).mean(axis=0)
test_data["Age"].replace(np.nan, avg_mean, inplace=True)
test_data["Age"].astype("int")
Favg_mean = test_data["Fare"].astype('float' ).mean(axis=0)
test_data["Fare"].replace(np.nan, Favg_mean, inplace=True ) | Titanic - Machine Learning from Disaster |
14,407,320 | model_algorithm(knn, X_train, y_train, X_test, y_test, 'KNearestNeighbor', labels, features )<compute_test_metric> | parameters = {
"n_estimators":[5,10,50,100,250],
"max_depth":[2,4,8,16,32,None]
} | Titanic - Machine Learning from Disaster |
14,407,320 | model_algorithm(adaboost, X_train, y_train, X_test, y_test, 'AdaBoost', labels, features )<compute_test_metric> | lm =RandomForestClassifier(n_estimators=250, max_depth=8, random_state=1)
y = train_data["Survived"]
features = ["Pclass", "Sex", "Age", "SibSp", "Parch","Fare","Embarked"]
X = pd.get_dummies(train_data[features])
X_test = pd.get_dummies(test_data[features])
lm.fit(X, train_data['Survived'] ) | Titanic - Machine Learning from Disaster |
14,407,320 | model_algorithm(gbc, X_train, y_train, X_test, y_test, 'GradientBoosting', labels, features )<compute_test_metric> | predictions = lm.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,643,676 | model_algorithm(dtree, X_train, y_train, X_test, y_test, 'DecisionTree', labels, None )<compute_test_metric> | train_data = pd.read_csv("/kaggle/input/titanic/train.csv")
test_data = pd.read_csv("/kaggle/input/titanic/test.csv" ) | Titanic - Machine Learning from Disaster |
14,643,676 | model_algorithm(rtree, X_train, y_train, X_test, y_test, 'RandomForest', labels, features )<save_to_csv> | label_encoder_sex = LabelEncoder() | Titanic - Machine Learning from Disaster |
14,643,676 | clf=LogisticRegression(C=0.05, solver="lbfgs", max_iter=5000)
clf.fit(X_train, y_train)
pred = clf.predict_proba(X_test)[:, 1]
pd.DataFrame({"id": test_ids, "target": pred} ).to_csv("submission_lr.csv", index=False )<load_from_csv> | train_data.iloc[:,4] = label_encoder_sex.fit_transform(train_data.iloc[:,4])
| Titanic - Machine Learning from Disaster |
14,643,676 | p = '.. /input/cat-in-the-dat-ii/'
X = pd.concat([pd.read_csv(p+'train.csv' ).iloc[:,1:-1],
pd.read_csv(p+'test.csv' ).iloc[:,1:]] ).astype('str')
y = pd.read_csv(p+'train.csv' ).target
sample = pd.read_csv(p+'sample_submission.csv')
X = OneHotEncoder().fit_transform(X)
train,test = X[:600000],X[600000:]
sample['tar... | test_data.iloc[:,3] = label_encoder_sex.fit_transform(test_data.iloc[:,3] ) | Titanic - Machine Learning from Disaster |
14,643,676 | !wget https://download.knime.org/analytics-platform/linux/knime_4.1.2.linux.gtk.x86_64.tar.gz
!tar xvzf knime_4.1.2.linux.gtk.x86_64.tar.gz
!rm knime_4.1.2.linux.gtk.x86_64.tar.gz
!unzip./knime_4.1.2/knime-workspace.zip -d./knime_4.1.2/knime-workspace/
!rm./knime_4.1.2/knime-workspace.zip
!cp -R /kaggle/input/knime-cat... | X_train = train_data[["PassengerId", "Sex", "SibSp", "Parch", "Pclass"]]
Y_train = train_data["Survived"] | Titanic - Machine Learning from Disaster |
14,643,676 | knime.executable_path = "./knime_4.1.2/knime"
workspace = "./knime_4.1.2/knime-workspace"
workflow = "knime-cat-publ/cat_publ/cat_publ"<choose_model_class> | X_test = test_data[["PassengerId", "Sex", "SibSp", "Parch", "Pclass"]] | Titanic - Machine Learning from Disaster |
14,643,676 | knime.Workflow(workflow_path=workflow,workspace_path=workspace )<concatenate> | my_imputer = SimpleImputer()
X_train1 = my_imputer.fit_transform(X_train)
X_test1 = my_imputer.fit_transform(X_test ) | Titanic - Machine Learning from Disaster |
14,643,676 | with knime.Workflow(workflow_path=workflow,workspace_path=workspace)as wf:
wf.execute()<define_variables> | sc = StandardScaler()
X_train1 = sc.fit_transform(X_train1)
X_test1 = sc.fit_transform(X_test1 ) | Titanic - Machine Learning from Disaster |
14,643,676 |
<import_modules> | import keras
from keras.models import Sequential
from keras.layers import Dense | Titanic - Machine Learning from Disaster |
14,643,676 | sample_submission = pd.read_csv(".. /input/cat-in-the-dat-ii/sample_submission.csv")
test = pd.read_csv(".. /input/cat-in-the-dat-ii/test.csv")
train = pd.read_csv(".. /input/cat-in-the-dat-ii/train.csv")
<feature_engineering> | model = Sequential() | Titanic - Machine Learning from Disaster |
14,643,676 | train["nom_0by1"]=train.nom_0.str.cat(train['nom_1'])
train["nom_0by2"]=train.nom_0.str.cat(train['nom_2'])
train["nom_0by3"]=train.nom_0.str.cat(train['nom_3'])
train["nom_0by4"]=train.nom_0.str.cat(train['nom_4'])
test["nom_0by1"]=test.nom_0.str.cat(test['nom_1'])
test["nom_0by2"]=test.nom_0.str.cat(test['nom_2'... | model.add(Dense(units = 4, activation = 'relu', input_dim = 5))
model.add(Dense(units = 3, activation = 'relu'))
model.add(Dense(units = 2, activation = 'relu'))
model.add(Dense(units = 1, activation = 'sigmoid'))
| Titanic - Machine Learning from Disaster |
14,643,676 | train['day_obj']=train.day.astype('str')
test['day_obj']=test.day.astype('str')
train['month_obj']=train.month.astype('str')
test['month_obj']=test.month.astype('str')
train['ord_0_obj']=train.ord_0
train['ord_1_obj']=train.ord_1
train['ord_2_obj']=train.ord_2
train['ord_3_obj']=train.ord_3
train['ord_4_obj']=train... | model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'] ) | Titanic - Machine Learning from Disaster |
14,643,676 | train["daybymonth"]=train.month_obj.str.cat(train['day_obj'])
test["daybymonth"]=test.month_obj.str.cat(test['day_obj'] )<define_variables> | model.fit(X_train1, Y_train, epochs = 100 ) | Titanic - Machine Learning from Disaster |
14,643,676 | cat_cols=['nom_5','nom_6','nom_7','nom_8','nom_9','day_obj','month_obj','ord_0_obj','ord_1_obj','ord_2_obj','ord_3_obj','ord_4_obj',
'ord_5_obj',
'nom_0_obj','nom_1_obj','nom_2_obj','nom_3_obj','nom_4_obj',
'bin_0_obj','bin_1_obj','bin_2_obj','bin_3_obj','bin_4_obj',
"nom_3by4","bin_4bynom_0"]
for c in cat_cols:
data_t... | prediction = model.predict(X_test1 ) | Titanic - Machine Learning from Disaster |
14,643,676 | train['nom_mean']=(train.nom_5+train.nom_6+train.nom_7)/3
test['nom_mean']=(test.nom_5+test.nom_6+test.nom_7)/3<define_variables> | pred = []
for i in prediction:
if i[0] < 0.5:
pred.append(0)
else:
pred.append(1 ) | Titanic - Machine Learning from Disaster |
14,643,676 | cols_to_use = ['ord_1', 'ord_2', 'ord_3', 'ord_4','ord_5','nom_0','nom_1','nom_2','nom_3','nom_4','bin_3','bin_4']
num_cols_to_use = ['ord_0','bin_0','bin_1','bin_2','day','month','nom_5','nom_6','nom_7','nom_8','nom_9','day_obj','month_obj',
'ord_0_obj','ord_1_obj','ord_2_obj','ord_3_obj','ord_4_obj','ord_5_obj',
'nom... | pred = np.array(pred ) | Titanic - Machine Learning from Disaster |
14,643,676 | val_predictions = my_pipeline.predict(val_X)
print(roc_auc_score(val_y,val_predictions))<save_to_csv> | output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': pred})
len(output ) | Titanic - Machine Learning from Disaster |
14,643,676 | ss=sample_submission
ss.target = prediction
ss.to_csv("submission.csv", index=False )<import_modules> | output.to_csv('my_submission_nn_1.csv', index = False)
print("Your submission was successfully saved!" ) | Titanic - Machine Learning from Disaster |
14,593,543 | from collections import defaultdict
from glob import glob
from random import choice, sample
import cv2
import numpy as np
import pandas as pd
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau,EarlyStopping
from keras.layers import Input, Dense, Flatten, GlobalMaxPool2D, GlobalAvgPool2D, Concatenate, Multip... | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns | Titanic - Machine Learning from Disaster |
14,593,543 | train_file_path = ".. /input/train_relationships.csv"
train_folders_path = ".. /input/train/"
val_famillies = "F09"<define_variables> | df_train=pd.read_csv('.. /input/titanic/train.csv')
df_test=pd.read_csv('.. /input/titanic/test.csv' ) | Titanic - Machine Learning from Disaster |
14,593,543 | all_images = glob(train_folders_path + "*/*/*.jpg")
train_images = [x for x in all_images if val_famillies not in x]
val_images = [x for x in all_images if val_famillies in x]<define_variables> | PassengerId=df_test['PassengerId'] | Titanic - Machine Learning from Disaster |
14,593,543 | train_person_to_images_map = defaultdict(list)
ppl = [x.split("/")[-3] + "/" + x.split("/")[-2] for x in all_images]
for x in train_images:
train_person_to_images_map[x.split("/")[-3] + "/" + x.split("/")[-2]].append(x)
val_person_to_images_map = defaultdict(list)
for x in val_images:
val_person_to_images_map[x.spli... | df_train.drop(['PassengerId','Name','Ticket'],axis=1,inplace=True)
df_test.drop(['PassengerId','Name','Ticket'],axis=1,inplace=True ) | Titanic - Machine Learning from Disaster |
14,593,543 | relationships = pd.read_csv(train_file_path)
relationships = list(zip(relationships.p1.values, relationships.p2.values))
relationships = [x for x in relationships if x[0] in ppl and x[1] in ppl]<define_variables> | df_train.isnull().sum() /len(df_train)*100 | Titanic - Machine Learning from Disaster |
14,593,543 | train = [x for x in relationships if val_famillies not in x[0]]
val = [x for x in relationships if val_famillies in x[0]]<data_type_conversions> | df_train.drop(['Cabin'],axis=1,inplace=True)
df_test.drop(['Cabin'],axis=1,inplace=True ) | Titanic - Machine Learning from Disaster |
14,593,543 | def read_img(path):
img = image.load_img(path, target_size=(197, 197))
img = np.array(img ).astype(np.float)
return preprocess_input(img, version=2 )<define_variables> | df_train.dropna(subset=['Embarked'],inplace=True)
df_train['Embarked'].isnull().sum() | Titanic - Machine Learning from Disaster |
14,593,543 | def gen(list_tuples, person_to_images_map, batch_size=16):
ppl = list(person_to_images_map.keys())
while True:
batch_tuples = sample(list_tuples, batch_size // 2)
labels = [1] * len(batch_tuples)
while len(batch_tuples)< batch_size:
p1 = choice(ppl)
p2 = choice(ppl)
if p1 != p2 and(p1, p2)not in list_tuples and(p2... | age_train_series=df_train.groupby(['Pclass','Sex'])['Age'].transform('median' ) | Titanic - Machine Learning from Disaster |
14,593,543 | def baseline_model() :
input_1 = Input(shape=(197, 197, 3))
input_2 = Input(shape=(197, 197, 3))
base_model = VGGFace(model='resnet50', include_top=False)
for x in base_model.layers[:-3]:
x.trainable = True
x1 = base_model(input_1)
x2 = base_model(input_2)
x1 = Concatenate(axis=-1 )([GlobalAvgPool2D()(x1), GlobalAvg... | age_test_series=df_test.groupby(['Pclass','Sex'])['Age'].transform('median' ) | Titanic - Machine Learning from Disaster |
14,593,543 | !pip install git+https://github.com/rcmalli/keras-vggface.git
<set_options> | df_train['Age']=df_train['Age'].fillna(age_train_series ) | Titanic - Machine Learning from Disaster |
14,593,543 | print("available RAM:", psutil.virtual_memory())
gc.collect()
print("available RAM:", psutil.virtual_memory() )<define_variables> | df_test['Age']=df_test['Age'].fillna(age_test_series ) | 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.