kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
14,376,120 | modelsEffnet = []
for path in MODELS_EFFNET:
state_dict = torch.load(path, map_location=torch.device('cpu'))
model = HuBMAPEffNet().to(device)
model.load_state_dict(state_dict)
model.eval()
model.to(device)
modelsEffnet.append(model)
del state_dict
modelsResnet = []
for path in MODELS_RESNET:
state_dict = torch.loa... | dResults = pd.DataFrame(columns = ['Model', 'MSE'] ) | Tabular Playground Series - Jan 2021 |
14,376,120 | def Make_prediction(img, tta = True):
pred = None
with torch.no_grad() :
for model in models:
p_tta = None
p = model(img)
p = torch.sigmoid(p ).detach()
if p_tta is None:
p_tta = p
else:
p_tta += p
if tta:
flips = [[-1],[-2],[-2,-1]]
for f in flips:
imgf = torch.flip(img, f)
p = model(imgf)
p = torch.flip(p, f)
p_t... | classifiers = [
DummyRegressor(strategy='median'),
SGDRegressor() ,
BayesianRidge() ,
LassoLars() ,
ARDRegression() ,
PassiveAggressiveRegressor() ,
LinearRegression() ,
LGBMRegressor() ,
RandomForestRegressor() ,
XGBRegressor() ]
for item in classifiers:
print(item)
clf = item
dResults=FitAndScoreModel(dResults,item,... | Tabular Playground Series - Jan 2021 |
14,376,120 | names, predictions = [],[]
for idx, row in tqdm(df_sample.iterrows() ,total=len(df_sample)) :
imageId = row['id']
data = rasterio.open(os.path.join(DATA, imageId+'.tiff'), transform = identity, num_threads='all_cpus')
preds = np.zeros(data.shape, dtype=np.uint8)
dataset = HuBMAPDataset(data)
dataloader = DataLoader(... | dResults.sort_values(by='MSE', ascending=True,inplace=True)
dResults.set_index('MSE',inplace=True)
dResults.head(dResults.shape[0] ) | Tabular Playground Series - Jan 2021 |
14,376,120 | print('replacement' )<save_to_csv> | import optuna.integration.lightgbm as lgbTune
| Tabular Playground Series - Jan 2021 |
14,376,120 | df = pd.DataFrame({'id':names,'predicted':predictions})
df['predicted'].loc[df[df.id == 'd488c759a'].index] = ''
df.to_csv('submission.csv', index=False )<load_pretrained> | params={'objective': 'regression',
'metric': 'rmse',
'num_leaves': 234,
'verbosity': -1,
'boosting_type': 'gbdt',
'n_jobs': -1,
'learning_rate': 0.005,
'max_depth': 8,
'tree_learner': 'serial',
'max_bin': 255,
'feature_pre_filter': False,
'bagging_fraction': 0.4134640813947842,
'bagging_freq': 1,
'feature_fraction': 0.... | Tabular Playground Series - Jan 2021 |
14,376,120 | imshow_from_file('.. /input/pics-j/small_scale.png' )<load_pretrained> | n_fold = 10
folds = KFold(n_splits=n_fold, shuffle=True, random_state=42)
train_columns = train.columns.values
oof = np.zeros(len(train))
LGBMpredictions = np.zeros(len(test))
feature_importance_df = pd.DataFrame()
for fold_,(trn_idx, val_idx)in enumerate(folds.split(train, target.values)) :
strLog = "fold {}".format(... | Tabular Playground Series - Jan 2021 |
14,376,120 | imshow_from_file('.. /input/pics-j/big_scale.png' )<define_variables> | Tabular Playground Series - Jan 2021 | |
14,376,120 |
IMAGES_DIR = '.. /input/hubmap-kidney-segmentation/test'
WEIGHTS_SMALL = '.. /input/weights-j/t198_best_model.ckpt'
WEIGHTS_BIG = '.. /input/weights-j/t246_best_model.ckpt'
OUTPUT_FILE = 'submission.csv'
THRESHOLD_SMALL = 0.6
RESIZE_FACTOR_SMALL = 0.25
ROUNDING_ORIG_SMALL = 64
OVERLAP_SMALL = 448
BASE_SIZE_CROP_SMALL... | XGparams={'colsample_bytree': 0.7,
'learning_rate': 0.01,
'max_depth': 7,
'min_child_weight': 1,
'n_estimators': 4000,
'nthread': 4,
'objective': 'reg:squarederror',
'subsample': 0.7} | Tabular Playground Series - Jan 2021 |
14,376,120 | !mkdir -p /tmp/pip/cache/
!cp.. /input/segmentationmodelspytorch/segmentation_models/efficientnet_pytorch-0.6.3.xyz /tmp/pip/cache/efficientnet_pytorch-0.6.3.tar.gz
!cp.. /input/segmentationmodelspytorch/segmentation_models/pretrainedmodels-0.7.4.xyz /tmp/pip/cache/pretrainedmodels-0.7.4.tar.gz
!cp.. /input/segmentatio... | n_fold = 10
folds = KFold(n_splits=n_fold, shuffle=True, random_state=42)
train_columns = train.columns.values
oof = np.zeros(len(train))
XGpredictions = np.zeros(len(test))
feature_importance_df = pd.DataFrame()
for fold_,(trn_idx, val_idx)in enumerate(folds.split(train, target.values)) :
strLog = "fold {}".format(fo... | Tabular Playground Series - Jan 2021 |
14,376,120 | warnings.filterwarnings("ignore" )<define_variables> | submission = pd.read_csv(input_path / 'sample_submission.csv', index_col='id')
submission.reset_index(inplace=True)
submission = submission.rename(columns = {'index':'id'} ) | Tabular Playground Series - Jan 2021 |
14,376,120 | VERBOSE = True
DATA_DIR = '.. /input/hubmap-kidney-segmentation/test'
REDUCTION = 3
TILE_SZ = 512
MEAN = np.array([0.63482309,0.47376275,0.67814029])
STD = np.array([0.17405236,0.23305763,0.1585981])
MODELS_FRESH_FROZEN = [f'.. /input/ret-r101-multi3468-lf/model_{i}.pth' for i in [0,2]] + \
[f'.. /input/ens-red345/mo... | LGBMsubmission=submission.copy()
LGBMsubmission['target'] = LGBMpredictions
LGBMsubmission.to_csv('submission_LGBM.csv', header=True, index=False)
LGBMsubmission.head() | Tabular Playground Series - Jan 2021 |
14,376,120 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if os.path.exists('tmp'):
if VERBOSE:
print("Removing 'tmp' directory")
shutil.rmtree('tmp' )<define_search_model> | XGBoostsubmission=submission.copy()
XGBoostsubmission['target'] = XGpredictions
XGBoostsubmission.to_csv('submission_XGBoost.csv', header=True, index=False)
XGBoostsubmission.head() | Tabular Playground Series - Jan 2021 |
14,376,120 | class FPN(nn.Module):
def __init__(self, input_channels:list, output_channels:list):
super().__init__()
self.convs = nn.ModuleList(
[nn.Sequential(nn.Conv2d(in_ch, out_ch*2, kernel_size=3, padding=1),
nn.ReLU(inplace=True), nn.BatchNorm2d(out_ch*2),
nn.Conv2d(out_ch*2, out_ch, kernel_size=3, padding=1))
for in_ch, out... | EnsembledSubmission=submission.copy()
EnsembledSubmission['target'] =(LGBMpredictions*0.72 + XGpredictions*0.28)
EnsembledSubmission.to_csv('ensembled_submission.csv', header=True, index=False)
EnsembledSubmission.head() | Tabular Playground Series - Jan 2021 |
14,377,327 | class UneXt50(nn.Module):
def __init__(self, stride=1, **kwargs):
super().__init__()
m = ResNet(Bottleneck, [3, 4, 6, 3], groups=32, width_per_group=4)
self.enc0 = nn.Sequential(m.conv1, m.bn1, nn.ReLU(inplace=True))
self.enc1 = nn.Sequential(nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1),
m.layer1)
sel... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import optuna
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, KFold
from sklearn.metrics import mean_squared_error
from sklearn.base i... | Tabular Playground Series - Jan 2021 |
14,377,327 | MODELS = []
for models_list in MODELS_PATHS:
models_i = []
for ij,path in enumerate(models_list):
state_dict = torch.load(path,map_location=torch.device('cpu'))
if ij < 2:
model = UneXt101()
elif ij < 5:
model = smp.Unet(encoder_name='efficientnet-b7', classes=1, activation=None, encoder_weights=None)
else:
model = sm... | df = pd.read_csv('.. /input/tabular-playground-series-jan-2021/train.csv')
df.head() | Tabular Playground Series - Jan 2021 |
14,377,327 | def _tile_resize_save(img, img_id, tile_sz, reduce=1):
x = 0
while x < img.shape[0]:
y = 0
while y < img.shape[1]:
img_tile = img[x:x+tile_sz,y:y+tile_sz]
if reduce > 1:
new_dim =(img_tile.shape[1]//reduce,img_tile.shape[0]//reduce)
img_tile = cv2.resize(img_tile, new_dim, interpolation = cv2.INTER_AREA)
save_path ... | def objective_xgb(trial, data, target):
parameters = {
'tree_method': 'gpu_hist',
'lambda': trial.suggest_loguniform('lambda', 1e-3, 10.0),
'alpha': trial.suggest_loguniform('alpha', 1e-3, 10.0),
'colsample_bytree': trial.suggest_categorical('colsample_bytree', [0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,1.0]),
'subsample': tri... | Tabular Playground Series - Jan 2021 |
14,377,327 | def load_resize(idx, reduce):
img = load_image(os.path.join(DATA_DIR,idx+'.tiff'))
init_shape = img.shape
shape = _tile_resize_save(img, idx,(MASK_SZ*REDUCTION), reduce=REDUCTION)
img = _reconstruct_img(idx,(MASK_SZ*REDUCTION)//REDUCTION, shape)
return img, init_shape<categorify> | xgb_parameters = {
'objective': 'reg:squarederror',
'tree_method': 'gpu_hist',
'n_estimators': 1000,
'lambda': 7.610705234008646,
'alpha': 0.0019377246932580476,
'colsample_bytree': 0.5,
'subsample': 0.7,
'learning_rate': 0.012,
'max_depth': 20,
'random_state': 24,
'min_child_weight': 229
} | Tabular Playground Series - Jan 2021 |
14,377,327 | def _get_nored_pads(initW, initH, upW, upH, xa, xb, ya, yb):
px = xa/(xa+xb)
py = ya/(ya+yb)
padx = upW - initW
pady = upH - initH
assert padx > 0
assert pady > 0
xa = int(px*padx)
xb = padx - xa
ya = int(py*pady)
yb = pady - ya
return xa, xb, ya, yb
def _add_padding(img, init_sz, img_shape, p0, p1):
start = ti... | def objective_lgb(trial):
X, y = df.drop(columns=['target', 'id'] ).values, df['target'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1337)
ds_train = lgb.Dataset(X_train, label=y_train)
ds_test = lgb.Dataset(X_test, label=y_test)
parameters = {
'device_type': 'gpu',
'... | Tabular Playground Series - Jan 2021 |
14,377,327 | def _split_image(img):
start = time.time()
if VERBOSE:
print(" > Splitting image into tiles...")
assert not img.shape[0]%TILE_SZ
assert not img.shape[1]%TILE_SZ
img = img.reshape(img.shape[0]//TILE_SZ,
TILE_SZ,
img.shape[1]//TILE_SZ,
TILE_SZ,
3)
img = img.transpose(0,2,1,3,4 ).reshape(-1,TILE_SZ,TILE_SZ,3)
if VERB... | lgb_parameters = {
'objective': 'regression',
'metric': 'rmse',
'boosting': 'gbdt',
'lambda_l1': 3.2737454713243543e-07,
'lambda_l2': 3.685676983230042e-06,
'num_leaves': 190,
'feature_fraction': 0.47291296723211934,
'bagging_fraction': 0.8846579981793894,
'bagging_freq': 3,
'min_child_samples': 58,
'verbose': 0,
'devi... | Tabular Playground Series - Jan 2021 |
14,377,327 | def img2tensor(img, dtype:np.dtype=np.float32):
if img.ndim==2: img = np.expand_dims(img,2)
img = np.transpose(img,(2,0,1))
return torch.from_numpy(img.astype(dtype, copy=False))
class HuBMAPTestDataset(Dataset):
def __init__(self, idxs):
self.fnames = idxs
def __len__(self):
return len(self.fnames)
def __getitem__(s... | class NonLinearTransformer(TransformerMixin):
def __init__(self):
pass
def fit(self, X, y=None):
return self
def transform(self, X, y=None):
X = X.drop(columns=['id'])
for c in X.columns:
if c == 'target':
continue
X[f'{c}^2'] = X[c] ** 2
return X | Tabular Playground Series - Jan 2021 |
14,377,327 | def _make_tiles_dataloader(idxs):
start = time.time()
ds = HuBMAPTestDataset(idxs)
dl = DataLoader(ds, BATCH_SIZE,
num_workers=NUM_WORKERS,
shuffle=False,
pin_memory=True)
if VERBOSE:
print(" > Tiles dataset created! Time =", time.time() - start)
return dl<categorify> | pipe_xgb = Pipeline([
('custom', NonLinearTransformer()),
('scaling', StandardScaler()),
('regression', xgb.XGBRegressor(**xgb_parameters))
])
pipe_lgb = Pipeline([
('custom', NonLinearTransformer()),
('scaling', StandardScaler()),
('regression', lgb.LGBMRegressor(**lgb_parameters))
] ) | Tabular Playground Series - Jan 2021 |
14,377,327 | def _generate_masks(dl, idxs, n_tiles, init_sz, group):
start = time.time()
if VERBOSE:
print(" > Generating masks...")
red = CUSTOM_REDS[group]
mp = Model_pred(MODELS[group], dl, red)
mask = torch.zeros(n_tiles,
init_sz,
init_sz,
dtype=torch.uint8)
for i, p in zip(idxs,iter(mp)) : mask[i] = p.squeeze(-1)
if VERB... | df_train = pd.read_csv('.. /input/tabular-playground-series-jan-2021/train.csv')
df_predict = pd.read_csv('.. /input/tabular-playground-series-jan-2021/test.csv' ) | Tabular Playground Series - Jan 2021 |
14,377,327 | class Model_pred:
def __init__(self, models, dl, red, half:bool=False):
self.models = models
self.dl = dl
self.half = half
self.red = red
def __iter__(self):
with torch.no_grad() :
for x in iter(self.dl):
x = x.to(device)
x = F.interpolate(x, scale_factor=1/self.red, mode='bilinear')
if self.half: x = x.half()
py = 0... | X, y = df_train.drop(columns=['target']), df_train['target'] | Tabular Playground Series - Jan 2021 |
14,377,327 | def _reshape_depad_mask(mask, init_shape, init_sz, p0, p1, xa, xb, ya, yb):
start = time.time()
if VERBOSE:
print(" > Merge tiled masks into one mask and crop padding...")
mask = mask.view(init_shape[0]//TILE_SZ,
init_shape[1]//TILE_SZ,
init_sz,
init_sz ).\
permute(0,2,1,3 ).reshape(init_shape[0]*REDUCTION,
init_sha... | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1337 ) | Tabular Playground Series - Jan 2021 |
14,377,327 | def _save_mask_tiles(mask, idx, p0, p1):
start = time.time()
if VERBOSE:
print(" > Saving tiles in HDD memory...")
x = 0
while x < mask.shape[0]:
y = 0
while y < mask.shape[1]:
mask_tile = mask[x:x+MASK_SZ,y:y+MASK_SZ].numpy()
save_path = "%s_%d_%d_%s_%s.png" %(idx, x, y, str(p0), str(p1))
Image.fromarray(mask_tile ).... | pipe_xgb.fit(X_train, y_train)
pipe_lgb.fit(X_train, y_train)
print(f'XGB Score: {pipe_xgb.score(X_test, y_test)}, LGB Score: {pipe_lgb.score(X_test, y_test)}')
print(f'XGB RMSE: {mean_squared_error(y_test, pipe_xgb.predict(X_test), squared=False)}, LGB RMSE: {mean_squared_error(y_test, pipe_lgb.predict(X_test), squ... | Tabular Playground Series - Jan 2021 |
14,377,327 | def make_one_prediction(img, group, idx, img_shape, p0, p1):
init_sz = TILE_SZ*REDUCTION
img, xa, xb, ya, yb, img_shape_p = _add_padding(img, init_sz, img_shape,
p0, p1)
img = _split_image(img)
n_tiles = img.shape[0]
idxs = _select_tiles(img)
dl = _make_tiles_dataloader(idxs)
mask = _generate_masks(dl, idxs, n_ti... | def ensemble_predict(X):
target_xgb = pipe_xgb.predict(X)
target_lgb = pipe_lgb.predict(X)
return [0.85 * x + 0.15 * l for(x, l)in zip(target_xgb, target_lgb)] | Tabular Playground Series - Jan 2021 |
14,377,327 | def get_mask_tiles(idx, p0_list, p1_list):
group = _get_group(os.path.join(DATA_DIR,idx+'.tiff'))
TH = THS[group]
img, init_shape = load_resize(idx, REDUCTION)
for p0 in p0_list:
for p1 in p1_list:
make_one_prediction(img, group, idx, init_shape, p0, p1)
return init_shape, TH<predict_on_test> | print(f'Ensemble RMSE: {mean_squared_error(y_test, ensemble_predict(X_test), squared=False)}' ) | Tabular Playground Series - Jan 2021 |
14,377,327 | def make_predictions(idx):
init_shape, TH = get_mask_tiles(idx, X_OVERLAP, Y_OVERLAP)
mask = torch.zeros(*init_shape[:2], dtype=torch.uint8)
x = 0
while x < init_shape[0]:
y = 0
while y < init_shape[1]:
mask_tile = 0.
for p0 in X_OVERLAP:
for p1 in Y_OVERLAP:
tile_path = "%s_%d_%d_%s_%s.png" %(idx, x, y, str(p0), ... | pipe_xgb.fit(X, y)
pipe_lgb.fit(X, y ) | Tabular Playground Series - Jan 2021 |
14,377,327 | <load_from_csv><EOS> | target = pd.DataFrame({
'id': df_predict['id'], 'target': ensemble_predict(df_predict)
})
target.to_csv('submission.csv', index=False ) | Tabular Playground Series - Jan 2021 |
14,208,130 | <SOS> metric: RMSE Kaggle data source: tabular-playground-series-jan-2021<predict_on_test> | PATH = '/kaggle/input/tabular-playground-series-jan-2021/' | Tabular Playground Series - Jan 2021 |
14,208,130 | for idx,row in tqdm(df_sample.iterrows() ,total=len(df_sample)) :
idx = row['id']
print("Computing predictions for image", idx)
rle = make_predictions(idx)
names.append(idx)
preds.append(rle )<save_to_csv> | train = pd.read_csv(PATH+'train.csv')
test = pd.read_csv(PATH+'test.csv')
submission = pd.read_csv(PATH+'sample_submission.csv' ) | Tabular Playground Series - Jan 2021 |
14,208,130 | df = pd.DataFrame({'id': names, 'predicted': preds})
df.to_csv('submission.csv',index=False )<install_modules> | !pip install pycaret | Tabular Playground Series - Jan 2021 |
14,208,130 | !pip install --no-index --find-links=.. /input/preinstall efficientnet<import_modules> | from pycaret.regression import * | Tabular Playground Series - Jan 2021 |
14,208,130 | import numpy as np
import pandas as pd
import os
import glob
import gc
from functools import partial
import json
import rasterio
from rasterio.windows import Window
import yaml
import pprint
import pathlib
from tqdm.notebook import tqdm
import cv2
import tensorflow as tf
import efficientnet as efn
import efficientnet.t... | reg = setup(data=train, target='target', silent=True, session_id=2021 ) | Tabular Playground Series - Jan 2021 |
14,208,130 | mod_paths = ['.. /input/hubmap-ensamble-model1/','.. /input/hubmap-ensamble-model2/']
THRESHOLD = 0.5
BATCH_SIZE = 256
CHECKSUM = False<load_pretrained> | blended = blend_models(best_3, fold=5 ) | Tabular Playground Series - Jan 2021 |
14,208,130 | identity = rasterio.Affine(1, 0, 0, 0, 1, 0)
fold_models = []
for mod_path in mod_paths:
with open(mod_path+'params.yaml')as file:
P = yaml.load(file, Loader=yaml.FullLoader)
pprint.pprint(P)
with open(mod_path + 'metrics.json')as json_file:
M = json.load(json_file)
print('Model run datetime: '+M['datetime'])
prin... | pred_holdout = predict_model(blended ) | Tabular Playground Series - Jan 2021 |
14,208,130 | WINDOW = P['TILE'] if 'TILE' in P.keys() else P['DIM_FROM']
CROP_SIZE = WINDOW//2
INPUT_SIZE = P['INPUT_SIZE']<define_variables> | final_model = finalize_model(blended ) | Tabular Playground Series - Jan 2021 |
14,208,130 | MIN_OVERLAP = WINDOW - CROP_SIZE
BOARD_CUT =(WINDOW - CROP_SIZE)//2<prepare_x_and_y> | predictions = predict_model(final_model, data=test ) | Tabular Playground Series - Jan 2021 |
14,208,130 | def rle_encode_less_memory(img):
pixels = np.concatenate([[False], img.T.flatten() , [False]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(str(x)for x in runs)
def make_grid(shape, window, min_overlap=0, board_cut = 0):
step = window - min_overlap
x, y = shape
start_x =... | submission['target'] = predictions['Label'] | Tabular Playground Series - Jan 2021 |
14,208,130 | AUTO = tf.data.experimental.AUTOTUNE
image_feature = {
'image': tf.io.FixedLenFeature([], tf.string),
'x1': tf.io.FixedLenFeature([], tf.int64),
'y1': tf.io.FixedLenFeature([], tf.int64)
}
def _parse_image(example_proto):
example = tf.io.parse_single_example(example_proto, image_feature)
image = tf.reshape(tf.io.deco... | submission.to_csv('submission_0116_baseline.csv', index=False ) | Tabular Playground Series - Jan 2021 |
14,282,092 | submission = pd.DataFrame.from_dict(subm, orient='index')
submission.to_csv('submission.csv', index=False)
submission.head()<install_modules> | import lightgbm as lgb
import optuna.integration.lightgbm as oplgb
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error
from tqdm.notebook import tqdm
import matplotlib.pyplot as plt
import seaborn as sns | Tabular Playground Series - Jan 2021 |
14,282,092 | sys.path.append(".. /input/zarrkaggleinstall")
sys.path.append(".. /input/segmentation-models-pytorch-install")
!pip install -q --no-deps.. /input/deepflash2-lfs
<categorify> | df_train = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/train.csv")
df_test = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv")
df_sample = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/sample_submission.csv" ) | Tabular Playground Series - Jan 2021 |
14,282,092 | def rle_encode_less_memory(img):
pixels = img.T.flatten()
pixels[0] = 0
pixels[-1] = 0
runs = np.where(pixels[1:] != pixels[:-1])[0] + 2
runs[1::2] -= runs[::2]
return ' '.join(str(x)for x in runs)
def load_model_weights(model, file, strict=True):
state = torch.load(file, map_location='cpu')
stats = state['stats']
mo... | train_id = df_train["id"]
test_id = df_test["id"]
df_train.drop("id", axis=1, inplace=True)
df_test.drop("id", axis=1, inplace=True ) | Tabular Playground Series - Jan 2021 |
14,282,092 | @patch
def read_img(self:BaseDataset, *args, **kwargs):
image = tifffile.imread(args[0])
if len(image.shape)== 5:
image = image.squeeze().transpose(1, 2, 0)
elif image.shape[0] == 3:
image = image.transpose(1, 2, 0)
return image
@patch
def apply(self:DeformationField, data, offset=(0, 0), pad=(0, 0), order=1):
"Appl... | feature_cols = [c for c in df_train.columns if c != "target"] | Tabular Playground Series - Jan 2021 |
14,282,092 | class CONFIG() :
data_path = Path('.. /input/hubmap-kidney-segmentation')
models_path = Path('.. /input/hubmap-efficient-sampling-deepflash2-train')
models_file = np.array([x for x in models_path.iterdir() if x.name.startswith('u')])
scale = 3
tile_shape =(512, 512)
padding =(100,100)
encoder_name = "efficientnet-... | train_x = df_train[feature_cols]
train_y = df_train.target
test_x = df_test | Tabular Playground Series - Jan 2021 |
14,282,092 | print(cfg.models_file)
print(len(cfg.models_file))
df_sample = pd.read_csv(cfg.data_path/'sample_submission.csv', index_col='id')
names,preds = [],[]
sub = None<categorify> | folds = KFold(n_splits=5, shuffle=True, random_state=2021 ) | Tabular Playground Series - Jan 2021 |
14,282,092 | names,preds = [],[]
for idx, _ in df_sample.iterrows() :
print(f'
f = cfg.data_path/'test'/f'{idx}.tiff'
ds = TileDataset([f], scale=cfg.scale, tile_shape=cfg.tile_shape, padding=cfg.padding)
shape = ds.data[f.name].shape
print('Shape:', shape)
names.append(idx)
msk = None
print('Prediction')
for model_path in cfg.... | class FoldsAverageLGBM:
def __init__(self, folds):
self.folds = folds
self.models = []
def fit(self, lgb_params, train_x, train_y):
oof_preds = np.zeros_like(train_y)
self.train_x = train_x.values
self.train_y = train_y.values
for tr_idx, va_idx in tqdm(folds.split(train_x)) :
tr_x, va_x = self.train_x[tr_idx], self.t... | Tabular Playground Series - Jan 2021 |
14,282,092 | df = pd.DataFrame({'id':names,'predicted':preds} ).set_index('id')
df_sample.loc[df.index.values] = df.values
df_sample.to_csv('submission.csv' )<set_options> | best_lgb_params = {
'seed': 2021,
'objective': 'regression',
'metric': 'rmse',
'verbosity': -1,
'feature_pre_filter': False,
'lambda_l1': 6.540486456085813,
'lambda_l2': 0.01548480538099245,
'num_leaves': 256,
'feature_fraction': 0.52,
'bagging_fraction': 0.6161835249194311,
'bagging_freq': 7,
'min_child_samples': 20
}... | Tabular Playground Series - Jan 2021 |
14,282,092 | warnings.filterwarnings("ignore" )<define_variables> | folds_average_lgbm = FoldsAverageLGBM(folds ) | Tabular Playground Series - Jan 2021 |
14,282,092 | Threshold = 35<categorify> | folds_average_lgbm.fit(best_lgb_params, train_x, train_y ) | Tabular Playground Series - Jan 2021 |
14,282,092 | def rle_encode_less_memory(img):
pixels = img.T.flatten()
pixels[0] = 0
pixels[-1] = 0
runs = np.where(pixels[1:] != pixels[:-1])[0] + 2
runs[1::2] -= runs[::2]
return ' '.join(str(x)for x in runs )<load_from_csv> | np.sqrt(mean_squared_error(df_train.target, folds_average_lgbm.oof_preds)) | Tabular Playground Series - Jan 2021 |
14,282,092 | df_sample = pd.read_csv('.. /input/hubmap-kidney-segmentation/sample_submission.csv' )<define_variables> | y_pred = folds_average_lgbm.predict(test_x ) | Tabular Playground Series - Jan 2021 |
14,282,092 | names,preds = [],[]<categorify> | sub = df_sample.copy()
sub["target"] = y_pred
sub.to_csv("submission_lgbm_1.csv", index=False)
sub.head() | Tabular Playground Series - Jan 2021 |
14,207,193 | for idx,row in tqdm(df_sample.iterrows() ,total=len(df_sample)) :
idx = row['id']
pred1 = np.load(f"./pred_{idx}_reduce2.npz")['arr_0'].astype(np.uint8)
pred2 = np.load(f"./pred_{idx}_reduce4.npz")['arr_0'].astype(np.uint8)
mask =(pred1 + pred2)> 2 * Threshold
rle = rle_encode_less_memory(mask)
names.append(idx)
pr... | train = pd.read_csv(input_path / 'train.csv', index_col='id')
display(train.head() ) | Tabular Playground Series - Jan 2021 |
14,207,193 | df = pd.DataFrame({'id':names,'predicted':preds})
df.to_csv('submission.csv',index=False )<set_options> | test = pd.read_csv(input_path / 'test.csv', index_col='id')
display(test.head() ) | Tabular Playground Series - Jan 2021 |
14,207,193 | warnings.filterwarnings("ignore" )<load_from_csv> | submission = pd.read_csv(input_path / 'sample_submission.csv', index_col='id')
display(submission.head() ) | Tabular Playground Series - Jan 2021 |
14,207,193 | sz = 4096
reduce = 2
TH = 0.39
DATA = '.. /input/hubmap-kidney-segmentation/test/'
MODELS = [f'.. /input/pytorch-reduce2-1024-resnet101-elu/model_{i}.pth' for i in range(10)]
df_sample = pd.read_csv('.. /input/hubmap-kidney-segmentation/sample_submission.csv')
bs = 1
device = torch.device('cuda' if torch.cuda.is_avail... | !pip install pytorch-tabnet
| Tabular Playground Series - Jan 2021 |
14,207,193 | def enc2mask(encs, shape):
img = np.zeros(shape[0]*shape[1], dtype=np.uint8)
for m,enc in enumerate(encs):
if isinstance(enc,np.float)and np.isnan(enc): continue
s = enc.split()
for i in range(len(s)//2):
start = int(s[2*i])- 1
length = int(s[2*i+1])
img[start:start+length] = 1 + m
return img.reshape(shape ).T
def ma... | features = train.columns[1:-1]
X = train[features]
y = np.log1p(train["target"])
X_test = test[features]
| Tabular Playground Series - Jan 2021 |
14,207,193 | s_th = 40
p_th = 1000*(sz//256)**2
identity = rasterio.Affine(1, 0, 0, 0, 1, 0)
def img2tensor(img,dtype:np.dtype=np.float32):
if img.ndim==2 : img = np.expand_dims(img,2)
img = np.transpose(img,(2,0,1))
return torch.from_numpy(img.astype(dtype, copy=False))
class HuBMAPDataset(Dataset):
def __init__(self, idx, sz=sz... | X = X.to_numpy()
y = y.to_numpy().reshape(-1, 1)
X_test = X_test.to_numpy() | Tabular Playground Series - Jan 2021 |
14,207,193 | class Model_pred:
def __init__(self, models, dl, tta:bool=True, half:bool=False):
self.models = models
self.dl = dl
self.tta = tta
self.half = half
def __iter__(self):
count=0
with torch.no_grad() :
for x,y in iter(self.dl):
if(( y>=0 ).sum() > 0):
x = x[y>=0].to(device)
y = y[y>=0]
if self.half: x = x.half()
py = Non... | kf = KFold(n_splits=5, random_state=42, shuffle=True)
predictions_array =[]
CV_score_array =[]
for train_index, test_index in kf.split(X):
X_train, X_valid = X[train_index], X[test_index]
y_train, y_valid = y[train_index], y[test_index]
regressor = TabNetRegressor(verbose=1,seed=42)
regressor.fit(X_train=X_train, y_t... | Tabular Playground Series - Jan 2021 |
14,207,193 | class FPN(nn.Module):
def __init__(self, input_channels:list, output_channels:list):
super().__init__()
self.convs = nn.ModuleList(
[nn.Sequential(nn.Conv2d(in_ch, out_ch*2, kernel_size=3, padding=1),
nn.ELU(inplace=True), nn.BatchNorm2d(out_ch*2),
nn.Conv2d(out_ch*2, out_ch, kernel_size=3, padding=1))
for in_ch, out_... | print("The CV score is %.5f" % np.mean(CV_score_array,axis=0))
| Tabular Playground Series - Jan 2021 |
14,207,193 | class UneXt50(nn.Module):
def __init__(self, stride=1, **kwargs):
super().__init__()
m = ResNet(Bottleneck, [3, 4, 23, 3], groups=32, width_per_group=4)
self.enc0 = nn.Sequential(m.conv1, m.bn1, nn.ELU(inplace=True))
self.enc1 = nn.Sequential(nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1),
m.layer1)
sel... | submission.iloc[:,0:] = predictions
submission.to_csv('submission.csv' ) | Tabular Playground Series - Jan 2021 |
14,139,468 | models = []
for path in MODELS:
state_dict = torch.load(path,map_location=torch.device('cpu'))
model = UneXt50()
model.load_state_dict(state_dict)
model.float()
model.eval()
model.to(device)
models.append(model)
del state_dict<categorify> | from catboost import CatBoostRegressor | Tabular Playground Series - Jan 2021 |
14,139,468 | names,preds = [],[]
for idx,row in tqdm(df_sample.iterrows() ,total=len(df_sample)) :
idx = row['id']
ds = HuBMAPDataset(idx)
dl = DataLoader(ds,bs,num_workers=0,shuffle=False,pin_memory=True)
mp = Model_pred(models,dl)
mask = torch.zeros(len(ds),ds.sz,ds.sz,dtype=torch.int8)
for p,i in iter(mp): mask[i.item() ] = ... | df_train = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/train.csv')
y = df_train['target']
df_train.drop(['id', 'target'], axis = 1, inplace = True)
df_test = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/test.csv')
sub_id = df_test['id']
df_test.drop('id', axis = 1, inplace = True ) | Tabular Playground Series - Jan 2021 |
14,139,468 | df = pd.DataFrame({'id':names,'predicted':preds})
df.to_csv('submission.csv',index=False )<install_modules> | cbr = CatBoostRegressor()
cbr.fit(df_train, y ) | Tabular Playground Series - Jan 2021 |
14,139,468 | !pip install.. /input/segmentationmodelspytorch-013/pretrainedmodels-0.7.4-py3-none-any.whl
!pip install.. /input/segmentationmodelspytorch-013/efficientnet_pytorch-0.6.3-py2.py3-none-any.whl
!pip install.. /input/segmentationmodelspytorch-013/timm-0.3.2-py3-none-any.whl
!pip install.. /input/segmentationmodelspytorch-... | submission = pd.DataFrame(sub_id, columns = ['id'])
submission.head() | Tabular Playground Series - Jan 2021 |
14,139,468 | sample_submission = pd.read_csv('.. /input/hubmap-kidney-segmentation/sample_submission.csv')
sample_submission = sample_submission.set_index('id')
seed = 1015
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def rle_en... | submission['target'] = cbr.predict(df_test ) | Tabular Playground Series - Jan 2021 |
14,139,468 | PATH = ".. /input/hubmap-models2"
model_list = ['1_unet-se_resnet50_0.9526_epoch_28.pth', '2_unet-se_resnet50_0.9494_epoch_28.pth', '1_unet-timm-effb0_0.9495_epoch_39.pth', '2_unet-timm-effb0_0.9477_epoch_35.pth', '1_unet-timm-resnest26d_0.9522_epoch_28.pth', '1_unet-se_resnet50_pesudo_0.9572_epoch_26.pth', '1_unet-tim... | submission.to_csv('catboost.csv', index = False ) | Tabular Playground Series - Jan 2021 |
14,220,134 | model_path = list(map(lambda x: os.path.join(PATH, x), model_list))<train_model> | mpl.rcParams['agg.path.chunksize'] = 10000 | Tabular Playground Series - Jan 2021 |
14,220,134 | models = []
for path in model_path:
model = torch.load(path, map_location= 'cuda')
model.float()
model.eval()
model.to('cuda')
models.append(model)
del model<define_variables> | train_data = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/train.csv')
test_data = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/test.csv')
print("successfully loaded!" ) | Tabular Playground Series - Jan 2021 |
14,220,134 | sz = 512
test_path = '.. /input/hubmap-kidney-segmentation/test/'
for step, person_idx in enumerate(test_files):
print(f'load {step+1}/{len(test_files)} data...')
img = tiff.imread(test_path + person_idx + '.tiff' ).squeeze()
if img.shape[0] == 3:
img = img.transpose(1,2,0)
predict_mask_l1 = np.zeros(( img.shape[0], ... | outlier = train_data.loc[train_data.target < 1.0]
print(outlier ) | Tabular Playground Series - Jan 2021 |
14,220,134 | sample_sub = pd.read_csv('.. /input/hubmap-kidney-segmentation/sample_submission.csv', index_col='id')
submission = pd.read_csv('.. /input/my-csv-outputs/d488c759a_single_mask.csv', index_col='id' )<save_to_csv> | train_data.drop([170514], inplace = True ) | Tabular Playground Series - Jan 2021 |
14,220,134 | pub_ids = submission.index.values
predictions = submission.values
sample_sub.loc[pub_ids] = predictions
sample_sub.to_csv('submission.csv')
<load_pretrained> | y_train = train_data["target"]
train_data.drop(columns = ["target"], inplace = True ) | Tabular Playground Series - Jan 2021 |
14,220,134 | df = pd.read_pickle('.. /input/preprocessingdata/df.pkl' )<prepare_x_and_y> | params = { 'n_estimators' : [1500, 2000, 2500],
'learning_rate' : [0.01, 0.02]
}
xgb = XGBRegressor(
objective = 'reg:squarederror',
subsample = 0.8,
colsample_bytree = 0.8,
learning_rate = 0.01,
tree_method = 'gpu_hist')
grid_search = GridSearchCV(xgb,
param_grid = params,
scoring = 'neg_root_mean_squared_error',
n_... | Tabular Playground Series - Jan 2021 |
14,220,134 | X_train = df[df.date_block_num < 33].drop(['item_cnt_month'], axis=1)
Y_train = df[df.date_block_num < 33]['item_cnt_month']
X_valid = df[df.date_block_num == 33].drop(['item_cnt_month'], axis=1)
Y_valid = df[df.date_block_num == 33]['item_cnt_month']
X_test = df[df.date_block_num == 34].drop(['item_cnt_month'], axis... | clf = XGBRegressor(
objective = 'reg:squarederror',
subsample = 0.8,
learning_rate = 0.02,
max_depth = 7,
n_estimators = 2500,
tree_method = 'gpu_hist')
clf.fit(train_data, y_train)
y_pred_xgb = clf.predict(test_data)
print(y_pred_xgb ) | Tabular Playground Series - Jan 2021 |
14,220,134 | feature_name = X_train.columns.tolist()
feature_name_indexes = [
'country_part',
'item_category_common',
'item_category_code',
'city_code',
]
def objective(trial):
lgb_train = lgb.Dataset(X_train[feature_name], Y_train)
lgb_eval = lgb.Dataset(X_valid[feature_name], Y_valid, reference=lgb_train)
params = {
'objective'... | solution = pd.DataFrame({"id":test_data.id, "target":y_pred_xgb})
solution.to_csv("solution.csv", index = False)
print("saved successful!" ) | Tabular Playground Series - Jan 2021 |
14,055,870 | study = optuna.create_study(direction='minimize')
study.optimize(objective, n_trials=50)
print('Number of finished trials:', len(study.trials))
print('Best trial:', study.best_trial.params )<init_hyperparams> | train = pd.read_csv(input_path / 'train.csv', index_col='id')
test = pd.read_csv(input_path / 'test.csv', index_col='id')
submission = pd.read_csv(input_path / 'sample_submission.csv', index_col='id' ) | Tabular Playground Series - Jan 2021 |
14,055,870 | params = {
'objective': 'rmse',
'metric': 'rmse',
'num_leaves': 1012,
'min_data_in_leaf':10,
'feature_fraction':0.622351664881,
'learning_rate': 0.01,
'num_rounds': 1000,
'early_stopping_rounds': 30,
'seed': 1
}
feature_name_indexes = [
'country_part',
'item_category_common',
'item_category_code',
'city_code',
]
lgb_tr... | target = train.pop('target')
X_train, X_test, y_train, y_test = train_test_split(train, target, train_size=0.8 ) | Tabular Playground Series - Jan 2021 |
14,055,870 | test = pd.read_csv('.. /input/competitive-data-science-predict-future-sales/test.csv')
Y_test = gbm.predict(X_test[feature_name] ).clip(0, 20)
submission = pd.DataFrame({
"ID": test.index,
"item_cnt_month": Y_test
})
submission.to_csv('gbm_submission.csv', index=False )<load_from_csv> | parameters = {
'n_estimators': 350,
'tree_method': 'hist',
'learning_rate': 0.03,
'colsample_bytree': 0.9,
'subsample': 0.9,
'min_child_weight': 9,
'max_depth': 11,
'n_jobs': -1
} | Tabular Playground Series - Jan 2021 |
14,055,870 | categories = pd.read_csv(".. /input/eng-translations/categories_eng.csv")
items = pd.read_csv(".. /input/eng-translations/items_eng.csv")
sales = pd.read_csv(".. /input/competitive-data-science-predict-future-sales/sales_train.csv")
test = pd.read_csv(".. /input/competitive-data-science-predict-future-sales/test.csv... | parameters2 = {
'n_estimators': 350,
'tree_method': 'exact',
'learning_rate': 0.03,
'colsample_bytree': 0.9,
'subsample': 0.9,
'min_child_weight': 9,
'max_depth': 11,
'n_jobs': -1
} | Tabular Playground Series - Jan 2021 |
14,055,870 | def downcast1(df, verbose=True):
start_mem = df.memory_usage().sum() / 1024**2
for col in df.columns:
dtype_name = df[col].dtype.name
if dtype_name == 'object':
pass
elif dtype_name == 'bool':
df[col] = df[col].astype('int8')
elif dtype_name.startswith('int')or(df[col].round() == df[col] ).all() :
df[col] = pd.to_nu... | Tabular Playground Series - Jan 2021 | |
14,055,870 | def cleans(i):
pattern = r'[A-Za-z0-9]+'
finds = re.findall(pattern, str(i))
stringy = ""
for j in finds:
stringy += f" {j}"
return stringy<feature_engineering> | Tabular Playground Series - Jan 2021 | |
14,055,870 | shops["clean"] = shops["shop_name"].apply(cleans)
shops.head()<feature_engineering> | final_model = XGBRegressor(tree_method='hist', min_child_weight=9, max_depth=11, n_jobs=-1, colsample_bytree=0.5, learning_rate=0.01, n_estimators=1500)
final_model.fit(X_train, y_train, early_stopping_rounds=10, eval_set=[(X_test, y_test)], verbose=False)
prediction = final_model.predict(X_test)
mse = mean_squared_... | Tabular Playground Series - Jan 2021 |
14,055,870 | sales.loc[sales["shop_id"]==0, "shop_id"] = 57
sales.loc[sales["shop_id"]==1, "shop_id"] = 58
sales.loc[sales["shop_id"]==10, "shop_id"] = 11
sales.loc[sales["shop_id"]==39, "shop_id"] = 40
test.loc[test['shop_id'] == 0, 'shop_id'] = 57
test.loc[test['shop_id'] == 1, 'shop_id'] = 58
test.loc[test['shop_id'] == 10, 'sho... | submission['target'] = final_model.predict(test)
submission.to_csv('xgb_reg.csv' ) | Tabular Playground Series - Jan 2021 |
14,162,481 | unique_test_shops = test["shop_id"].unique()
sales = sales[sales["shop_id"].isin(unique_test_shops)]
print(f"Number of Unique Shops in Test Data:{len(unique_test_shops)}
Number of Unique Shops in Sales Data:{len(sales['shop_id'].unique())}" )<drop_column> | import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib_venn import venn2
import shap
from optuna.integration import _lightgbm_tuner as lgb_tuner
import optuna
from catboost import CatBoost
from catboost import Pool
from catboost import cv
import category_encoders as ce
from tqdm import tqdm
import lightg... | Tabular Playground Series - Jan 2021 |
14,162,481 | shops.drop("shop_name", axis=1, inplace=True )<feature_engineering> | df_train = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/train.csv")
df_test = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv")
submission = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/sample_submission.csv" ) | Tabular Playground Series - Jan 2021 |
14,162,481 | shops["city"] = shops["clean"].apply(lambda x: x.split() [0] )<categorify> | y = df_train["target"]
X = df_train.drop(["target","id"], axis=1 ) | Tabular Playground Series - Jan 2021 |
14,162,481 | le = LabelEncoder()
shops["city"] = le.fit_transform(shops["city"])
shops.drop("clean", axis=1, inplace=True)
<feature_engineering> | fold_num = 10
EARLY_STOPPING_ROUNDS = 10
VERBOSE_EVAL = 10000
LGB_ROUND_NUM = 10000
objective = 'regression'
metric = 'rmse'
params = {
'task': 'train',
'boosting_type': 'gbdt',
'objective': objective,
'metric': metric,
'verbosity': -1,
"seed": 42,
}
@contextmanager
def timer(logger=None, format_str='{:.3f}[s]', prefix... | Tabular Playground Series - Jan 2021 |
14,162,481 | items["item_name"] = items["item_name"].str.lower()
items["item_name_clean"] = items["item_name"].apply(cleans)
items.drop("item_name", axis=1, inplace=True )<categorify> | fold = KFold(n_splits=5, shuffle=True, random_state=71)
cv = list(fold.split(X, y))
oof, models = fit_lgbm(X.values, y, cv, params=params ) | Tabular Playground Series - Jan 2021 |
14,162,481 | items["item_name_five"] = [x[:5] for x in items["item_name_clean"]]
items["item_name_five"] = le.fit_transform(items["item_name_five"])
items.drop("item_name_clean", axis=1, inplace=True )<groupby> | def visualize_importance(models, feat_train_df):
feature_importance_df = pd.DataFrame()
for i, model in enumerate(models):
_df = pd.DataFrame()
_df['feature_importance'] = model.feature_importance()
_df['column'] = feat_train_df.columns
_df['fold'] = i + 1
feature_importance_df = pd.concat([feature_importance_df, _df... | Tabular Playground Series - Jan 2021 |
14,162,481 | items["first_sale_date"] = sales.groupby("item_id" ).agg({"date_block_num":"min"})["date_block_num"]
items<data_type_conversions> | X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8)
def opt(trial):
n_estimators = trial.suggest_int('n_estimators', 0, 1000)
max_depth = trial.suggest_int('max_depth', 1, 20)
learning_rate = trial.suggest_discrete_uniform('learning_rate', 0.01,0.1,0.01)
min_child_weight = trial.suggest_int('m... | Tabular Playground Series - Jan 2021 |
14,162,481 | items[items["first_sale_date"].isna() ]
items["first_sale_date"] = items["first_sale_date"].fillna(34 )<feature_engineering> | def fit_xgb(X, y, cv, params: dict=None, verbose: int=50):
metric_func = mean_squared_error
if params is None:
params = {}
models = []
oof_pred = np.zeros_like(y, dtype=np.float)
for i,(idx_train, idx_valid)in enumerate(cv):
x_train, y_train = X[idx_train], y[idx_train]
x_valid, y_valid = X[idx_valid], y[idx_valid]
mo... | Tabular Playground Series - Jan 2021 |
14,162,481 | categories["category"] = categories["category_name"].apply(lambda x: x.split() [0])
categories<count_values> |
params_xgb = {'n_estimators': 208,
'max_depth': 4,
'learning_rate':0.08,
'min_child_weight': 13,
'subsample': 0.8,
'colsample_bytree': 0.8}
oof_xgb, models_xgb = fit_xgb(X.values, y, cv, params=params_xgb ) | Tabular Playground Series - Jan 2021 |
14,162,481 | categories["category"].value_counts()<feature_engineering> | def opt_cb(trial):
params = {
'iterations' : trial.suggest_int('iterations', 50, 300),
'depth' : trial.suggest_int('depth', 4, 10),
'learning_rate' : trial.suggest_loguniform('learning_rate', 0.01, 0.3),
'random_strength' :trial.suggest_int('random_strength', 0, 100),
'bagging_temperature' :trial.suggest_loguniform('ba... | Tabular Playground Series - Jan 2021 |
14,162,481 | categories.loc[categories["category"] == "Game"] = "Games"<feature_engineering> | def fit_cb(X, y, cv, params: dict=None, verbose: int=50):
metric_func = mean_squared_error
if params is None:
params = {}
models = []
oof_pred = np.zeros_like(y, dtype=np.float)
for i,(idx_train, idx_valid)in enumerate(cv):
x_train, y_train = X[idx_train], y[idx_train]
x_valid, y_valid = X[idx_valid], y[idx_valid]
tra... | Tabular Playground Series - Jan 2021 |
14,162,481 | def make_misc(x):
if len(categories[categories['category']==x])>= 5:
return x
else:
return 'Misc'
categories["cats"] = categories["category"].apply(make_misc)
categories<drop_column> | params_cb = {
'loss_function': 'RMSE',
'max_depth': 3,
'learning_rate': 0.08,
'subsample': 0.8,
'num_boost_round': 1000,
'early_stopping_rounds': 100,
}
oof_cb, models_cb = fit_cb(X.values, y, cv, params=params_cb ) | Tabular Playground Series - Jan 2021 |
14,162,481 | categories.drop(["category", "category_name"], axis=1, inplace=True )<drop_column> | df_test = df_test.drop("id",axis=1 ) | Tabular Playground Series - Jan 2021 |
14,162,481 | categories["cats_le"] = le.fit_transform(categories["cats"])
categories.drop("cats", inplace=True, axis=1 )<feature_engineering> | pred_lgb = np.array([model.predict(df_test.values)for model in models])
pred_lgb = np.mean(pred_lgb, axis=0)
pred_lgb = np.where(pred_lgb < 0, 0, pred_lgb)
pred_xgb = np.array([model.predict(df_test.values)for model in models_xgb])
pred_xgb = np.mean(pred_xgb, axis=0)
pred_xgb = np.where(pred_xgb < 0, 0, pred_xgb)... | Tabular Playground Series - Jan 2021 |
14,162,481 | sales = sales[sales["item_price"] > 0]
sales = sales[sales["item_price"] < 50000]
sales = sales[sales["item_cnt_day"] > 0]
sales = sales[sales["item_cnt_day"] < 1000]
sales["item_price"] = sales["item_price"].apply(lambda x: round(x,2))
sales<merge> | submission["target"] = tmp_sub["pred"].copy() | Tabular Playground Series - Jan 2021 |
14,162,481 | group = sales.groupby(index_feats ).agg({"item_cnt_day": "sum"})
group = group.reset_index()
group = group.rename(columns={"item_cnt_day": "item_cnt_month"})
train = pd.merge(train, group, on=index_feats, how="left")
train<set_options> | submission.to_csv("submission.csv", index=False ) | Tabular Playground Series - Jan 2021 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.