Kaggle competition: Prostate cANcer graDe Assessment (PANDA) Challenge
<SOS> metric: QuadraticWeightedKappa Kaggle data source: prostate-cancer-grade-assessment-(panda)-challenge<statistical_test>
sys.path = [
'.. /input/ttach-kaggle/ttach/',
] + sys.path
@numba.jit(nopython=True)
 def ema_residuals(x, alpha=0.01):

 new_x = np.zeros_like(x)
 ema = x[0]
for i in range(1, len(x)) :
ema = ema*(1-alpha)+ alpha*x[i]
new_x[i] = x[i] - ema
return new_x<compute_test_metric>
def get_tiles(img, tile_size, n_tiles, mode=0):
h, w, c = img.shape
pad_h =(tile_size - h % tile_size)% tile_size +(( tile_size * mode)// 2)
 pad_w =(tile_size - w % tile_size)% tile_size +(( tile_size * mode)// 2)
 img2 = np.pad(
 img,
[[pad_h // 2, pad_h - pad_h // 2], [pad_w // 2, pad_w - pad_w // 2], [0, 0]],
constant_values=255, 
)
 img3 = img2.reshape(
 img2.shape[0] // tile_size, tile_size, img2.shape[1] // tile_size, tile_size, 3 
)
 img3 = img3.transpose(0, 2, 1, 3, 4 ).reshape(-1, tile_size, tile_size, 3)
 n_tiles_with_info =(
 img3.reshape(img3.shape[0], -1 ).sum(1)< tile_size ** 2 * 3 * 255
).sum()
if len(img3)< n_tiles:
img3 = np.pad(
 img3,
[[0, n_tiles - len(img3)], [0, 0], [0, 0], [0, 0]],
constant_values=255, 
)
 idxs = np.argsort(img3.reshape(img3.shape[0], -1 ).sum(-1)) [:n_tiles]
img3 = img3[idxs]
return img3, n_tiles_with_info >= n_tiles
def concat_tiles(tiles, tile_shape):
image = cv2.hconcat([cv2.vconcat(tiles[ts])for ts in tile_shape])
 return image
@numba.jit(nopython=True)
 def ema(x, alpha=0.01):

 new_x = np.zeros_like(x)
 ema = x[0]
for i in range(1, len(x)) :
ema = ema*(1-alpha)+ alpha*x[i]
new_x[i] = ema
return new_x<feature_engineering>
class TestDataset(Dataset):
def __init__(
 self,
df,
image_dir,
num_tile,
img_size,
tile_size_r,
tile_size_k,
tile_mode,
transform, 
):
self.df = df
self.img_ids = self.df.image_id
self.image_dir = image_dir
self.transform = transform
self.num_tiles = num_tile
self.img_size = img_size
self.tile_mode = tile_mode
self.tile_size_k = tile_size_k
self.tile_size_r = tile_size_r
self.is_karolinska =(self.df.data_provider == "karolinska" ).values
self.tiff_level = 1
n = int(self.num_tiles ** 0.5)
 self.tile_shape = np.array(range(self.num_tiles)).reshape(( n, n))
def __len__(self):
return len(self.df)
 def __getitem__(self, idx):
file_name = self.img_ids[idx]
file_path = os.path.join(self.image_dir, f"{file_name}.tiff")
 img_tmp = skimage.io.MultiImage(file_path)[self.tiff_level]
tiles, _ = get_tiles(
 img_tmp,
tile_size=self.tile_size_k,
n_tiles=self.num_tiles,
mode=self.tile_mode, 
)
 tiles = np.array(tiles)
 image = concat_tiles(tiles, tile_shape=self.tile_shape)
 image = image.astype(np.float32)
 image = 255 - image
image /= 255
if self.transform:
augmented = self.transform(image=image)
 image = augmented["image"]
return image
flat_negative_sample = np.zeros_like(negative_sample)
 flat_positive_sample = np.zeros_like(positive_sample)
 for i in range(3):
flat_negative_sample[:,i] = ema_residuals(negative_sample[:,i])
 flat_positive_sample[:,i] = ema_residuals(positive_sample[:,i] )<feature_engineering>
GlobalParams = collections.namedtuple(
 "GlobalParams",
[
"batch_norm_momentum",
"batch_norm_epsilon",
"dropout_rate",
"num_classes",
"width_coefficient",
"depth_coefficient",
"depth_divisor",
"min_depth",
"drop_connect_rate",
"image_size",
], 
)
 BlockArgs = collections.namedtuple(
 "BlockArgs",
[
"kernel_size",
"num_repeat",
"input_filters",
"output_filters",
"expand_ratio",
"id_skip",
"stride",
"se_ratio",
], 
)
 GlobalParams.__new__.__defaults__ =(None,)* len(GlobalParams._fields)
 BlockArgs.__new__.__defaults__ =(None,)* len(BlockArgs._fields)
 class SwishImplementation(torch.autograd.Function):
@staticmethod
def forward(ctx, i):
result = i * torch.sigmoid(i)
 ctx.save_for_backward(i)
 return result
@staticmethod
def backward(ctx, grad_output):
i = ctx.saved_variables[0]
sigmoid_i = torch.sigmoid(i)
 return grad_output *(sigmoid_i *(1 + i *(1 - sigmoid_i)))
 class MemoryEfficientSwish(nn.Module):
def forward(self, x):
return SwishImplementation.apply(x)
 class Swish(nn.Module):
def forward(self, x):
return x * torch.sigmoid(x)
 def round_filters(filters, global_params):

 multiplier = global_params.width_coefficient
if not multiplier:
return filters
divisor = global_params.depth_divisor
min_depth = global_params.min_depth
filters *= multiplier
min_depth = min_depth or divisor
new_filters = max(min_depth, int(filters + divisor / 2)// divisor * divisor)
 if new_filters < 0.9 * filters:
new_filters += divisor
return int(new_filters)
 def round_repeats(repeats, global_params):

 multiplier = global_params.depth_coefficient
if not multiplier:
return repeats
return int(math.ceil(multiplier * repeats))
def drop_connect(inputs, p, training):

 if not training:
return inputs
batch_size = inputs.shape[0]
keep_prob = 1 - p
random_tensor = keep_prob
random_tensor += torch.rand(
 [batch_size, 1, 1, 1], dtype=inputs.dtype, device=inputs.device 
)
 binary_tensor = torch.floor(random_tensor)
 output = inputs / keep_prob * binary_tensor
return output
def get_same_padding_conv2d(image_size=None):

 if image_size is None:
return Conv2dDynamicSamePadding
else:
return partial(Conv2dStaticSamePadding, image_size=image_size)
 class Conv2dDynamicSamePadding(nn.Conv2d):

 def __init__(
 self,
in_channels,
out_channels,
kernel_size,
stride=1,
dilation=1,
groups=1,
bias=True, 
):
super().__init__(
 in_channels, out_channels, kernel_size, stride, 0, dilation, groups, bias 
)
 self.stride = self.stride if len(self.stride)== 2 else [self.stride[0]] * 2
def forward(self, x):
ih, iw = x.size() [-2:]
kh, kw = self.weight.size() [-2:]
sh, sw = self.stride
oh, ow = math.ceil(ih / sh), math.ceil(iw / sw)
 pad_h = max(( oh - 1)* self.stride[0] +(kh - 1)* self.dilation[0] + 1 - ih, 0)
 pad_w = max(( ow - 1)* self.stride[1] +(kw - 1)* self.dilation[1] + 1 - iw, 0)
 if pad_h > 0 or pad_w > 0:
x = F.pad(
 x, [pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2] 
)
 return F.conv2d(
 x,
self.weight,
self.bias,
self.stride,
self.padding,
self.dilation,
self.groups, 
)
 class Conv2dStaticSamePadding(nn.Conv2d):

 def __init__(
 self, in_channels, out_channels, kernel_size, image_size=None, **kwargs 
):
super().__init__(in_channels, out_channels, kernel_size, **kwargs)
 self.stride = self.stride if len(self.stride)== 2 else [self.stride[0]] * 2
assert image_size is not None
ih, iw = image_size if type(image_size)== list else [image_size, image_size]
kh, kw = self.weight.size() [-2:]
sh, sw = self.stride
oh, ow = math.ceil(ih / sh), math.ceil(iw / sw)
 pad_h = max(( oh - 1)* self.stride[0] +(kh - 1)* self.dilation[0] + 1 - ih, 0)
 pad_w = max(( ow - 1)* self.stride[1] +(kw - 1)* self.dilation[1] + 1 - iw, 0)
 if pad_h > 0 or pad_w > 0:
self.static_padding = nn.ZeroPad2d(
(pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2)
)
 else:
self.static_padding = Identity()
def forward(self, x):
x = self.static_padding(x)
 x = F.conv2d(
 x,
self.weight,
self.bias,
self.stride,
self.padding,
self.dilation,
self.groups, 
)
 return x
class Identity(nn.Module):
def __init__(self,):
super(Identity, self ).__init__()
def forward(self, input):
return input
flat_negative_sample = np.zeros_like(negative_sample)
 flat_positive_sample = np.zeros_like(positive_sample)
 for i in range(3):
flat_negative_sample[:,i] = ema(negative_sample[:,i])
 flat_positive_sample[:,i] = ema(positive_sample[:,i] )<categorify>
def efficientnet_params(model_name):

 params_dict = {
"efficientnet-b0":(1.0, 1.0, 224, 0.2),
"efficientnet-b1":(1.0, 1.1, 240, 0.2),
"efficientnet-b2":(1.1, 1.2, 260, 0.3),
"efficientnet-b3":(1.2, 1.4, 300, 0.3),
"efficientnet-b4":(1.4, 1.8, 380, 0.4),
"efficientnet-b5":(1.6, 2.2, 456, 0.4),
"efficientnet-b6":(1.8, 2.6, 528, 0.5),
"efficientnet-b7":(2.0, 3.1, 600, 0.5),
"efficientnet-b8":(2.2, 3.6, 672, 0.5),
"efficientnet-l2":(4.3, 5.3, 800, 0.5),
}
return params_dict[model_name]
class BlockDecoder(object):

 @staticmethod
def _decode_block_string(block_string):

 assert isinstance(block_string, str)
 ops = block_string.split("_")
 options = {}
for op in ops:
splits = re.split(r"(\d.*)", op)
 if len(splits)>= 2:
key, value = splits[:2]
options[key] = value
assert("s" in options and len(options["s"])== 1)or(
 len(options["s"])== 2 and options["s"][0] == options["s"][1] 
)
 return BlockArgs(
 kernel_size=int(options["k"]),
num_repeat=int(options["r"]),
input_filters=int(options["i"]),
output_filters=int(options["o"]),
expand_ratio=int(options["e"]),
id_skip=("noskip" not in block_string),
se_ratio=float(options["se"])if "se" in options else None,
stride=[int(options["s"][0])], 
)
 @staticmethod
def _encode_block_string(block):

 args = [
"r%d" % block.num_repeat,
"k%d" % block.kernel_size,
"s%d%d" %(block.strides[0], block.strides[1]),
"e%s" % block.expand_ratio,
"i%d" % block.input_filters,
"o%d" % block.output_filters,
]
if 0 < block.se_ratio <= 1:
args.append("se%s" % block.se_ratio)
 if block.id_skip is False:
args.append("noskip")
 return "_".join(args)
 @staticmethod
def decode(string_list):

 assert isinstance(string_list, list)
 blocks_args = []
for block_string in string_list:
blocks_args.append(BlockDecoder._decode_block_string(block_string))
return blocks_args
@staticmethod
def encode(blocks_args):

 block_strings = []
for block in blocks_args:
block_strings.append(BlockDecoder._encode_block_string(block))
return block_strings
def efficientnet(
 width_coefficient=None,
depth_coefficient=None,
dropout_rate=0.2,
drop_connect_rate=0.2,
image_size=None,
num_classes=1000, 
):

 blocks_args = [
"r1_k3_s11_e1_i32_o16_se0.25",
"r2_k3_s22_e6_i16_o24_se0.25",
"r2_k5_s22_e6_i24_o40_se0.25",
"r3_k3_s22_e6_i40_o80_se0.25",
"r3_k5_s11_e6_i80_o112_se0.25",
"r4_k5_s22_e6_i112_o192_se0.25",
"r1_k3_s11_e6_i192_o320_se0.25",
]
blocks_args = BlockDecoder.decode(blocks_args)
 global_params = GlobalParams(
 batch_norm_momentum=0.99,
batch_norm_epsilon=1e-3,
dropout_rate=dropout_rate,
drop_connect_rate=drop_connect_rate,
num_classes=num_classes,
width_coefficient=width_coefficient,
depth_coefficient=depth_coefficient,
depth_divisor=8,
min_depth=None,
image_size=image_size, 
)
 return blocks_args, global_params
def get_model_params(model_name, override_params):

 if model_name.startswith("efficientnet"):
w, d, s, p = efficientnet_params(model_name)
 blocks_args, global_params = efficientnet(
 width_coefficient=w, depth_coefficient=d, dropout_rate=p, image_size=s 
)
 else:
raise NotImplementedError("model name is not pre-defined: %s" % model_name)
 if override_params:
global_params = global_params._replace(**override_params)
 return blocks_args, global_params
url_map = {"no-url"}
url_map_advprop = {"no-url"}
def load_pretrained_weights(model, model_name, load_fc=True, advprop=False):

 url_map_ = url_map_advprop if advprop else url_map
state_dict = model_zoo.load_url(url_map_[model_name])
 if load_fc:
model.load_state_dict(state_dict)
 else:
state_dict.pop("_fc.weight")
 state_dict.pop("_fc.bias")
 res = model.load_state_dict(state_dict, strict=False)
 assert set(res.missing_keys)== set(
 ["_fc.weight", "_fc.bias"] 
), "issue loading pretrained weights"
print("Loaded pretrained weights for {}".format(model_name))
class MBConvBlock(nn.Module):

 def __init__(self, block_args, global_params):
super().__init__()
self._block_args = block_args
self._bn_mom = 1 - global_params.batch_norm_momentum
self._bn_eps = global_params.batch_norm_epsilon
self.has_se =(self._block_args.se_ratio is not None)and(
 0 < self._block_args.se_ratio <= 1 
)
 self.id_skip = block_args.id_skip
Conv2d = get_same_padding_conv2d(image_size=global_params.image_size)
 inp = self._block_args.input_filters
oup =(
 self._block_args.input_filters * self._block_args.expand_ratio 
)
 if self._block_args.expand_ratio != 1:
self._expand_conv = Conv2d(
 in_channels=inp, out_channels=oup, kernel_size=1, bias=False 
)
 self._bn0 = nn.BatchNorm2d(
 num_features=oup, momentum=self._bn_mom, eps=self._bn_eps 
)
 k = self._block_args.kernel_size
s = self._block_args.stride
self._depthwise_conv = Conv2d(
 in_channels=oup,
out_channels=oup,
groups=oup,
kernel_size=k,
stride=s,
bias=False, 
)
 self._bn1 = nn.BatchNorm2d(
 num_features=oup, momentum=self._bn_mom, eps=self._bn_eps 
)
 if self.has_se:
num_squeezed_channels = max(
 1, int(self._block_args.input_filters * self._block_args.se_ratio)
)
 self._se_reduce = Conv2d(
 in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1 
)
 self._se_expand = Conv2d(
 in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1 
)
 final_oup = self._block_args.output_filters
self._project_conv = Conv2d(
 in_channels=oup, out_channels=final_oup, kernel_size=1, bias=False 
)
 self._bn2 = nn.BatchNorm2d(
 num_features=final_oup, momentum=self._bn_mom, eps=self._bn_eps 
)
 self._swish = MemoryEfficientSwish()
def forward(self, inputs, drop_connect_rate=None):

 x = inputs
if self._block_args.expand_ratio != 1:
x = self._swish(self._bn0(self._expand_conv(inputs)))
 x = self._swish(self._bn1(self._depthwise_conv(x)))
 if self.has_se:
x_squeezed = F.adaptive_avg_pool2d(x, 1)
 x_squeezed = self._se_expand(self._swish(self._se_reduce(x_squeezed)))
 x = torch.sigmoid(x_squeezed)* x
x = self._bn2(self._project_conv(x))
input_filters, output_filters =(
 self._block_args.input_filters,
self._block_args.output_filters, 
)
 if(
 self.id_skip
and self._block_args.stride == 1
and input_filters == output_filters 
):
if drop_connect_rate:
x = drop_connect(x, p=drop_connect_rate, training=self.training)
 x = x + inputs
return x
def set_swish(self, memory_efficient=True):

 self._swish = MemoryEfficientSwish() if memory_efficient else Swish()
@numba.jit(nopython=True)
 def drop_missing(intersect,sample):

 i=j=k=0
new_intersect=np.empty_like(intersect)
 while i< intersect.size and j < sample.size:
if intersect[i]==sample[j]:
new_intersect[k]=intersect[i]
k+=1
i+=1
j+=1
elif intersect[i]<sample[j]:
i+=1
else :
j+=1
return new_intersect[:k]
@numba.jit(nopython=True)
 def _local_maxima_1d_window_single_pass(x, w):
midpoints = np.empty(x.shape[0] // 2, dtype=np.intp)
 left_edges = np.empty(x.shape[0] // 2, dtype=np.intp)
 right_edges = np.empty(x.shape[0] // 2, dtype=np.intp)
 m = 0
i = 1
i_max = x.shape[0] - 1
while i < i_max:
if x[i - 1] < x[i]:
i_ahead = i + 1
while i_ahead < i_max and x[i_ahead] == x[i]:
i_ahead += 1
i_right = i_ahead - 1
f = False
i_window_end = i_right + w
while i_ahead < i_max and i_ahead < i_window_end:
if x[i_ahead] > x[i]:
f = True
break
i_ahead += 1
if x[i_ahead] < x[i]:
left_edges[m] = i
right_edges[m] = i_right
midpoints[m] =(left_edges[m] + right_edges[m])// 2
m += 1
i = i_ahead - 1
i += 1
midpoints = midpoints[:m]
left_edges = left_edges[:m]
right_edges = right_edges[:m]
return midpoints, left_edges, right_edges
@numba.jit(nopython=True)
 def local_maxima_1d_window(x, w=1):

 fm, fl, fr = _local_maxima_1d_window_single_pass(x, w)
 bm, bl, br = _local_maxima_1d_window_single_pass(x[::-1], w)
 bm = np.abs(bm - x.shape[0] + 1)[::-1]
bl = np.abs(bl - x.shape[0] + 1)[::-1]
br = np.abs(br - x.shape[0] + 1)[::-1]
m = drop_missing(fm, bm)
 return m<categorify>
class EfficientNet(nn.Module):

 def __init__(self, blocks_args=None, global_params=None):
super().__init__()
assert isinstance(blocks_args, list), "blocks_args should be a list"
assert len(blocks_args)> 0, "block args must be greater than 0"
self._global_params = global_params
self._blocks_args = blocks_args
Conv2d = get_same_padding_conv2d(image_size=global_params.image_size)
 bn_mom = 1 - self._global_params.batch_norm_momentum
bn_eps = self._global_params.batch_norm_epsilon
in_channels = 3
out_channels = round_filters(
 32, self._global_params 
)
 self._conv_stem = Conv2d(
 in_channels, out_channels, kernel_size=3, stride=2, bias=False 
)
 self._bn0 = nn.BatchNorm2d(
 num_features=out_channels, momentum=bn_mom, eps=bn_eps 
)
 self._blocks = nn.ModuleList([])
 for block_args in self._blocks_args:
block_args = block_args._replace(
 input_filters=round_filters(
 block_args.input_filters, self._global_params 
),
output_filters=round_filters(
 block_args.output_filters, self._global_params 
),
num_repeat=round_repeats(block_args.num_repeat, self._global_params), 
)
 self._blocks.append(MBConvBlock(block_args, self._global_params))
if block_args.num_repeat > 1:
block_args = block_args._replace(
 input_filters=block_args.output_filters, stride=1 
)
 for _ in range(block_args.num_repeat - 1):
self._blocks.append(MBConvBlock(block_args, self._global_params))
in_channels = block_args.output_filters
out_channels = round_filters(1280, self._global_params)
 self._conv_head = Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
 self._bn1 = nn.BatchNorm2d(
 num_features=out_channels, momentum=bn_mom, eps=bn_eps 
)
 self._avg_pooling = nn.AdaptiveAvgPool2d(1)
 self._dropout = nn.Dropout(self._global_params.dropout_rate)
 self._fc = nn.Linear(out_channels, self._global_params.num_classes)
 self._swish = MemoryEfficientSwish()
def set_swish(self, memory_efficient=True):

 self._swish = MemoryEfficientSwish() if memory_efficient else Swish()
for block in self._blocks:
block.set_swish(memory_efficient)
 def extract_features(self, inputs):

 x = self._swish(self._bn0(self._conv_stem(inputs)))
 for idx, block in enumerate(self._blocks):
drop_connect_rate = self._global_params.drop_connect_rate
if drop_connect_rate:
drop_connect_rate *= float(idx)/ len(self._blocks)
 x = block(x, drop_connect_rate=drop_connect_rate)
 x = self._swish(self._bn1(self._conv_head(x)))
 return x
def forward(self, inputs):

 bs = inputs.size(0)
 x = self.extract_features(inputs)
 x = self._avg_pooling(x)
 x = x.view(bs, -1)
 x = self._dropout(x)
 x = self._fc(x)
 return x
@classmethod
def from_name(cls, model_name, override_params=None):
cls._check_model_name_is_valid(model_name)
 blocks_args, global_params = get_model_params(model_name, override_params)
 return cls(blocks_args, global_params)
 @classmethod
def from_pretrained(
 cls, model_name, advprop=False, num_classes=1000, in_channels=3 
):
model = cls.from_name(model_name, override_params={"num_classes": num_classes})
 load_pretrained_weights(
 model, model_name, load_fc=(num_classes == 1000), advprop=advprop 
)
 if in_channels != 3:
Conv2d = get_same_padding_conv2d(image_size=model._global_params.image_size)
 out_channels = round_filters(32, model._global_params)
 model._conv_stem = Conv2d(
 in_channels, out_channels, kernel_size=3, stride=2, bias=False 
)
 return model
@classmethod
def get_image_size(cls, model_name):
cls._check_model_name_is_valid(model_name)
 _, _, res, _ = efficientnet_params(model_name)
 return res
@classmethod
def _check_model_name_is_valid(cls, model_name):

 valid_models = ["efficientnet-b" + str(i)for i in range(9)]
if model_name not in valid_models:
raise ValueError("model_name should be one of: " + ", ".join(valid_models))
class CustomEfficientNet(nn.Module):
def __init__(
 self,
base="efficientnet-b0",
pool_type="gem",
in_ch=3,
out_ch=1,
pretrained=False, 
):
super(CustomEfficientNet, self ).__init__()
assert base in {
"efficientnet-b0",
"efficientnet-b1",
"efficientnet-b2",
"efficientnet-b3",
"efficientnet-b4",
}
assert pool_type in {"concat", "avg", "gem"}
self.base = base
self.in_ch = in_ch
self.out_ch = out_ch
self.pretrained = pretrained
if pretrained:
self.net = EfficientNet.from_pretrained(base)
 else:
self.net = EfficientNet.from_name(base)
 out_shape = self.net._fc.in_features
if pool_type == "concat":
self.net._avg_pooling = AdaptiveConcatPool2d()
out_shape = out_shape * 2
elif pool_type == "gem":
self.net._avg_pooling = GeM()
out_shape = out_shape
self.net._fc = nn.Sequential(
 Flatten() , SEBlock(out_shape), nn.Dropout() , nn.Linear(out_shape, out_ch)
)
 def forward(self, x):
x = self.net(x)
 return x
class AdaptiveConcatPool2d(nn.Module):
def __init__(self, sz=None):
super().__init__()
sz = sz or(1, 1)
 self.ap = nn.AdaptiveAvgPool2d(sz)
 self.mp = nn.AdaptiveMaxPool2d(sz)
 def forward(self, x):
return torch.cat([self.mp(x), self.ap(x)], 1)
 class SEBlock(nn.Module):
def __init__(self, in_ch, r=8):
super(SEBlock, self ).__init__()
self.linear_1 = nn.Linear(in_ch, in_ch // r)
 self.linear_2 = nn.Linear(in_ch // r, in_ch)
 def forward(self, x):
input_x = x
x = F.relu(self.linear_1(x), inplace=True)
 x = self.linear_2(x)
 x = torch.sigmoid(x)
 x = input_x * x
return x
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
 def gem(x, p=3, eps=1e-6):
return F.avg_pool2d(x.clamp(min=eps ).pow(p),(x.size(-2), x.size(-1)) ).pow(1.0 / p)
 class GeM(nn.Module):
def __init__(self, p=3, eps=1e-6):
super(GeM, self ).__init__()
self.p = Parameter(torch.ones(1)* p)
 self.eps = eps
def forward(self, x):
return gem(x, p=self.p, eps=self.eps)
 def __repr__(self):
return(
 self.__class__.__name__
+ f"(p={self.p.data.tolist() [0]:.4f}, eps={str(self.eps)})" 
)
 def inference(
 dataloader, model, device, out_ch, tta=False, fp16=False, dataloader2=None, 
):
probs = []
def extract_preds(logits_tmp):
if out_ch == 1:
preds_tmp = logits_tmp
elif out_ch == 5:
preds_tmp = logits_tmp.sigmoid().sum(1)
 elif out_ch > 5:
preds_tmp = logits_tmp[:, :5].sigmoid()
preds_tmp = preds_tmp.sum(1)
 return preds_tmp.detach()
for i, images in tqdm(enumerate(dataloader), total=len(dataloader)) :
if fp16:
images = images.half()
images = images.to(device)
 with torch.no_grad() :
logits = model(images)
 preds = extract_preds(logits)
 if tta:
logits_hflip = model(images.flip(3))
preds_hflip = extract_preds(logits_hflip)
 preds =(preds + preds_hflip)/ 2.0
probs.append(preds.to("cpu" ).numpy())
 probs = np.concatenate(probs)
 if dataloader2 is not None:
probs2 = inference(
 dataloader2, model, device, out_ch, tta, fp16=fp16, dataloader2=None 
)
 return(probs + probs2)/ 2.0, probs
return probs
def quadratic_weighted_kappa(y_hat, y):
return cohen_kappa_score(y_hat, y, weights="quadratic")
 class MyOptimizedRounder:
def __init__(self):
self.coef = None
self.initial_coef = np.array([0.5, 1.5, 2.5, 3.5, 4.5])
 def judge_each_thres(self, thres, x):
tmp = thres.reshape(( 1, -1)) <= x.reshape(( -1, 1))
result = tmp.sum(axis=1)
 return result
def _kappa_loss(self, coef, x, y):
x_p = self.judge_each_thres(coef, np.copy(x))
ll = quadratic_weighted_kappa(y, x_p)
 return -ll
def fit(self, x, y):
loss_partial = partial(self._kappa_loss, x=x, y=y)
 self.coef = sp.optimize.minimize(
 loss_partial, self.initial_coef, method="nelder-mead" 
)
 def predict(self, x, coef=None):
if coef is None:
coef = self.coef["x"]
return self.judge_each_thres(coef, np.copy(x))
def predict_default_thres(self, x):
coef = self.initial_coef.copy()
return self.judge_each_thres(coef, np.copy(x))
def coefficients(self):
return self.coef["x"]
def print_eval_local(df, preds):
ground_truth = df.isup_grade.values
score = quadratic_weighted_kappa(ground_truth, preds)
 print(f"Local CV kappa score(all): {score}")
 indx_val_karolinska = df.data_provider == "karolinska"
indx_val_radboud = df.data_provider == "radboud"
indx = indx_val_karolinska
v_acc_k =(preds[indx] == ground_truth[indx] ).mean() * 100.0
v_kappa_k = quadratic_weighted_kappa(ground_truth[indx], preds[indx])
 print(f"Local CV kappa score(karolinska): {v_kappa_k}")
 print(f"Local CV accuracy(karolinska): {v_acc_k}")
 indx = indx_val_radboud
v_acc_r =(preds[indx] == ground_truth[indx] ).mean() * 100.0
v_kappa_r = quadratic_weighted_kappa(ground_truth[indx], preds[indx])
 print(f"Local CV kappa score(radboud): {v_kappa_r}")
 print(f"Local CV accuracy(radboud): {v_acc_r}")
def get_peaks(
 x,
window=25,
visualise=False,
visualise_color=None, 
):

 x_flatten = ema_residuals(x)
 x_flatten_abs = np.abs(x_flatten)
 peaks_indices = local_maxima_1d_window(x_flatten_abs, window)
 heights = x_flatten_abs[peaks_indices]
peaks_sorted_indices = np.argsort(heights)[::-1]
peaks_indices = peaks_indices[peaks_sorted_indices]
heights = heights[peaks_sorted_indices]
ky = heights
kx = np.arange(1, heights.shape[0]+1)
 conv_length = 9
grad = np.diff(ky, 1)/np.diff(kx, 1)
 grad = np.convolve(grad, np.ones(conv_length)/conv_length)
 grad = grad[conv_length-1:-conv_length+1]
knee_x = plateau_detection(grad, -0.01, plateau_length=1000)
 knee_x -= conv_length//2
if visualise:
plt.plot(grad, color=visualise_color)
 plt.axvline(knee_x, ls="--", color=visualise_color)
 peaks_x = peaks_indices[:knee_x]
peaks_y = heights[:knee_x]
ii = np.argsort(peaks_x)
 peaks_x = peaks_x[ii]
peaks_y = peaks_y[ii]
return peaks_x, peaks_y
@numba.jit(nopython=True)
 def plateau_detection(grad, threshold, plateau_length=5):

 count = 0
loc = 0
for i in range(grad.shape[0]):
if grad[i] > threshold:
count += 1
if count == plateau_length:
loc = i - plateau_length
break
return loc<normalization>
class Config:
def __init__(self, on_kernel=True, kfold=1, debug=False):
self.on_kernel = on_kernel
self.num_tile = 64
self.tile_size_k = 192
self.tile_size_r = 192
self.img_size = 1536
self.fp16 = False
self.batch_size = 4
if self.fp16:
self.batch_size = int(self.batch_size * 2)
 self.tta = False
self.ada_bn = False
self.in_ch = 3
self.out_ch = 10
self.base = "efficientnet-b1"
self.pseudo_use_threshold = 0.2
self.pseudo_soft_label = False
self.weight_name = "final_2_efficientnet-b1_kfold_{}_latest.pt"
self.weight_name = self.weight_name.format(kfold)
 if on_kernel:
self.data_dir = ".. /input/prostate-cancer-grade-assessment"
test_image_folder = os.path.join(self.data_dir, "test_images")
 train_image_folder = os.path.join(self.data_dir, "train_images")
 is_test = os.path.exists(test_image_folder)
 self.image_folder = test_image_folder if is_test else train_image_folder
df_train = pd.read_csv(os.path.join(self.data_dir, "train.csv"))
sample = pd.read_csv(os.path.join(self.data_dir, "test.csv"))
self.df = sample if is_test else df_train.loc[:16]
else:
self.data_dir = ".. /input"
self.image_folder = ".. /input/train_images"
df = pd.read_csv(".. /input/train-5kfold.csv")
 self.kfold = 1
self.df = df[df["kfold"] == self.kfold].reset_index(drop=True)
 if debug:
self.df = self.df[:16].reset_index(drop=True)
 def get_weight_path(self):
if self.on_kernel:
return os.path.join(".. /input/030-weight", self.weight_name)
 else:
dir_name = self.weight_name.split("_")[0]
return os.path.join(".. /output/model", dir_name, self.weight_name)
 def get_args_ds(self):
return {
"df": self.df,
"image_dir": self.image_folder,
"num_tile": self.num_tile,
"img_size": self.img_size,
"tile_size_k": self.tile_size_k,
"tile_size_r": self.tile_size_r,
"transform": Compose([ToTensorV2() ]),
}
def get_args_dl(self):
return {"batch_size": self.batch_size, "shuffle": False, "num_workers": 4}
def get_model(cfg_model):
net = None
if "seresnext" in cfg_model.base:
net = CustomSEResNeXt(
 in_ch=cfg_model.in_ch,
out_ch=cfg_model.out_ch,
pool_type="gem",
pretrained=False, 
)
 elif "efficientnet" in cfg_model.base:
net = CustomEfficientNet(
 base=cfg_model.base,
in_ch=cfg_model.in_ch,
out_ch=cfg_model.out_ch,
pretrained=False, 
)
 assert net is not None
return net
def inference_from_cfg(cfg, model=None):
print("Make frame and path")
 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 test_dataset = TestDataset(tile_mode=0, **cfg.get_args_ds())
 test_loader = DataLoader(test_dataset, **cfg.get_args_dl())
 test_dataset2 = TestDataset(tile_mode=2, **cfg.get_args_ds())
 test_loader2 = DataLoader(test_dataset2, **cfg.get_args_dl())
 print("Make data loader")
 if model is not None:
print(f"Use existed Model: {cfg.base}")
 else:
print(f"Get Model: {cfg.base}")
 model = get_model(cfg)
 w_path = cfg.get_weight_path()
print(f"Load weight...: {w_path}")
 state_dict = torch.load(w_path)["state_dict"]
state_dict = {k[4:]: v for k, v in state_dict.items() }
model.load_state_dict(state_dict)
 if cfg.ada_bn:
for m in model.modules() :
if isinstance(m, _BatchNorm):
m.track_running_stats = False
if cfg.fp16:
model = model.half()
model.eval()
model = model.to(device)
 transforms = tta.Compose(
 [tta.HorizontalFlip() , tta.VerticalFlip() , tta.Rotate90(angles=[0, 90, 180])] 
)
 model = tta.ClassificationTTAWrapper(model, transforms)
 print("Inference start")
 probs, probs_without_tta = inference(
 test_loader,
model,
device,
out_ch=cfg.out_ch,
tta=cfg.tta,
fp16=cfg.fp16,
dataloader2=test_loader2, 
)
 return probs, probs_without_tta
def inference_mean_cfgs(cfgs):
probs_all = None
probs_without_tta_all = None
for c in cfgs:
probs, probs_without_tta = inference_from_cfg(c)
 if probs_all is None:
probs_all = probs
probs_without_tta_all = probs_without_tta
else:
probs_all = probs_all + probs
probs_without_tta_all = probs_without_tta_all + probs_without_tta
probs = probs_all / float(len(cfgs))
probs_without_tta = probs_without_tta_all / float(len(cfgs))
return probs, probs_without_tta
def main(on_kernel=False, debug=False):
cfgs = [Config(on_kernel=on_kernel, kfold=k, debug=debug)for k in [1, 4, 5]]
probs_raw, probs_without_tta_raw = inference_mean_cfgs(cfgs)
 print("Round predicts")
 rounder = MyOptimizedRounder()
preds = rounder.predict_default_thres(probs_raw)
 preds_without_tta = rounder.predict_default_thres(probs_without_tta_raw)
 if on_kernel:
df = cfgs[0].df[["image_id"]].copy()
df["probs_raw"] = probs_raw
df["isup_grade"] = preds
df["isup_grade"] = df["isup_grade"].astype(int)
 return df
else:
print(f"
*** Normal preds results ***")
 print_eval_local(cfgs[0].df, preds_without_tta)
 print(f"
*** Mode TTA preds results ***")
 print_eval_local(cfgs[0].df, preds)
 df = cfgs[0].df
df["probs_raw"] = probs_raw
df["probs_without_tta_raw"] = probs_without_tta_raw
df["preds"] = preds
df["preds_without_tta"] = preds_without_tta
df.to_csv(f"local_preds_{cfgs[0].weight_name.split('.')[0]}.csv", index=False)
@numba.jit(nopython=True, parallel=True)
 def calculate_current_phase(data):

 n = 800000
assert data.shape[0] == n
omegas = np.exp(-2j * np.pi * np.arange(n)/ n)
 res = np.zeros(data.shape[1], dtype=omegas.dtype)
 for i in numba.prange(data.shape[1]):
res[i] = omegas.dot(data[:, i].astype(omegas.dtype))
return np.angle(res, deg=False)
 def to_angle(x, phase):
dt = 1/800000
return(np.degrees(2*np.pi*dt*x + phase)+ 90)% 360<categorify>
sys.path = [
'.. /input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master',
] + sys.path
def process_measurement(data_df, meta_df):

 peaks = []
for i, sig_id in enumerate(meta_df.signal_id):
mat = []
signal = data_df.iloc[:, i].values.astype(np.float)
 px, h = get_peaks(signal)
 mat.append(px)
 mat.append(h)
 mat.append([sig_id]*len(px))
peaks.append(np.asarray(mat))
peaks = pd.DataFrame(
 np.concatenate(peaks, axis=1 ).T,
columns=['px', 'height', 'signal_id'] 
)
 phase_50hz = calculate_current_phase(data_df.values)
 phase_50hz = pd.DataFrame(
 phase_50hz,
columns=['phase_50hz'] 
)
 phase_50hz['signal_id'] = meta_df['signal_id'].values
peaks = pd.merge(peaks, phase_50hz, on='signal_id', how='left')
 peaks['phase_aligned_x'] = to_angle(peaks['px'], peaks['phase_50hz'])
 peaks['Q'] = pd.cut(peaks['phase_aligned_x'], [0, 90, 180, 270, 360], labels=[0, 1, 2, 3])
 return peaks<merge>
sys.path = [
'.. /input/ttach-kaggle/ttach/',
] + sys.path
train_peaks = process_measurement(train_df, meta_train_df)
 train_peaks = pd.merge(train_peaks, meta_train_df[['signal_id', 'id_measurement', 'target']], on='signal_id', how='left')
 del train_df
gc.collect()<merge>
import skimage.io
import numpy as np
import pandas as pd
import torchvision
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from efficientnet_pytorch import model as enet
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook as tqdm
def calculate_features(peaks_df, meta_df):
results = pd.DataFrame(index=meta_df['id_measurement'].unique())
 results.index.rename('id_measurement', inplace=True)
 res = peaks_df.groupby('id_measurement' ).agg({
'px': 'count',
})
 res.columns = ["peak_count_total"]
results = pd.merge(results, res, on='id_measurement', how='left')
 p = peaks_df[peaks_df['Q'].isin([0, 2])].copy()
res = p.groupby('id_measurement' ).agg({
'px': 'count',
})
 res.columns = ["peak_count_Q02"]
results = pd.merge(results, res, on='id_measurement', how='left')
 p = peaks_df[peaks_df['Q'].isin([1, 3])].copy()
res = p.groupby('id_measurement' ).agg({
'px': 'count',
})
 res.columns = ['peak_count_Q13']
results = pd.merge(results, res, on='id_measurement', how='left')
 p = peaks_df[peaks_df['Q'].isin([0, 2])].copy()
res = p.groupby('id_measurement' ).agg({
'height': ['mean', 'std'],
})
 res.columns = ["_".join(f)+ '_Q02' for f in res.columns]
results = pd.merge(results, res, on='id_measurement', how='left')
 return results<feature_engineering>
data_dir = '.. /input/prostate-cancer-grade-assessment'
df_train = pd.read_csv(os.path.join(data_dir, 'train.csv'))
df_test = pd.read_csv(os.path.join(data_dir, 'test.csv'))
df_sub = pd.read_csv(os.path.join(data_dir, 'sample_submission.csv'))
model_dir = '.. /input/panda-public-models'
image_folder = os.path.join(data_dir, 'test_images')
 is_test = os.path.exists(image_folder)
 image_folder = image_folder if is_test else os.path.join(data_dir, 'train_images')
 df = df_test if is_test else df_train.loc[:16]
tile_size = 256
image_size = 256
n_tiles = 36
batch_size = 4
num_workers = 4
device = torch.device('cuda')
 print(image_folder )
X_train = calculate_features(train_peaks, meta_train_df )<data_type_conversions>
class enetv3(nn.Module):
def __init__(self, modelname, out_dim=5, freeze_bn=True):
super(enetv3, self ).__init__()
if "resnet" in modelname or "resnext" in modelname:
basemodel = resnet.__dict__[modelname](
 pretrained=True)
 if modelname == "rx50":
basemodel = torch.hub.load('facebookresearch/semi-supervised-ImageNet1K-models', 'resnext50_32x4d_ssl')
 if "eff" in modelname:
self.basemodel = EfficientNet.from_name(modelname)
 self.myfc = nn.Linear(self.basemodel._fc.in_features, out_dim)
 self.basemodel._fc = nn.Identity()
self.basemodel._avg_pooling = nn.AdaptiveAvgPool2d(1)
 else:
fcs = basemodel.fc.state_dict() ["weight"].shape[1]
self.basemodel = nn.Sequential(*list(basemodel.children())[:-2])
 if poolmethod=="maxpool":
self.pool = nn.AdaptiveMaxPool2d(1)
 else:
self.pool = nn.AdaptiveAvgPool2d(1)
 self.myfc = nn.Linear(fcs, out_dim)
 def extract(self, x):
return self.basemodel(x)
 def forward(self, x):
x = self.basemodel(x)
 if not "eff" in modelname:
x = self.pool(x ).squeeze(2 ).squeeze(2)
 x = self.myfc(x)
 else:
x = self.myfc(x)
 return x
def load_models(model_files):
models = []
for model_f in model_files:
model_f = os.path.join(".. /input/latesubspanda", model_f)
 if "res" in model_f:
model = enetv2(out_dim=5)
 elif "eff" in model_f:
model = enetv3(modelname, out_dim=5)
 model.load_state_dict(torch.load(model_f))
model.eval()
model.to(device)
 models.append(model)
 print(f'{model_f} loaded!')
 return models
modelname="efficientnet-b0"
model_files = [
'efficientnet-b0famlabelsmodelsub_avgpool_tile36_imsize256_mixup_final_epoch20_fold0.pth',
]
model_files2 = [
'efficientnet-b0famlabelsmodelsub_avgpool_tile36_imsize256_mixup_final_epoch20_fold0.pth',
"efficientnet-b0famlabelsmodelsub_avgpool_tile36_imsize256_mixup_final_epoch20_fold1.pth",
"efficientnet-b0famlabelsmodelsub_avgpool_tile36_imsize256_mixup_final_epoch20_fold2.pth",
"efficientnet-b0famlabelsmodelsub_avgpool_tile36_imsize256_mixup_final_epoch20_fold3.pth",
"efficientnet-b0famlabelsmodelsub_avgpool_tile36_imsize256_mixup_final_epoch20_fold4.pth"
]
models2 = load_models(model_files2)
 models = load_models(model_files )
y_train = meta_train_df.groupby('id_measurement')['target'].sum() > 0
y_train = y_train.astype(np.float )<define_search_space>
def get_tiles(img, mode=0):
result = []
h, w, c = img.shape
pad_h =(tile_size - h % tile_size)% tile_size +(( tile_size * mode)// 2)
 pad_w =(tile_size - w % tile_size)% tile_size +(( tile_size * mode)// 2)
 img2 = np.pad(img,[[pad_h // 2, pad_h - pad_h // 2], [pad_w // 2,pad_w - pad_w//2], [0,0]], constant_values=255)
 img3 = img2.reshape(
 img2.shape[0] // tile_size,
tile_size,
img2.shape[1] // tile_size,
tile_size,
3 
)
 img3 = img3.transpose(0,2,1,3,4 ).reshape(-1, tile_size, tile_size,3)
 n_tiles_with_info =(img3.reshape(img3.shape[0],-1 ).sum(1)< tile_size ** 2 * 3 * 255 ).sum()
if len(img)< n_tiles:
img3 = np.pad(img3,[[0,N-len(img3)],[0,0],[0,0],[0,0]], constant_values=255)
 idxs = np.argsort(img3.reshape(img3.shape[0],-1 ).sum(-1)) [:n_tiles]
img3 = img3[idxs]
for i in range(len(img3)) :
result.append({'img':img3[i], 'idx':i})
 return result, n_tiles_with_info >= n_tiles
class PANDADataset(Dataset):
def __init__(self,
df,
image_size,
n_tiles=n_tiles,
tile_mode=0,
rand=False,
sub_imgs=False 
):
self.df = df.reset_index(drop=True)
 self.image_size = image_size
self.n_tiles = n_tiles
self.tile_mode = tile_mode
self.rand = rand
self.sub_imgs = sub_imgs
def __len__(self):
return self.df.shape[0]
def __getitem__(self, index):
row = self.df.iloc[index]
img_id = row.image_id
tiff_file = os.path.join(image_folder, f'{img_id}.tiff')
 image = skimage.io.MultiImage(tiff_file)[1][:,:,::-1]
tiles, OK = get_tiles(image, self.tile_mode)
 if self.rand:
idxes = np.random.choice(list(range(self.n_tiles)) , self.n_tiles, replace=False)
 else:
idxes = list(range(self.n_tiles))
idxes = np.asarray(idxes)+ self.n_tiles if self.sub_imgs else idxes
n_row_tiles = int(np.sqrt(self.n_tiles))
images = np.zeros(( image_size * n_row_tiles, image_size * n_row_tiles, 3))
for h in range(n_row_tiles):
for w in range(n_row_tiles):
i = h * n_row_tiles + w
if len(tiles)> idxes[i]:
this_img = tiles[idxes[i]]['img']
else:
this_img = np.ones(( self.image_size, self.image_size, 3)).astype(np.uint8)* 255
this_img = 255 - this_img
h1 = h * image_size
w1 = w * image_size
images[h1:h1+image_size, w1:w1+image_size] = this_img
images = images.astype(np.float32)
 images /= 255
images = images.transpose(2, 0, 1)
 return torch.tensor(images )
num_folds = 5
np.random.seed(13)
 splits = np.zeros(X_train.shape[0], dtype=np.int)
 m = y_train == 1
splits[m] = np.random.randint(0, num_folds, size=m.sum())
 m = y_train == 0
splits[m] = np.random.randint(0, num_folds, size=m.sum() )<count_values>
dataset = PANDADataset(df, image_size, n_tiles, 0)
 loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False)
 dataset2 = PANDADataset(df, image_size, n_tiles, 2)
 loader2 = DataLoader(dataset2, batch_size=batch_size, num_workers=num_workers, shuffle=False )
pd.Series(splits ).value_counts()<init_hyperparams>
if len(dataset)> 50:
transforms = tta.Compose(
 [
tta.HorizontalFlip() ,
tta.VerticalFlip() ,
tta.Rotate90(angles=[0, 90, 180]),
] 
)
 else:
transforms = tta.Compose(
 [
] 
)
 tta_models = []
tta_models2 = []
for model in models:
tta_models.append(tta.ClassificationTTAWrapper(model, transforms))
for model in models2:
tta_models2.append(tta.ClassificationTTAWrapper(model, transforms))
params = {
'objective': 'binary',
'metric': 'binary_logloss',
'boosting': 'gbdt',
'learning_rate': 0.01,
'num_leaves': 80,
'num_boost_round': 10000,
'feature_fraction': 0.8,
'bagging_fraction': 0.8,
'num_threads': 4,
'seed': 23974,
}<define_variables>
LOGITS = []
LOGITS2 = []
LOGITS12 = []
LOGITS22 = []
with torch.no_grad() :
for data in tqdm(loader):
data = data.to(device)
 for tta_model in tta_models:
logits = tta_model(data)
 LOGITS.append(logits)
 for i, tta_model in enumerate(tta_models2):
if i == 0:
logits = tta_model(data ).sigmoid()
else:
logits = logits + tta_model(data ).sigmoid()
LOGITS2.append(logits/5)
 for data in tqdm(loader2):
data = data.to(device)
 for tta_model in tta_models:
logits = tta_model(data)
 LOGITS12.append(logits)
 for i, tta_model in enumerate(tta_models2):
if i == 0:
logits = tta_model(data ).sigmoid()
else:
logits = logits + tta_model(data ).sigmoid()
LOGITS22.append(logits/5)
 LOGITS =(torch.cat(LOGITS ).sigmoid().cpu() + torch.cat(LOGITS2 ).cpu()
+torch.cat(LOGITS12 ).sigmoid().cpu() + torch.cat(LOGITS22 ).cpu())/ 4
models = []
cv_scores = []
val_cv_scores = []
feature_names = X_train.columns.tolist()
yp_train = np.zeros(X_train.shape[0])
 yp_val = np.zeros(X_train.shape[0])
 yp_test = np.zeros(X_train.shape[0])
 for fold in range(num_folds):
val_fold = fold
test_fold =(fold + 1)% num_folds
train_folds = [f for f in range(num_folds)if f not in [val_fold, test_fold]]
train_indices = np.where(np.isin(splits, train_folds)) [0]
val_indices = np.where(splits == val_fold)[0]
test_indices = np.where(splits == test_fold)[0]
trn = lgb.Dataset(
 X_train.values[train_indices],
y_train[train_indices],
feature_name=feature_names, 
)
 val = lgb.Dataset(
 X_train.values[val_indices],
y_train[val_indices],
feature_name=feature_names, 
)
 test = lgb.Dataset(
 X_train.values[test_indices],
y_train[test_indices],
feature_name=feature_names, 
)
 model = lgb.train(
 params,
trn,
valid_sets=(trn, test, val),
valid_names=("train", "test", "validation"),
early_stopping_rounds=10,
verbose_eval=50 
)
 yp = model.predict(X_train.values[train_indices])
 yp_train[train_indices] += yp
yp_val_fold = model.predict(X_train.values[val_indices])
 yp_val[val_indices] += yp_val_fold
yp_test_fold = model.predict(X_train.values[test_indices])
 yp_test[test_indices] += yp_test_fold
models.append(model)
 cv_scores.append(model.best_score['test']['binary_logloss'])
 val_cv_scores.append(model.best_score['validation']['binary_logloss'])
 yp_train /=(num_folds - 2)
 cv_scores = np.asarray(cv_scores)
 val_cv_scores = np.asarray(val_cv_scores )<compute_test_metric>
PREDS = LOGITS.sum(1 ).numpy()
df['isup_grade'] = PREDS
df
print("CV Val Logloss: {:.4f} +/- {:.4f}({:.4f})".format(val_cv_scores.mean() , val_cv_scores.std() /np.sqrt(val_cv_scores.shape[0]), val_cv_scores.std()))
print("CV Test Logloss: {:.4f} +/- {:.4f}({:.4f})".format(cv_scores.mean() , cv_scores.std() /np.sqrt(cv_scores.shape[0]), cv_scores.std()))
print("Train accuracy: {:.4f}".format(metrics.accuracy_score(y_train, yp_train > 0.5)))
 print("CV Val accuracy: {:.4f}".format(metrics.accuracy_score(y_train, yp_val > 0.5)))
 print("CV Test accuracy: {:.4f}".format(metrics.accuracy_score(y_train, yp_test > 0.5)) )<compute_train_metric>
df_tmp.rename({'probs_raw': 'part_1_pred'}, axis=1, inplace=True )
thresholds = np.linspace (.01,.9, 90)
 scores_train = []
scores_val = []
scores_test = []
for t in thresholds:
s_train = metrics.f1_score(
 y_train.values.astype(np.float),
yp_train > t 
)
 s_val = metrics.f1_score(
 y_train.values.astype(np.float),
yp_val > t 
)
 s_test = metrics.f1_score(
 y_train.values.astype(np.float),
yp_test > t 
)
 scores_train.append(s_train)
 scores_val.append(s_val)
 scores_test.append(s_test)
 plt.plot(thresholds, scores_train)
 plt.plot(thresholds, scores_val)
 plt.plot(thresholds, scores_test)
 plt.axvline(thresholds[np.argmax(scores_val)], ls='--')
 plt.xlabel('Threshold')
 plt.ylabel('F1 Score')
 plt.show()
print(round(np.max(scores_val), 4), thresholds[np.argmax(scores_val)])
 best_thresh = thresholds[np.argmax(scores_val)]<define_variables>
df = df.merge(df_tmp[['image_id', 'part_1_pred']], on = 'image_id', how = 'left' )
best_thresh = 0.4<define_variables>
p_w = 0.5
df['isup_grade'] = df['isup_grade'] * p_w + df['part_1_pred'] *(1-p_w )
pred_problem = yp_test > best_thresh
pred_neg = yp_test <= best_thresh
true_problem = y_train > 0.5
true_neg = y_train <= 0.5<set_options>
df['isup_grade'] = df['isup_grade'].apply(lambda x: int(np.round(x)) )
<statistical_test><EOS> 
df[['image_id', 'isup_grade']].to_csv('submission.csv', index=False)
 print(df.head())
 print()
print(df.isup_grade.value_counts() )