Kaggle competition: Digit Recognizer
<SOS> metric: categorizationaccuracy Kaggle data source: digit-recognizer<choose_model_class>
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout
import matplotlib.pyplot as plt
import keras
from keras.utils.np_utils import to_categorical
class MultiHeadResNet200D(nn.Module):
def __init__(
 self, out_dims_head: tp.List[int]=[3, 4, 3, 1], pretrained=False 
):

 self.base_name = "resnet200d_320"
self.n_heads = len(out_dims_head)
 super(MultiHeadResNet200D, self ).__init__()
base_model = timm.create_model(
 self.base_name, num_classes=sum(out_dims_head), pretrained=False)
 in_features = base_model.num_features
if pretrained:
pretrained_model_path = '.. /input/startingpointschestx/resnet200d_320_chestx.pth'
state_dict = dict()
for k, v in torch.load(pretrained_model_path, map_location='cpu')["model"].items() :
if k[:6] == "model.":
k = k.replace("model.", "")
 state_dict[k] = v
base_model.load_state_dict(state_dict)
 base_model.reset_classifier(0, '')
 self.backbone = base_model
for i, out_dim in enumerate(out_dims_head):
layer_name = f"head_{i}"
layer = nn.Sequential(
 SpatialAttentionBlock(in_features, [64, 32, 16, 1]),
nn.AdaptiveAvgPool2d(output_size=1),
nn.Flatten(start_dim=1),
nn.Linear(in_features, in_features),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(in_features, out_dim))
setattr(self, layer_name, layer)
 def forward(self, x):

 h = self.backbone(x)
 hs = [
getattr(self, f"head_{i}" )(h)for i in range(self.n_heads)]
y = torch.cat(hs, axis=1)
 return y
m = MultiHeadResNet200D([3, 4, 3, 1], False)
 m = m.eval()
x = torch.rand(1, 3, 256, 256)
 with torch.no_grad() :
y = m(x)
 print("[forward test]")
 print("input:\t{}
output:\t{}".format(x.shape, y.shape))
del m; del x; del y
gc.collect()<categorify>
train = pd.read_csv('.. /input/digit-recognizer/train.csv')
 test = pd.read_csv('.. /input/digit-recognizer/test.csv')
 test1 = test.copy()
class LabeledImageDataset(data.Dataset):

 def __init__(
 self,
file_list: tp.List[
tp.Tuple[tp.Union[str, Path], tp.Union[int, float, np.ndarray]]],
transform_list: tp.List[tp.Dict], 
):

 self.file_list = file_list
self.transform = ImageTransformForCls(transform_list)
 def __len__(self):

 return len(self.file_list)
 def __getitem__(self, index):

 img_path, label = self.file_list[index]
img = self._read_image_as_array(img_path)
 img, label = self.transform(( img, label))
return img, label
def _read_image_as_array(self, path: str):

 img_arr = cv2.imread(str(path))
img_arr = cv2.cvtColor(img_arr, cv2.COLOR_BGR2RGB)
 return img_arr<create_dataframe>
x_train=train.drop(['label'],1)
 y_train=train['label']
x_train=x_train.values.reshape(-1,28,28,1)
 test=test.values.reshape(-1,28,28,1)
 x_train=x_train/255
test=test/255
def get_dataloaders_for_inference(
 file_list: tp.List[tp.List], batch_size=64, 
):

 dataset = LabeledImageDataset(
 file_list,
transform_list=[
["Normalize", {
"always_apply": True, "max_pixel_value": 255.0,
"mean": ["0.4887381077884414"], "std": ["0.23064819430546407"]}],
["ToTensorV2", {"always_apply": True}],
])
 loader = data.DataLoader(
 dataset,
batch_size=batch_size, shuffle=False,
num_workers=2, pin_memory=True,
drop_last=False)
 return loader<categorify>
model=models.Sequential([
Conv2D(32,(5,5), activation='relu' , input_shape=(28,28,1)) ,
MaxPooling2D(pool_size=(2,2)) ,
Conv2D(64,(5,5), activation ='relu'),
MaxPooling2D(pool_size=(2,2)) ,
Dropout(0.25),
Conv2D(64,(3,3), activation ='relu'),
MaxPooling2D(pool_size=(2,2)) ,
Dropout(0.25),
Flatten() ,
Dense(64, activation='relu'),
Dense(10, activation='softmax')
 ] )
class ImageTransformBase:

 def __init__(self, data_augmentations: tp.List[tp.Tuple[str, tp.Dict]]):

 augmentations_list = [
self._get_augmentation(aug_name )(**params)
 for aug_name, params in data_augmentations]
self.data_aug = albumentations.Compose(augmentations_list)
 def __call__(self, pair: tp.Tuple[np.ndarray])-> tp.Tuple[np.ndarray]:

 raise NotImplementedError
def _get_augmentation(self, aug_name: str)-> tp.Tuple[ImageOnlyTransform, DualTransform]:

 if hasattr(albumentations, aug_name):
return getattr(albumentations, aug_name)
 else:
return eval(aug_name)
 class ImageTransformForCls(ImageTransformBase):

 def __init__(self, data_augmentations: tp.List[tp.Tuple[str, tp.Dict]]):

 super(ImageTransformForCls, self ).__init__(data_augmentations)
 def __call__(self, in_arrs: tp.Tuple[np.ndarray])-> tp.Tuple[np.ndarray]:

 img, label = in_arrs
augmented = self.data_aug(image=img)
 img = augmented["image"]
return img, label<load_pretrained>
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
 model.fit(x_train, y_train, epochs=60, batch_size=64 )
def load_setting_file(path: str):

 with open(path)as f:
settings = yaml.safe_load(f)
 return settings
def set_random_seed(seed: int = 42, deterministic: bool = False):

 random.seed(seed)
 np.random.seed(seed)
 os.environ["PYTHONHASHSEED"] = str(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = deterministic
def run_inference_loop(stgs, model, loader, device):
model.to(device)
 model.eval()
pred_list = []
with torch.no_grad() :
for x, t in tqdm(loader):
y = model(x.to(device))
pred_list.append(y.sigmoid().detach().cpu().numpy())
 pred_arr = np.concatenate(pred_list)
 del pred_list
return pred_arr<set_options>
y_test = model.predict(test)
 y_test = np.argmax(y_test, axis = 1)
 index_list = []
for i in list(test1.index):
index_list.append(i+1)
 submission_df = pd.DataFrame({
"ImageId": index_list,
"Label": y_test
})
 submission_df.to_csv("submission_cnn.csv", index = False )