kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
13,482,615 | PRE_TRAINING_TIME_START = datetime.now()
AUTO = tf.data.experimental.AUTOTUNE<set_options> | cbc=CatBoostClassifier(verbose=0, n_estimators=100)
cbc.fit(X_train,y_train)
pred_cbc=cbc.predict(X_test)
| Titanic - Machine Learning from Disaster |
13,482,615 | SEED = 42
os.environ['PYTHONHASHSEED']=str(SEED)
random.seed(SEED)
np.random.seed(SEED)
os.environ['TF_DETERMINISTIC_OPS']=str(SEED)
tf.random.set_seed(SEED)
<set_options> | log=LogisticRegression(max_iter=1000)
log.fit(X_train,y_train)
pred_log=log.predict(X_test)
| Titanic - Machine Learning from Disaster |
13,482,615 | 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.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync )<define_variables> | print('XGBoost:', round(xgbclassifier.score(X_train, y_train)* 100, 2), '%.\t\t\t RandomForest:', round(randomfc.score(X_train, y_train)* 100, 2), '%.')
print('LightGBM:', round(lightgb.score(X_train, y_train)* 100, 2), '%.\t\t\t AdaBoost:', round(ada.score(X_train, y_train)* 100, 2), '%.')
print('CatBoost:', round(cbc.score(X_train, y_train)* 100, 2), '%.\t\t\t LogisticRegression:', round(log.score(X_train, y_train)* 100, 2), '%.' ) | Titanic - Machine Learning from Disaster |
13,482,615 | IMAGE_SIZE =(512, 512)
GCS_TRAIN_PATHS = [
KaggleDatasets().get_gcs_path('tfrecords'),
KaggleDatasets().get_gcs_path('tfrecords-2')
]
TRAINING_FILENAMES = []
for i in GCS_TRAIN_PATHS:
TRAINING_FILENAMES.append(tf.io.gfile.glob(i + '/*.tfrecords'))
TRAINING_FILENAMES = list(itertools.chain.from_iterable(TRAINING_FILENAMES))
GCS_TEST_PATH = KaggleDatasets().get_gcs_path('tfrecords-3')
TEST_FILENAMES = tf.io.gfile.glob(GCS_TEST_PATH + '/*.tfrecords')
print(len(TRAINING_FILENAMES))
print(len(TEST_FILENAMES))<define_variables> | print('XGBoost:', round(accuracy_score(y_test,pred_xgb)* 100, 2), '%.\t\t\t RandomForest:', round(accuracy_score(y_test,pred_rf)* 100, 2), '%.')
print('LightGBM:', round(accuracy_score(y_test,pred_lgb)* 100, 2), '%.\t\t\t AdaBoost:', round(accuracy_score(y_test,pred_ada)* 100, 2), '%.')
print('CatBoost:', round(accuracy_score(y_test,pred_cbc)* 100, 2), '%.\t\t\t LogisticRegression:', round(accuracy_score(y_test,pred_log)* 100, 2), '%.' ) | Titanic - Machine Learning from Disaster |
13,482,615 | EPOCHS = 12
DO_AUG = True
BATCH_SIZE = 256
current_epoch = 0
chance = 0
NUM_TRAINING_IMAGES = 105390
NUM_TEST_IMAGES = 12186
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE<define_variables> | X_train=train.drop('Survived',axis=1)
X_test=test.copy()
y_train = train['Survived']
model_params = {
'n_estimators': randint(4,200),
'max_features': truncnorm(a=0, b=1, loc=0.25, scale=0.1),
'min_samples_split': uniform(0.01, 0.199)
}
rf_model = RandomForestClassifier()
clf = RandomizedSearchCV(rf_model, model_params, n_iter=100, cv=5, random_state=1)
model = clf.fit(X_train, y_train)
pprint(model.best_estimator_.get_params() ) | Titanic - Machine Learning from Disaster |
13,482,615 | CLASSES = [str(c ).zfill(2)for c in range(0, 42)]<categorify> | testData=test.copy()
predictions_rf=model.predict(testData ) | Titanic - Machine Learning from Disaster |
13,482,615 | def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"words": tf.io.FixedLenFeature([6633], tf.float32),
"label": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
image = decode_image(example['image'])
words = example['words']
label = tf.cast(example['label'], tf.int32)
return(( image, words), label)
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"words": tf.io.FixedLenFeature([6633], tf.float32),
"filename": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
image = decode_image(example['image'])
words = example['words']
filename = example['filename']
return(( image, words), filename)
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=AUTO)
dataset = dataset.with_options(ignore_order)
dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
return dataset
def get_training_dataset(do_aug=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
if do_aug:
dataset = dataset.map(image_augmentation, num_parallel_calls=AUTO)
dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(AUTO)
return dataset
def get_test_dataset(ordered=False, tta=None):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
if tta == 0:
dataset = dataset.map(image_augmentation_tta_0, num_parallel_calls=AUTO)
elif tta == 1:
dataset = dataset.map(image_augmentation_tta_1, num_parallel_calls=AUTO)
elif tta == 2:
dataset = dataset.map(image_augmentation_tta_2, num_parallel_calls=AUTO)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(AUTO)
return dataset<normalization> | subm=pd.read_csv('.. /input/titanic/gender_submission.csv')
Survived=pd.Series(predictions_rf)
subm.drop(columns=['Survived'],inplace=True)
subm['Survived']=pd.Series(predictions_rf)
subm.to_csv(r'RandomForestSubmission.csv', index = False)
print("Submitted" ) | Titanic - Machine Learning from Disaster |
13,181,043 | @tf.function
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.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
c2 = tf.math.cos(shear)
s2 = tf.math.sin(shear)
shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))
@tf.function
def transform(image):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
if tf.random.uniform(shape=[], minval=0, maxval=2, dtype=tf.int32, seed=SEED)== 0:
rot = 17.* tf.random.normal([1],dtype='float32')
else:
rot = tf.constant([0],dtype='float32')
if tf.random.uniform(shape=[], minval=0, maxval=2, dtype=tf.int32, seed=SEED)== 0:
shr = 5.5 * tf.random.normal([1],dtype='float32')
else:
shr = tf.constant([0],dtype='float32')
if tf.random.uniform(shape=[], minval=0, maxval=3, dtype=tf.int32, seed=SEED)== 0:
h_zoom = tf.random.normal([1],dtype='float32')/8.5
if h_zoom > 0:
h_zoom = 1.0 + h_zoom * -1
else:
h_zoom = 1.0 + h_zoom
else:
h_zoom = tf.constant([1],dtype='float32')
if tf.random.uniform(shape=[], minval=0, maxval=3, dtype=tf.int32, seed=SEED)== 0:
w_zoom = tf.random.normal([1],dtype='float32')/8.5
if w_zoom > 0:
w_zoom = 1.0 + w_zoom * -1
else:
w_zoom = 1.0 + w_zoom
else:
w_zoom = tf.constant([1],dtype='float32')
if tf.random.uniform(shape=[], minval=0, maxval=3, dtype=tf.int32, seed=SEED)== 0:
h_shift = 18.* tf.random.normal([1],dtype='float32')
else:
h_shift = tf.constant([0],dtype='float32')
if tf.random.uniform(shape=[], minval=0, maxval=3, dtype=tf.int32, seed=SEED)== 0:
w_shift = 18.* tf.random.normal([1],dtype='float32')
else:
w_shift = tf.constant([0],dtype='float32')
m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
z = tf.ones([DIM*DIM],dtype='int32')
idx = tf.stack([x,y,z])
idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3] )<prepare_x_and_y> | train_data = pd.read_csv("/kaggle/input/titanic/train.csv")
test_data = pd.read_csv("/kaggle/input/titanic/test.csv")
train_data | Titanic - Machine Learning from Disaster |
13,181,043 | @tf.function
def transform_grid_mark(image, inv_mat, image_shape):
h, w, c = image_shape
cx, cy = w//2, h//2
new_xs = tf.repeat(tf.range(-cx, cx, 1), h)
new_ys = tf.tile(tf.range(-cy, cy, 1), [w])
new_zs = tf.ones([h*w], dtype=tf.int32)
old_coords = tf.matmul(inv_mat, tf.cast(tf.stack([new_xs, new_ys, new_zs]), tf.float32))
old_coords_x, old_coords_y = tf.round(old_coords[0, :] + tf.cast(w, tf.float32)//2.) , tf.round(old_coords[1, :] + tf.cast(h, tf.float32)//2.)
old_coords_x = tf.cast(old_coords_x, tf.int32)
old_coords_y = tf.cast(old_coords_y, tf.int32)
clip_mask_x = tf.logical_or(old_coords_x<0, old_coords_x>w-1)
clip_mask_y = tf.logical_or(old_coords_y<0, old_coords_y>h-1)
clip_mask = tf.logical_or(clip_mask_x, clip_mask_y)
old_coords_x = tf.boolean_mask(old_coords_x, tf.logical_not(clip_mask))
old_coords_y = tf.boolean_mask(old_coords_y, tf.logical_not(clip_mask))
new_coords_x = tf.boolean_mask(new_xs+cx, tf.logical_not(clip_mask))
new_coords_y = tf.boolean_mask(new_ys+cy, tf.logical_not(clip_mask))
old_coords = tf.cast(tf.stack([old_coords_y, old_coords_x]), tf.int32)
new_coords = tf.cast(tf.stack([new_coords_y, new_coords_x]), tf.int64)
rotated_image_values = tf.gather_nd(image, tf.transpose(old_coords))
rotated_image_channel = list()
for i in range(c):
vals = rotated_image_values[:,i]
sparse_channel = tf.SparseTensor(tf.transpose(new_coords), vals, [h, w])
rotated_image_channel.append(tf.sparse.to_dense(sparse_channel, default_value=0, validate_indices=False))
return tf.transpose(tf.stack(rotated_image_channel), [1,2,0])
@tf.function
def random_rotate(image, angle, image_shape):
def get_rotation_mat_inv(angle):
angle = math.pi * angle / 180
cos_val = tf.math.cos(angle)
sin_val = tf.math.sin(angle)
one = tf.constant([1], tf.float32)
zero = tf.constant([0], tf.float32)
rot_mat_inv = tf.concat([cos_val, sin_val, zero,
-sin_val, cos_val, zero,
zero, zero, one], axis=0)
rot_mat_inv = tf.reshape(rot_mat_inv, [3,3])
return rot_mat_inv
angle = float(angle)* tf.random.normal([1],dtype='float32')
rot_mat_inv = get_rotation_mat_inv(angle)
return transform_grid_mark(image, rot_mat_inv, image_shape)
@tf.function
def grid_mask() :
h = tf.constant(IMAGE_SIZE[0], dtype=tf.float32)
w = tf.constant(IMAGE_SIZE[1], dtype=tf.float32)
image_height, image_width =(h, w)
d1 = 112
d2 = 352
rotate_angle = 45
ratio = 0.6
hh = tf.math.ceil(tf.math.sqrt(h*h+w*w))
hh = tf.cast(hh, tf.int32)
hh = hh+1 if hh%2==1 else hh
d = tf.random.uniform(shape=[], minval=d1, maxval=d2, dtype=tf.int32)
l = tf.cast(tf.cast(d,tf.float32)*ratio+0.5, tf.int32)
st_h = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)
st_w = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)
y_ranges = tf.range(-1 * d + st_h, -1 * d + st_h + l)
x_ranges = tf.range(-1 * d + st_w, -1 * d + st_w + l)
for i in range(0, hh//d+1):
s1 = i * d + st_h
s2 = i * d + st_w
y_ranges = tf.concat([y_ranges, tf.range(s1,s1+l)], axis=0)
x_ranges = tf.concat([x_ranges, tf.range(s2,s2+l)], axis=0)
x_clip_mask = tf.logical_or(x_ranges <0 , x_ranges > hh-1)
y_clip_mask = tf.logical_or(y_ranges <0 , y_ranges > hh-1)
clip_mask = tf.logical_or(x_clip_mask, y_clip_mask)
x_ranges = tf.boolean_mask(x_ranges, tf.logical_not(clip_mask))
y_ranges = tf.boolean_mask(y_ranges, tf.logical_not(clip_mask))
hh_ranges = tf.tile(tf.range(0,hh), [tf.cast(tf.reduce_sum(tf.ones_like(x_ranges)) , tf.int32)])
x_ranges = tf.repeat(x_ranges, hh)
y_ranges = tf.repeat(y_ranges, hh)
y_hh_indices = tf.transpose(tf.stack([y_ranges, hh_ranges]))
x_hh_indices = tf.transpose(tf.stack([hh_ranges, x_ranges]))
y_mask_sparse = tf.SparseTensor(tf.cast(y_hh_indices, tf.int64), tf.zeros_like(y_ranges), [hh, hh])
y_mask = tf.sparse.to_dense(y_mask_sparse, 1, False)
x_mask_sparse = tf.SparseTensor(tf.cast(x_hh_indices, tf.int64), tf.zeros_like(x_ranges), [hh, hh])
x_mask = tf.sparse.to_dense(x_mask_sparse, 1, False)
mask = tf.expand_dims(tf.clip_by_value(x_mask + y_mask, 0, 1), axis=-1)
mask = random_rotate(mask, rotate_angle, [hh, hh, 1])
mask = tf.image.crop_to_bounding_box(mask,(hh-tf.cast(h, tf.int32)) //2,(hh-tf.cast(w, tf.int32)) //2, tf.cast(image_height, tf.int32), tf.cast(image_width, tf.int32))
return mask
@tf.function
def apply_grid_mask(image):
mask = grid_mask()
mask = tf.concat([mask, mask, mask], axis=-1)
return image * tf.cast(mask, 'float32' )<normalization> | women = train_data.loc[train_data.Sex == 'female']["Survived"]
rate_women = sum(women)/len(women)
print("% of women who survived:", rate_women*100)
men = train_data.loc[train_data.Sex == 'male']["Survived"]
rate_men = sum(men)/len(men)
print("% of men who survived", rate_men*100)
passengers = train_data.Survived.values
rate_passengers = sum(passengers)/len(passengers)
print("
% of all passengers who survived", rate_passengers*100)
print("% of survivors who were women: ", 100*sum(women)/sum(passengers))
print("% of survivors who were men: ", 100*sum(men)/sum(passengers))
print("
% of passengers who were women:", 100*len(train_data.loc[train_data.Sex == 'female'])/len(train_data))
print("% of passengers who were men:",100*len(train_data.loc[train_data.Sex == 'male'])/len(train_data))
| Titanic - Machine Learning from Disaster |
13,181,043 | @tf.function
def image_augmentation_tta_0(iw, filename):
max_chance = 8
image, words = iw
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.flip_left_right(image)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_brightness(image, 0.1)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_contrast(image, 0.9, 1.1)
return(( image, words), filename)
@tf.function
def image_augmentation_tta_1(iw, filename):
max_chance = 8
image, words = iw
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.flip_left_right(image)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_brightness(image, 0.1)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_contrast(image, 0.9, 1.1)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_saturation(image, 0.95, 1.05)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_hue(image, 0.05)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = transform(image)
return(( image, words), filename)
@tf.function
def image_augmentation_tta_2(iw, filename):
max_chance = 8
image, words = iw
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.flip_left_right(image)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_brightness(image, 0.1)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_contrast(image, 0.9, 1.1)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_saturation(image, 0.95, 1.05)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = tf.image.random_hue(image, 0.05)
if tf.random.uniform(shape=[], minval=0, maxval=11, dtype=tf.int32, seed=SEED)< max_chance:
image = transform(image)
if tf.random.uniform(shape=[], minval=0, maxval=10, dtype=tf.int32, seed=SEED)< max_chance:
image = apply_grid_mask(image)
return(( image, words), filename )<import_modules> | withsbsp=train_data.loc[train_data.Survived == 0]["SibSp"]
print("Average number of siblings/spouses for those who died: {}".format(sum(withsbsp)/len(withsbsp)))
survivedsbsp = train_data.loc[train_data.Survived == 1]["SibSp"]
print("Average number of siblings/spouses for those who survived: {}".format(sum(survivedsbsp)/len(survivedsbsp)))
nmen = train_data.loc[train_data.Survived == 0][train_data.Sex == 'male']["Parch"]
ymen = train_data.loc[train_data.Survived == 1][train_data.Sex == 'male']["Parch"]
print("
Average number of children/parents per man who did not survive: {}".format(sum(nmen)/len(nmen)))
print("Average number of children/parents per man who survived: {}".format(sum(ymen)/len(ymen)))
| Titanic - Machine Learning from Disaster |
13,181,043 | from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Input, Flatten, Dense, Dropout, AveragePooling2D, GlobalAveragePooling2D, SpatialDropout2D, BatchNormalization, Activation, Concatenate<init_hyperparams> | male=train_data.loc[train_data.Sex=='male']
nmen = train_data.loc[train_data.Survived == 0][train_data.Sex == 'male'][train_data.Parch >=1]
ymen = train_data.loc[train_data.Survived == 1][train_data.Sex == 'male'][train_data.Parch >=1]
mediann=np.median(nmen.Parch)
mediany=np.median(ymen.Parch)
print("
Average number of children/Fathers per man who did not survive: {}
The median is {}"
.format(sum(nmen.Parch)/len(nmen),mediann))
print("Average number of children/Fathers per man who survived: {}
The median is {}"
.format(sum(ymen.Parch)/len(ymen),mediany))
print("% of men with children/parents: ", 100*(len(nmen)+len(ymen)) /len(male)) | Titanic - Machine Learning from Disaster |
13,181,043 | class EpochCallback(tf.keras.callbacks.Callback):
def on_epoch_begin(self, epoch, logs=None):
global current_epoch
global chance
current_epoch = epoch
if current_epoch < 2:
chance = 0
elif current_epoch < 9:
chance = current_epoch - 1
else:
chance = 8
print(f'Epoch
print(datetime.now() )<choose_model_class> | train_data1 = train_data.drop(['Name', 'Ticket','Cabin','Embarked','PassengerId'], axis = 1)
train_data1
X_test = test_data.drop(['Name', 'Ticket','Cabin','Embarked','PassengerId'], axis = 1)
train_data1 = pd.get_dummies(train_data1)
train_data1 = train_data1.drop(['Sex_male'],axis=1)
X_test=pd.get_dummies(X_test)
X_test= X_test.drop(['Sex_male'],axis=1)
| Titanic - Machine Learning from Disaster |
13,181,043 | es_val_acc = tf.keras.callbacks.EarlyStopping(
monitor='val_sparse_categorical_accuracy', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=True
)
es_val_loss = tf.keras.callbacks.EarlyStopping(
monitor='val_loss', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=True
)
es_acc = tf.keras.callbacks.EarlyStopping(
monitor='sparse_categorical_accuracy', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=False
)
es_loss = tf.keras.callbacks.EarlyStopping(
monitor='loss', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=False
)
epoch_cb = EpochCallback()<choose_model_class> | c1a = int(( train_data1.loc[train_data1.Pclass ==1])['Age'].mean())
c2a = int(( train_data1.loc[train_data1.Pclass ==2])['Age'].mean())
c3a = int(( train_data1.loc[train_data1.Pclass ==3])['Age'].mean())
print(c1a,c2a,c3a)
a =train_data1.loc[train_data.Pclass==1].fillna({'Age':c1a})
train_data1.loc[train_data.Pclass==1]=a
a2=X_test.loc[X_test.Pclass==1].fillna({'Age':c1a})
X_test.loc[X_test.Pclass==1] =a2
b=train_data1.loc[train_data.Pclass==2].fillna({'Age':c2a})
train_data1.loc[train_data.Pclass==2]=b
b2=X_test.loc[X_test.Pclass==2].fillna({'Age':c2a})
X_test.loc[X_test.Pclass==2] =b2
c=train_data1.loc[train_data.Pclass==3].fillna({'Age':c3a})
train_data1.loc[train_data.Pclass==3]=c
c2=X_test.loc[X_test.Pclass==3].fillna({'Age':c3a})
X_test.loc[X_test.Pclass==3] =c2
X_test['Fare'] = X_test['Fare'].fillna(20)
| Titanic - Machine Learning from Disaster |
13,181,043 | with strategy.scope() :
efn7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3))
for layer in efn7.layers:
layer.trainable = True
model_image = Sequential([
efn7,
GlobalAveragePooling2D(name='efficientnet-b7_gap'),
], name='b7-image')
model_words = Sequential([
Input(( 6633,), name='mlp-words_input'),
Dense(331, name='mlp-words_dense_1'),
BatchNormalization(name='mlp-words_bn_1'),
Activation('relu', name='mlp-words_act_1'),
Dense(110, name='mlp-words_dense_2'),
BatchNormalization(name='mlp-words_bn_2'),
Activation('relu', name='mlp-words_act_2'),
], name='mlp-words')
concatenate = Concatenate(name='concatenate' )([model_image.output, model_words.output])
output = Dense(len(CLASSES), activation='softmax', name='output' )(concatenate)
model = Model(inputs=[model_image.input, model_words.input], outputs=output)
model.compile(optimizer=tfa.optimizers.LAMB(0.01), loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
model.summary()
<train_model> | X_train = train_data1.drop(columns=["Survived"])
y_train = train_data1.Survived
params = {'n_estimators': [1,200],
'max_features': [1,6],
'max_depth': [1,None],
'min_samples_split': [2,10],
'min_samples_leaf': [1,10],
'criterion':['gini','entropy']
}
forest = RandomForestClassifier()
forest_cv = RandomizedSearchCV(forest, params, cv=5)
forest_cv.fit(X_train,y_train)
print("Tuned Decision Tree Parameters: {}".format(forest_cv.best_params_))
print("Best score is {}".format(forest_cv.best_score_))
| Titanic - Machine Learning from Disaster |
13,181,043 | <init_hyperparams><EOS> | y_pred = forest_cv.predict(X_test)
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': y_pred})
output.to_csv('my_submission.csv', index=False)
print("Your submission was successfully saved!" ) | Titanic - Machine Learning from Disaster |
13,359,181 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<train_model> | %matplotlib inline
warnings.filterwarnings('ignore' ) | Titanic - Machine Learning from Disaster |
13,359,181 | model.fit(
get_training_dataset(do_aug=DO_AUG), steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[es_acc, epoch_cb, lr_schedule], verbose=1
)<compute_test_metric> | train = pd.read_csv(".. /input/titanic/train.csv")
test = pd.read_csv(".. /input/titanic/test.csv")
train.describe(include="all" ) | Titanic - Machine Learning from Disaster |
13,359,181 | h = model.history
plt_acc(h)
plt_loss(h )<feature_engineering> | ids = test['PassengerId'] | Titanic - Machine Learning from Disaster |
13,359,181 | POST_TRAINING_TIME_START = datetime.now()<predict_on_test> | Cat_Features = ['Sex', 'Pclass', 'SibSp', 'Parch', 'Embarked'] | Titanic - Machine Learning from Disaster |
13,359,181 | def test(tta=None):
test_ds = get_test_dataset(ordered=True, tta=tta)
print(f'Computing predictions for TTA {tta}...')
test_images_ds = test_ds.map(lambda iw, filename: [iw])
model_pred = model.predict(test_images_ds)
return model_pred<categorify> | print(pd.isnull(train ).sum() ) | Titanic - Machine Learning from Disaster |
13,359,181 | model_pred = test(tta=None)
model_pred_tta_0 = test(tta=0)
model_pred_tta_1 = test(tta=1)
model_pred_tta_2 = test(tta=2 )<prepare_output> | all_data = pd.concat([train.drop(columns='Survived'), test], ignore_index=True)
print(all_data.shape ) | Titanic - Machine Learning from Disaster |
13,359,181 | pred_plain = np.argmax(model_pred, axis=-1)
test_ds = get_test_dataset(ordered=True)
test_ids_ds = test_ds.map(lambda iw, filename: filename ).unbatch()
test_ids = next(iter(test_ids_ds.batch(pred_plain.shape[0])) ).numpy().astype('U')
df_submission = pd.DataFrame({'filename': test_ids, 'category': pred_plain})
df_submission = df_submission.drop_duplicates()
df_submission['category'] = df_submission['category'].apply(lambda c: str(c ).zfill(2))
df_submission<save_to_csv> | for feature in ['PassengerId','Cabin', 'Ticket']:
all_data.drop(feature, axis = 1, inplace=True)
all_data.head() | Titanic - Machine Learning from Disaster |
13,359,181 | df_submission.to_csv('submission.csv', index=False)
!head submission.csv<feature_engineering> | all_data['Embarked'].fillna(all_data['Embarked'].mode() [0], inplace = True)
all_data['Fare'].fillna(all_data['Fare'].median() , inplace = True)
| Titanic - Machine Learning from Disaster |
13,359,181 | pred_tta_0 = np.mean(np.array([model_pred, model_pred_tta_0]), axis=0)
pred_tta_0 = np.argmax(pred_tta_0, axis=-1)
test_ds = get_test_dataset(ordered=True)
test_ids_ds = test_ds.map(lambda iw, filename: filename ).unbatch()
test_ids = next(iter(test_ids_ds.batch(pred_tta_0.shape[0])) ).numpy().astype('U')
df_submission_tta_0 = pd.DataFrame({'filename': test_ids, 'category': pred_tta_0})
df_submission_tta_0 = df_submission_tta_0.drop_duplicates()
df_submission_tta_0['category'] = df_submission_tta_0['category'].apply(lambda c: str(c ).zfill(2))
df_submission_tta_0<save_to_csv> | all_data['Title'] = all_data.Name.str.extract('([A-Za-z]+)\.', expand=False)
all_data['Title'].value_counts() | Titanic - Machine Learning from Disaster |
13,359,181 | df_submission_tta_0.to_csv('submission_tta_0.csv', index=False)
!head submission_tta_0.csv<feature_engineering> | frequent_titles = all_data['Title'].value_counts() [:5].index.tolist()
frequent_titles | Titanic - Machine Learning from Disaster |
13,359,181 | pred_tta_all = np.mean(np.array([model_pred, model_pred_tta_0, model_pred_tta_1, model_pred_tta_2]), axis=0)
pred_tta_all = np.argmax(pred_tta_all, axis=-1)
test_ds = get_test_dataset(ordered=True)
test_ids_ds = test_ds.map(lambda iw, filename: filename ).unbatch()
test_ids = next(iter(test_ids_ds.batch(pred_tta_all.shape[0])) ).numpy().astype('U')
df_submission_tta_all = pd.DataFrame({'filename': test_ids, 'category': pred_tta_all})
df_submission_tta_all = df_submission.drop_duplicates()
df_submission_tta_all['category'] = df_submission_tta_all['category'].apply(lambda c: str(c ).zfill(2))
df_submission_tta_all<save_to_csv> | all_data['Title'] = all_data['Title'].apply(lambda x: x if x in frequent_titles else 'Other')
| Titanic - Machine Learning from Disaster |
13,359,181 | df_submission_tta_all.to_csv('submission_tta_all.csv', index=False)
!head submission_tta_all.csv<load_pretrained> | median_ages = {}
for title in frequent_titles:
median_ages[title] = all_data.loc[all_data['Title'] == title]['Age'].median()
median_ages['Other'] = all_data['Age'].median()
all_data.loc[all_data['Age'].isnull() , 'Age'] = all_data[all_data['Age'].isnull() ]['Title'].map(median_ages ) | Titanic - Machine Learning from Disaster |
13,359,181 | model.save('model.h5')
model.save_weights('model_weights.h5' )<train_model> | num_bins = 5
feature = 'Fare'
labels = [feature + '_' + str(i + 1)for i in range(num_bins)]
all_data['FareBin'] = pd.qcut(all_data['Fare'], num_bins, labels ) | Titanic - Machine Learning from Disaster |
13,359,181 | print(f'Post training time : {(datetime.now() - POST_TRAINING_TIME_START ).total_seconds() } seconds' )<define_variables> | used_features = ['Age', 'Fare','Name']
for feature in used_features:
all_data.drop(feature, axis = 1, inplace=True ) | Titanic - Machine Learning from Disaster |
13,359,181 | numeric_features_train = list(train.select_dtypes(exclude =
['object', 'category'] ).columns)
numeric_features_test = list(test.select_dtypes(exclude =
['object', 'category'] ).columns)
print("numeric_features_train = ", numeric_features_train)
print("Len = ", len(numeric_features_train))
print("
numeric_features_test = ", numeric_features_test)
print("Len = ", len(numeric_features_test))<count_missing_values> | all_data = pd.get_dummies(all_data)
all_data.head() | Titanic - Machine Learning from Disaster |
13,359,181 | print(train.isnull().any())
print(test.isnull().any() )<drop_column> | target = train['Survived']
train = all_data.iloc[: len(train)]
test = all_data.iloc[len(train):]
train.shape | Titanic - Machine Learning from Disaster |
13,359,181 | SP = train.pop('SalePrice' )<split> | MLA = [
ensemble.AdaBoostClassifier() ,
ensemble.BaggingClassifier() ,
ensemble.ExtraTreesClassifier() ,
ensemble.GradientBoostingClassifier() ,
ensemble.RandomForestClassifier() ,
gaussian_process.GaussianProcessClassifier() ,
linear_model.LogisticRegressionCV() ,
linear_model.PassiveAggressiveClassifier() ,
linear_model.RidgeClassifierCV() ,
linear_model.SGDClassifier() ,
linear_model.Perceptron() ,
naive_bayes.BernoulliNB() ,
naive_bayes.GaussianNB() ,
neighbors.KNeighborsClassifier() ,
svm.SVC(probability=True),
svm.NuSVC(probability=True),
svm.LinearSVC() ,
tree.DecisionTreeClassifier() ,
tree.ExtraTreeClassifier() ,
discriminant_analysis.LinearDiscriminantAnalysis() ,
discriminant_analysis.QuadraticDiscriminantAnalysis() ,
XGBClassifier()
]
cv_split = model_selection.ShuffleSplit(n_splits = 10, test_size =.3, random_state = 0)
MLA_columns = ['MLA Name', 'MLA Train Accuracy Mean', 'MLA Validation Accuracy Mean', 'MLA Validation Accuracy STD']
MLA_compare = pd.DataFrame(columns = MLA_columns)
estimators = []
for row_index, alg in enumerate(MLA):
alg_name = alg.__class__.__name__
MLA_compare.loc[row_index, 'MLA Name'] = alg_name
print(alg.__class__.__name__)
cv_results = model_selection.cross_validate(alg, train, target, cv=cv_split, return_estimator=True, return_train_score=True)
estimators += list(cv_results['estimator'])
MLA_compare.loc[row_index, 'MLA Train Accuracy Mean'] = cv_results['train_score'].mean()
MLA_compare.loc[row_index, 'MLA Validation Accuracy Mean'] = cv_results['test_score'].mean()
MLA_compare.loc[row_index, 'MLA Validation Accuracy STD'] = cv_results['test_score'].std()
MLA_compare.sort_values(by = ['MLA Validation Accuracy Mean'], ascending = False, inplace = True)
MLA_compare
| Titanic - Machine Learning from Disaster |
13,359,181 | def getTheta(r):
X_train, X_test , y_train, y_test = train_test_split(train_X, SP,
test_size = 0.2,
random_state = r)
theta = np.dot(np.linalg.pinv(X_train), y_train)
print("Training Error =",rmse(predictTarget(X_train, theta), y_train))
print("Validation Error = ", rmse(predictTarget(X_test, theta), y_test))
return theta<predict_on_test> | def hard_voting(estimators, X):
Y = np.zeros([X.shape[0], len(estimators)], dtype=int)
for i, estimator in enumerate(estimators):
Y[:, i] = estimator.predict(X)
y = np.zeros(X.shape[0], dtype=int)
for i in range(X.shape[0]):
y[i] = np.argmax(np.bincount(Y[i,:]))
return y
y_predict = hard_voting(estimators, train)
accuracy_score(target, y_predict)
| Titanic - Machine Learning from Disaster |
13,359,181 | <predict_on_test><EOS> | predictions = hard_voting(estimators, test)
output = pd.DataFrame({ 'PassengerId' : ids, 'Survived': predictions })
output.to_csv('submission_voting_cross_validation.csv', index=False ) | Titanic - Machine Learning from Disaster |
13,410,275 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<predict_on_test> | for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
| Titanic - Machine Learning from Disaster |
13,410,275 | prediction = np.zeros(( test_X.shape[0], 1))
rList = [42, 3, 468, 12, 120, 130, 234, 1000, 100, 200, 1200, 5, 45,
49, 300, 320,980, 81, 2100, 1420, 768]
for r in rList:
y1 = predictTarget(test_X, getTheta(r))
print(prediction.shape)
prediction = np.hstack(( prediction,y1.reshape(y1.shape[0], 1)) )<prepare_output> | ds_train = pd.read_csv('/kaggle/input/titanic/train.csv')
ds_output = pd.read_csv('/kaggle/input/titanic/test.csv' ) | Titanic - Machine Learning from Disaster |
13,410,275 | prediction = np.sum(prediction, axis = 1)/len(rList )<save_to_csv> | X_train = ds_train.drop(['PassengerId','Name','Ticket'],axis=1)
X_output = ds_output.drop(['PassengerId','Name','Ticket'],axis=1 ) | Titanic - Machine Learning from Disaster |
13,410,275 | sub = pd.DataFrame()
sub['Id'] = test['Id']
sub['SalePrice'] = prediction
sub.to_csv("prediction.csv", index = False )<set_options> | X_train['Cabin'].isna().sum() / X_train.shape[0] | Titanic - Machine Learning from Disaster |
13,410,275 | %matplotlib inline
sns.set()<load_from_csv> | X_train = X_train.drop(['Cabin'],axis=1)
X_output = X_output.drop(['Cabin'],axis=1 ) | Titanic - Machine Learning from Disaster |
13,410,275 | sub = pd.read_csv('.. /input/sample_submission.csv' )<load_from_disk> | print(f"Count : {X_train['Embarked'].isna().sum() } / {X_train.shape[0]} = {X_train['Embarked'].isna().sum() /X_train.shape[0]}")
print(f"Most common letter : {np.squeeze(X_train['Embarked'].mode())}" ) | Titanic - Machine Learning from Disaster |
13,410,275 | with open('.. /input/train_annotations.json/train_annotations.json','r')as anno_train:
train = json.load(anno_train)
with open('.. /input/test_annotations.json/test_annotations.json','r')as anno_test:
test = json.load(anno_test )<create_dataframe> | letter_dictionnary = X_train['Embarked'].astype('category' ).cat.categories | Titanic - Machine Learning from Disaster |
13,410,275 | test_df = pd.DataFrame()
test_df = test_df.append(test['images'], ignore_index=True )<create_dataframe> | X_train['Sex']=X_train['Sex'].astype('category' ).cat.codes
X_output["Sex"]=X_output["Sex"].astype('category' ).cat.codes | Titanic - Machine Learning from Disaster |
13,410,275 | train_df = pd.DataFrame()
train_df = train_df.append(train['images'], ignore_index=True)
train_df_anno = pd.DataFrame()
train_df_anno = train_df_anno.append(train['annotations'], ignore_index=True)
train_df['category_id'] = train_df_anno['category_id']
del train_df_anno
gc.collect()<define_variables> | X_train['Embarked']=X_train['Embarked'].astype('category' ).cat.codes
X_output['Embarked']=X_output["Embarked"].astype('category' ).cat.codes | Titanic - Machine Learning from Disaster |
13,410,275 | category_numbers = [0]*(np.max(train_df['category_id'])+1 )<feature_engineering> | X_train = pd.concat([X_train, pd.get_dummies(X_train.Pclass)], axis=1)
X_output = pd.concat([X_output, pd.get_dummies(X_output.Pclass)], axis=1)
X_train.rename(columns={1: "Pclass1", 2: "Pclass2",3:"Pclass3"}, inplace=True)
X_output.rename(columns={1: "Pclass1", 2: "Pclass2",3:"Pclass3"}, inplace=True)
X_train.drop(['Pclass'],inplace=True,axis=1)
X_output.drop(['Pclass'],inplace=True,axis=1 ) | Titanic - Machine Learning from Disaster |
13,410,275 | for i in train_df['category_id']:
category_numbers[i]+=1<define_variables> | X_train = pd.concat([X_train, pd.get_dummies(X_train.Embarked)], axis=1)
X_output = pd.concat([X_output, pd.get_dummies(X_output.Embarked)], axis=1)
X_train.rename(columns={0: f"Embarked_{letter_dictionnary[0]}", 1: f"Embarked_{letter_dictionnary[1]}",2: f"Embarked_{letter_dictionnary[2]}"}, inplace=True)
X_output.rename(columns={0: f"Embarked_{letter_dictionnary[0]}", 1: f"Embarked_{letter_dictionnary[1]}",2: f"Embarked_{letter_dictionnary[2]}"}, inplace=True)
X_train.drop(['Embarked'],inplace=True,axis=1)
X_output.drop(['Embarked'],inplace=True,axis=1 ) | Titanic - Machine Learning from Disaster |
13,410,275 | few_shot = 0
for i in category_numbers[1:]:
if i <= 200:
few_shot+=1<feature_engineering> | def normalization(column):
return(column-column.mean())/column.std() | Titanic - Machine Learning from Disaster |
13,410,275 | few_shot/len(category_numbers )<load_from_csv> | X_train['Age'],X_train['Fare'] = normalization(X_train['Age']),normalization(X_train['Fare'] ) | Titanic - Machine Learning from Disaster |
13,410,275 | df = pd.read_csv('.. /input/train.csv')
test = pd.read_csv('.. /input/test.csv' )<concatenate> | X_output['Age'],X_output['Fare'] = normalization(X_output['Age']),normalization(X_output['Fare'] ) | Titanic - Machine Learning from Disaster |
13,410,275 | df = df.append(test )<data_type_conversions> | y_train = X_train['Survived']
X_train = X_train.drop(['Survived'], axis=1 ) | Titanic - Machine Learning from Disaster |
13,410,275 | df['area'] = df['area'].str.replace(',','')
df['densidade_dem'] = df['densidade_dem'].str.replace(',','')
df['area'] = df['area'].astype(float)
df['densidade_dem'] = df['densidade_dem'].astype(float )<feature_engineering> | X_train.reset_index(drop=True, inplace=True)
y_train.reset_index(drop=True, inplace=True)
X_output.reset_index(drop=True, inplace=True ) | Titanic - Machine Learning from Disaster |
13,410,275 | df['populacao'] = df['populacao'].str.replace(',','')
df['populacao'] = df['populacao'].str.replace('(2)','')
df['populacao'] = df['populacao'].str.replace('(','')
df['populacao'] = df['populacao'].str.replace(')','')
df['populacao'] = df['populacao'].str.replace('.','')
df['populacao'] = df['populacao'].astype(int )<feature_engineering> | X_train,X_test,y_train,y_test = train_test_split(X_train,y_train ) | Titanic - Machine Learning from Disaster |
13,410,275 | df['comissionados_por_servidor'] = df['comissionados_por_servidor'].str.replace('
df['comissionados_por_servidor'] = df['comissionados_por_servidor'].str.replace('!','')
df['comissionados_por_servidor'] = df['comissionados_por_servidor'].str.replace('%','')
df['comissionados_por_servidor'] = df['comissionados_por_servidor'].astype(float)
df['comissionados_por_servidor'] = df['comissionados_por_servidor']/100<categorify> | hyperparameters = {'C': np.arange(0.5,4,0.2), 'kernel':['linear', 'rbf', 'sigmoid'], 'gamma':np.linspace(10**-3,1,50)}
grid = GridSearchCV(svm.SVC() , hyperparameters, cv=5)
grid.fit(X_train,y_train)
C, kernel, gamma = grid.best_params_['C'],grid.best_params_['kernel'],grid.best_params_['gamma']
print(f"Best score : {grid.best_score_} for hyperparameters : {grid.best_params_}" ) | Titanic - Machine Learning from Disaster |
13,410,275 | df_porte = pd.get_dummies(df['porte'])
df_regiao = pd.get_dummies(df['regiao'] )<concatenate> | KM = KMeans(n_clusters=30)
KM.fit(X_train,y_train)
print(f"Best score : {completeness_score(KM.predict(X_test),y_test)} for hyperparameters : n_clusters = 15" ) | Titanic - Machine Learning from Disaster |
13,410,275 | df = pd.concat([df, df_porte], axis=1)
df = pd.concat([df, df_regiao], axis=1 )<import_modules> | hyperparameters = {'n_neighbors': np.arange(1,50), 'metric': ['euclidean','manhattan']}
grid = GridSearchCV(KNeighborsClassifier() , hyperparameters, cv=5)
grid.fit(X_train,y_train)
n_neighbors,metric = grid.best_params_['n_neighbors'],grid.best_params_['metric']
print(f"Best score : {grid.best_score_} for hyperparameters : {grid.best_params_}" ) | Titanic - Machine Learning from Disaster |
13,410,275 | import matplotlib.pyplot as plt
import seaborn as sns<split> | hyperparameters = {'n_estimators': [1500,2000,2500,3000,4000],'max_features':['auto','sqrt','log2'], 'max_depth':[10,20,30]}
grid = GridSearchCV(RandomForestClassifier() , hyperparameters, cv=5)
grid.fit(X_train,y_train)
n_estimators,max_features,max_depth = grid.best_params_['n_estimators'],grid.best_params_['max_features'],grid.best_params_['max_depth']
print(f"Best score : {grid.best_score_} for hyperparameters : {grid.best_params_}" ) | Titanic - Machine Learning from Disaster |
13,410,275 | test = df[df['nota_mat'].isnull() ]
<filter> | hyperparameters = {'n_estimators': [500,700,800,900,1000],'max_features':['auto','sqrt','log2'], 'max_depth':[10,20,30]}
grid = GridSearchCV(ExtraTreesClassifier() , hyperparameters, cv=5)
grid.fit(X_train,y_train)
n_e,max_f,max_d= grid.best_params_['n_estimators'],grid.best_params_['max_features'],grid.best_params_['max_depth']
print(f"Best score : {grid.best_score_} for hyperparameters : {grid.best_params_}" ) | Titanic - Machine Learning from Disaster |
13,410,275 | df = df[~df['nota_mat'].isnull() ]<split> | best_mean_score = 0 | Titanic - Machine Learning from Disaster |
13,410,275 | train, valid = train_test_split(df, random_state=42 )<define_variables> | sv = svm.SVC(C=C, kernel=kernel, gamma=gamma)
sv.fit(X_train,y_train)
sv_mean_score, sv_std_score = cross_val_score(sv,X_test, y_test, cv = 5 ).mean() ,cross_val_score(sv,X_test, y_test, cv = 5 ).std()
print(sv_mean_score, sv_std_score)
if sv_mean_score>best_mean_score:
best_mean_score = sv_mean_score
model = "sv" | Titanic - Machine Learning from Disaster |
13,410,275 | removed_cols = ['municipio', 'estado', 'codigo_mun', 'porte', 'regiao', 'nota_mat','capital']
feats = [c for c in df.columns if c not in removed_cols]<import_modules> | knn = KNeighborsClassifier(n_neighbors, metric=metric)
knn.fit(X_train,y_train)
knn_mean_score, knn_std_score = cross_val_score(knn,X_test, y_test, cv = 5 ).mean() ,cross_val_score(knn,X_test, y_test, cv = 5 ).std()
print(knn_mean_score, knn_std_score)
if knn_mean_score>best_mean_score:
best_mean_score = knn_mean_score
model = "knn" | Titanic - Machine Learning from Disaster |
13,410,275 | from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier<choose_model_class> | rdf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, max_features=max_features)
rdf.fit(X_train,y_train)
rdf_mean_score, rdf_std_score = cross_val_score(rdf, X_test, y_test, cv = 5 ).mean() ,cross_val_score(rdf, X_test, y_test, cv = 5 ).std()
print(rdf_mean_score, rdf_std_score)
if rdf_mean_score>best_mean_score:
best_mean_score = rdf_mean_score
model = "rdf" | Titanic - Machine Learning from Disaster |
13,410,275 | models = {'RandomForest': RandomForestClassifier(random_state=42, min_samples_leaf=8,
min_samples_split=3, n_jobs=-1, n_estimators=75),
'ExtraTrees': ExtraTreesClassifier(random_state=42, n_jobs=-1),
'GradientBoosting': GradientBoostingClassifier(random_state=42),
'DecisionTree': DecisionTreeClassifier(random_state=42),
'AdaBoost': AdaBoostClassifier(random_state=42),
'KNM 11': KNeighborsClassifier(n_neighbors=11, n_jobs=-1),}<import_modules> | clf = ExtraTreesClassifier(n_estimators=n_e, max_depth=max_d,max_features=max_f)
clf.fit(X_train,y_train)
clf_mean_score, clf_std_score = cross_val_score(clf, X_test, y_test, cv = 5 ).mean() ,cross_val_score(clf, X_test, y_test, cv = 5 ).std()
print(clf_mean_score, clf_std_score)
if clf_mean_score>best_mean_score:
best_mean_score = clf_mean_score
model = "clf" | Titanic - Machine Learning from Disaster |
13,410,275 | from sklearn.metrics import accuracy_score<predict_on_test> | if model=="svm":
y_output = sv.predict(X_output)
elif model=="knn":
y_output = knn.predict(X_output)
elif model=="rdf":
y_output = rdf.predict(X_output)
else:
y_output = clf.predict(X_output)
print("Chosen model :", model ) | Titanic - Machine Learning from Disaster |
13,410,275 | def run_model(models, train, valid, feats, y_name):
model.fit(train[feats], train[y_name])
preds = model.predict(valid[feats])
return accuracy_score(valid[y_name], preds )<find_best_params> | submission = ds_output["PassengerId"] | Titanic - Machine Learning from Disaster |
13,410,275 | scores = []
for name, model in models.items() :
score = run_model(model, train.fillna(-1), valid.fillna(-1), feats, 'nota_mat')
scores.append(score)
print(name, ':', score )<concatenate> | submission = pd.DataFrame(submission ) | Titanic - Machine Learning from Disaster |
13,410,275 | train = train.append(valid )<choose_model_class> | submission['Survived']=y_output | Titanic - Machine Learning from Disaster |
13,410,275 | rf = RandomForestClassifier(random_state=42, min_samples_leaf=8, min_samples_split=3, n_jobs=-1, n_estimators=200 )<train_model> | submission.set_index('PassengerId',drop=True, inplace=True ) | Titanic - Machine Learning from Disaster |
13,410,275 | rf.fit(train[feats].fillna(-1), train['nota_mat'] )<predict_on_test> | submission.to_csv(r'/kaggle/working/submission.csv' ) | Titanic - Machine Learning from Disaster |
13,055,333 | test['nota_mat'] = rf.predict(test[feats].fillna(-1))<save_to_csv> | train_data = pd.read_csv(".. /input/titanic/train.csv")
train_data.head() | Titanic - Machine Learning from Disaster |
13,055,333 | test[['codigo_mun','nota_mat']].to_csv('randomforest.csv', index=False )<load_from_csv> | test_data = pd.read_csv(".. /input/titanic/test.csv")
test_data.head() | Titanic - Machine Learning from Disaster |
13,055,333 | df = pd.read_csv('.. /input/train.csv')
df.shape<load_from_csv> | train_data["relatives"] = train_data["SibSp"] + train_data["Parch"]
test_data["relatives"] = test_data["SibSp"] + test_data["Parch"] | Titanic - Machine Learning from Disaster |
13,055,333 | df_test = pd.read_csv('.. /input/test.csv')
df_test.shape<concatenate> | train_data["Sex_cat"] = train_data["Sex"].astype("category" ) | Titanic - Machine Learning from Disaster |
13,055,333 | df = df.append(df_test, ignore_index=True, sort=False)
df.shape<data_type_conversions> | test_data["Sex_cat"] = test_data["Sex"].astype("category" ) | Titanic - Machine Learning from Disaster |
13,055,333 | df['populacao'] = df['populacao'].str.replace('.', '')
df['populacao'] = df['populacao'].str.replace('\(\)', '')
df['populacao'] = df['populacao'].str.replace('\(1\)', '')
df['populacao'] = df['populacao'].str.replace('\(2\)', '')
df['populacao'] = df['populacao'].str.replace(',', '' ).astype('float')
df['densidade_dem'] = df['densidade_dem'].str.replace(',', '' ).astype('float')
df['area'] = df['area'].str.replace(',', '' ).astype('float')
df['comissionados_por_servidor'] = df['comissionados_por_servidor'].str.replace('
df['comissionados_por_servidor'] = df['comissionados_por_servidor'].str.replace('%', '' ).astype('float' )<data_type_conversions> | train_data["Embarked_filled"] = train_data["Embarked_filled"].astype("category")
test_data["Embarked_filled"] = test_data["Embarked_filled"].astype("category" ) | Titanic - Machine Learning from Disaster |
13,055,333 | df['in_na_densidade_dem'] = df['densidade_dem'].isna().astype('int')
df['densidade_dem'].fillna(df['densidade_dem'].mean() , inplace=True)
df['in_na_participacao_transf_receita'] = df['participacao_transf_receita'].isna().astype('int')
df['participacao_transf_receita'].fillna(-1, inplace=True)
df['in_na_servidores'] = df['servidores'].isna().astype('int')
df['servidores'].fillna(-1, inplace=True)
df['in_na_perc_pop_econ_ativa'] = df['perc_pop_econ_ativa'].isna().astype('int')
df['perc_pop_econ_ativa'].fillna(-1, inplace=True)
df['in_na_gasto_pc_saude'] = df['gasto_pc_saude'].isna().astype('int')
df['gasto_pc_saude'].fillna(-1, inplace=True)
df['in_na_hab_p_medico'] = df['hab_p_medico'].isna().astype('int')
df['hab_p_medico'].fillna(-1, inplace=True)
df['in_na_exp_vida'] = df['exp_vida'].isna().astype('int')
df['exp_vida'].fillna(df['exp_vida'].mean() , inplace=True)
df['in_na_gasto_pc_educacao'] = df['gasto_pc_educacao'].isna().astype('int')
df['gasto_pc_educacao'].fillna(-1, inplace=True)
df['in_na_exp_anos_estudo'] = df['exp_anos_estudo'].isna().astype('int')
df['exp_anos_estudo'].fillna(-1, inplace=True )<feature_engineering> | train_data["Fare_filled"] = train_data["Fare"].fillna(0)
test_data["Fare_filled"] = test_data["Fare"].fillna(0 ) | Titanic - Machine Learning from Disaster |
13,055,333 | ordem_porte = ['Pequeno porte 1', 'Pequeno porte 2', 'Médio porte', 'Grande porte']
df['porte'] = pd.Categorical(df['porte'], categories=ordem_porte ).codes
df['div_gasto'] = df['gasto_pc_saude'] / df['pib']
df['exp_pib'] = df['pib'] / df['exp_vida']
df['exp_pib_estudos'] = df['pib'] / df['exp_anos_estudo']<data_type_conversions> | train_data["Fare_filled"] = train_data["Fare_filled"].astype(int)
test_data["Fare_filled"] = test_data["Fare_filled"].astype(int ) | Titanic - Machine Learning from Disaster |
13,055,333 | for col in df.columns:
if df[col].dtype == 'object':
df[col] = df[col].astype('category' ).cat.codes<split> | train_data["Cabin_filled"] = train_data["Cabin"].fillna("U0")
deck = []
for data in train_data["Cabin_filled"]:
if data[0][0] == "U":
deck.append("U")
elif data[0][0] == "A":
deck.append("A")
elif data[0][0] == "B":
deck.append("B")
elif data[0][0] == "C":
deck.append("C")
elif data[0][0] == "D":
deck.append("D")
elif data[0][0] == "E":
deck.append("E")
elif data[0][0] == "F":
deck.append("F")
elif data[0][0] == "G":
deck.append("G")
deck.append("U")
train_data["Deck"] = deck | Titanic - Machine Learning from Disaster |
13,055,333 | test = df[df['nota_mat'].isnull() ]
df = df[~df['nota_mat'].isnull() ]<filter> | test_data["Cabin_filled"] = test_data["Cabin"].fillna("U0")
deck_test = []
for data in test_data["Cabin_filled"]:
if data[0][0] == "U":
deck_test.append("U")
elif data[0][0] == "A":
deck_test.append("A")
elif data[0][0] == "B":
deck_test.append("B")
elif data[0][0] == "C":
deck_test.append("C")
elif data[0][0] == "D":
deck_test.append("D")
elif data[0][0] == "E":
deck_test.append("E")
elif data[0][0] == "F":
deck_test.append("F")
elif data[0][0] == "G":
deck_test.append("G")
test_data["Deck"] = deck_test | Titanic - Machine Learning from Disaster |
13,055,333 | df = df[df['populacao'] > 5000].copy()<split> | data = [train_data, test_data]
for dataset in data:
mean = train_data["Age"].mean()
std = test_data["Age"].std()
is_null = dataset["Age"].isnull().sum()
rand_age = np.random.randint(mean - std, mean + std, size = is_null)
age_slice = dataset["Age"].copy()
age_slice[np.isnan(age_slice)] = rand_age
dataset["Age_filled"] = age_slice
dataset["Age_filled"] = dataset["Age_filled"].astype(int)
test_data["Age_filled"].isnull().sum() | Titanic - Machine Learning from Disaster |
13,055,333 | train, valid = train_test_split(df, test_size=0.2, random_state=42 )<define_variables> | data = [train_data, test_data]
for dataset in data:
dataset['Age_filled'] = dataset['Age_filled'].astype(int)
dataset.loc[ dataset['Age_filled'] <= 11, 'Age_filled'] = 0
dataset.loc[(dataset['Age_filled'] > 11)&(dataset['Age_filled'] <= 18), 'Age_filled'] = 1
dataset.loc[(dataset['Age_filled'] > 18)&(dataset['Age_filled'] <= 22), 'Age_filled'] = 2
dataset.loc[(dataset['Age_filled'] > 22)&(dataset['Age_filled'] <= 27), 'Age_filled'] = 3
dataset.loc[(dataset['Age_filled'] > 27)&(dataset['Age_filled'] <= 33), 'Age_filled'] = 4
dataset.loc[(dataset['Age_filled'] > 33)&(dataset['Age_filled'] <= 40), 'Age_filled'] = 5
dataset.loc[(dataset['Age_filled'] > 40)&(dataset['Age_filled'] <= 66), 'Age_filled'] = 6
dataset.loc[ dataset['Age_filled'] > 66, 'Age_filled'] = 6
test_data['Age_filled'].value_counts() | Titanic - Machine Learning from Disaster |
13,055,333 | feats = [c for c in df.columns if c not in ['nota_mat', 'codigo_mun', 'municipio']]<import_modules> | train_data["Deck_cat"] = train_data["Deck"].astype("category")
test_data["Deck_cat"] = test_data["Deck"].astype("category" ) | Titanic - Machine Learning from Disaster |
13,055,333 | from sklearn.ensemble import RandomForestClassifier<choose_model_class> | from sklearn.ensemble import RandomForestClassifier | Titanic - Machine Learning from Disaster |
13,055,333 | rf = RandomForestClassifier(n_estimators=200, min_samples_split=5, max_depth=4, random_state=42 )<train_model> | y = train_data["Survived"] | Titanic - Machine Learning from Disaster |
13,055,333 | rf.fit(train[feats], train['nota_mat'] )<predict_on_test> | X = train_data[["Pclass", "Sex_cat", "relatives", "Deck_cat", "Age_filled"]]
X_test = test_data[["Pclass", "Sex_cat", "relatives", "Deck_cat", "Age_filled"]] | Titanic - Machine Learning from Disaster |
13,055,333 | preds = rf.predict(valid[feats] )<compute_test_metric> | X["Sex_cat"] = X["Sex_cat"].cat.codes
X_test["Sex_cat"] = X_test["Sex_cat"].cat.codes | Titanic - Machine Learning from Disaster |
13,055,333 | accuracy_score(valid['nota_mat'], preds )<count_values> | X["Deck_cat"] = X["Deck_cat"].cat.codes
X_test["Deck_cat"] = X_test["Deck_cat"].cat.codes | Titanic - Machine Learning from Disaster |
13,055,333 | valid['nota_mat'].value_counts()<predict_on_test> | model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)
| Titanic - Machine Learning from Disaster |
13,055,333 | pred_test = rf.predict(test[feats] )<save_to_csv> | model.fit(X, y ) | Titanic - Machine Learning from Disaster |
13,055,333 | r1 = pd.DataFrame({'codigo_mun': test['codigo_mun'], 'nota_mat': pred_test})
r1.to_csv('r1.csv', index=False )<compute_train_metric> | predictions = model.predict(X_test ) | Titanic - Machine Learning from Disaster |
13,055,333 | def cv(df, test, feats, y_name, k=5):
preds, score, fis = [], [], []
chunk = df.shape[0] // k
for i in range(k):
if i+1 < k:
valid = df.iloc[i*chunk:(i+1)*chunk]
train = df.iloc[:i*chunk].append(df.iloc[(i+1)*chunk:])
else:
valid = df.iloc[i*chunk:]
train = df.iloc[:i*chunk]
rf = RandomForestClassifier(random_state=42, n_jobs=-1, n_estimators=200)
rf.fit(train[feats], train[y_name])
score.append(accuracy_score(valid[y_name], rf.predict(valid[feats])))
preds.append(rf.predict(test[feats]))
fis.append(rf.feature_importances_)
print(i, 'OK')
return score, preds, fis<compute_test_metric> | output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions} ) | Titanic - Machine Learning from Disaster |
13,055,333 | score, preds, fis = cv(df, test, feats, 'nota_mat' )<save_to_csv> | output.to_csv('my_submission.csv', index=False)
print("Your submission was successfully saved!" ) | Titanic - Machine Learning from Disaster |
13,290,484 | r2 = pd.DataFrame({'codigo_mun': test['codigo_mun'], 'nota_mat': preds[1]})
r2.to_csv('r2.csv', index=False )<import_modules> | train_data = pd.read_csv(".. /input/titanic/train.csv")
train_data.head() | Titanic - Machine Learning from Disaster |
13,290,484 | import lightgbm as lgb<compute_train_metric> | missing_val_count_by_column =(train_data.isnull().sum())
print(missing_val_count_by_column[missing_val_count_by_column > 0] ) | Titanic - Machine Learning from Disaster |
13,290,484 | def cv(df, test, feats, y_name, k=5):
preds, score, fis = [], [], []
chunk = df.shape[0] // k
for i in range(k):
if i+1 < k:
valid = df.iloc[i*chunk:(i+1)*chunk]
train = df.iloc[:i*chunk].append(df.iloc[(i+1)*chunk:])
else:
valid = df.iloc[i*chunk:]
train = df.iloc[:i*chunk]
rf = lgb.LGBMClassifier(min_child_samples=500)
rf.fit(train[feats], train[y_name], eval_set=[(train[feats], train['nota_mat']),(valid[feats], valid['nota_mat'])], early_stopping_rounds=50)
score.append(accuracy_score(valid[y_name], rf.predict(valid[feats])))
preds.append(rf.predict(test[feats]))
fis.append(rf.feature_importances_)
print(i, 'OK')
return score, preds, fis<compute_test_metric> | features = ['Pclass', 'Sex','SibSp','Age','Parch','Fare','Embarked']
X = pd.get_dummies(train_data[features])
y = train_data["Survived"] | Titanic - Machine Learning from Disaster |
13,290,484 | score, preds, fis = cv(df, test, feats, 'nota_mat' )<save_to_csv> | my_imputer = SimpleImputer()
imputed_X = my_imputer.fit_transform(X ) | Titanic - Machine Learning from Disaster |
13,290,484 | r3 = pd.DataFrame({'codigo_mun': test['codigo_mun'], 'nota_mat': preds[1]})
r3.to_csv('r3.csv', index=False )<set_options> | train_X, val_X, train_y, val_y = train_test_split(imputed_X,y,random_state=1 ) | Titanic - Machine Learning from Disaster |
13,290,484 | gc.enable()<set_options> | tree = DecisionTreeClassifier()
tree.fit(train_X, train_y)
tree.score(val_X,val_y ) | Titanic - Machine Learning from Disaster |
13,290,484 | tf.compat.v1.disable_eager_execution()<define_variables> | dumb_tree = DecisionTreeClassifier(max_depth=1)
dumb_tree.fit(train_X, train_y)
dumb_tree.score(val_X,val_y ) | Titanic - Machine Learning from Disaster |
13,290,484 | CATEGORY_CNT = 54
BATCH_SIZE = 256
PREDICT_BATCH_SIZE = 256
EPOCHS = 10
STEPS_PER_EPOCH = 3000
VAL_STEPS_PER_EPOCH = 100
WORD2VEC_DIM = 200
FASTTEXT_DIM = 200
EXP_DECAY_COEF = 0.75
VERBOSE = 1
MAXLEN = 300
TRAINABLE_EMBED_SIZE = 75<load_pretrained> | smart_tree = DecisionTreeClassifier(max_depth=4,min_impurity_decrease=.004)
smart_tree.fit(train_X, train_y)
smart_tree.score(val_X,val_y ) | Titanic - Machine Learning from Disaster |
13,290,484 | def save_object(obj, name):
f = open(name, 'wb')
pickle.dump(obj, f)
f.close()
def load_object(name):
f = open(name, 'rb')
obj = pickle.load(f)
f.close()
return obj<load_pretrained> | def get_score(max_leaf_nodes, train_X, val_X, train_y, val_y):
model = DecisionTreeClassifier(max_leaf_nodes=max_leaf_nodes)
model.fit(train_X, train_y)
print("Max leaf nodes:", max_leaf_nodes," \t \t Score:", model.score(val_X,val_y))
return()
for max_leaf_nodes in [2,3,4,5,6,7,8,9]:
get_score(max_leaf_nodes, train_X, val_X, train_y, val_y ) | Titanic - Machine Learning from Disaster |
13,290,484 | b_cat_map = load_object(".. /input/bonus-task-pickled-data-1/b_cat_map.pkl")
f_cat_map = load_object(".. /input/bonus-task-pickled-data-1/f_cat_map.pkl")
embed_fasttext = load_object(".. /input/bonus-task-pickled-data-1/embed_fasttext.pkl")
embed_word2vec = load_object(".. /input/bonus-task-pickled-data-1/embed_word2vec.pkl")
itemid = load_object(".. /input/bonus-task-pickled-data-1/itemid.pkl")
y_train = load_object(".. /input/bonus-task-pickled-data-1/y_train.pkl")
word_index = load_object(".. /input/bonus-x/word_index.pkl" )<categorify> | test_data = pd.read_csv(".. /input/titanic/test.csv")
X_test=pd.get_dummies(test_data[features])
imputed_test=my_imputer.fit_transform(X_test ) | Titanic - Machine Learning from Disaster |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.