Kaggle competition: Digit Recognizer
batch_size = 64
epochs = 30<train_model>
train = pd.read_csv(r".. /input/digit-recognizer/train.csv",dtype = np.float32)
 train_label = train.label.values
train_image = train.loc[:,train.columns != "label"].values/255
train_image, valid_image, train_label, valid_label = train_test_split(train_image,
train_label,
test_size = 0.2,
random_state = 7)
 train_image = torch.from_numpy(train_image)
 train_label = torch.from_numpy(train_label ).type(torch.LongTensor)
 valid_image = torch.from_numpy(valid_image)
 valid_label = torch.from_numpy(valid_label ).type(torch.LongTensor)
 batch_size = 100
n_iters = 15000
num_epochs = n_iters /(len(train_image)/ batch_size)
 num_epochs = int(num_epochs)
 print('num_epochs',num_epochs)
 train = torch.utils.data.TensorDataset(train_image,train_label)
 valid = torch.utils.data.TensorDataset(valid_image,valid_label)
 train_loader = DataLoader(train, batch_size = batch_size, shuffle = False)
 valid_loader = DataLoader(valid, batch_size = batch_size, shuffle = False)
train_datagen = ImageDataGenerator(
 rotation_range=10,
zoom_range = 0.1,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range = 0.1,
horizontal_flip=False,
vertical_flip=False 
)
 train_datagen.fit(x_train )<train_model>

 class res18model(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.backbone = torchvision.models.resnet18(pretrained=True)
 self.backbone.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3,
bias=False)
 in_features = self.backbone.fc.in_features
self.logit = nn.Linear(in_features, num_classes)
 def forward(self, x):
batch_size, C, H, W = x.shape
x = self.backbone.conv1(x)
 x = self.backbone.bn1(x)
 x = self.backbone.relu(x)
 x = self.backbone.maxpool(x)
 x = self.backbone.layer1(x)
 x = self.backbone.layer2(x)
 x = self.backbone.layer3(x)
 x = self.backbone.layer4(x)
 x = F.adaptive_avg_pool2d(x,1 ).reshape(batch_size,-1)
 x = F.dropout(x, 0.25, self.training)
 x = self.logit(x)
 return x
history = model.fit(
 train_datagen.flow(x_train,y_train,batch_size = batch_size),
validation_data =(x_test,y_test),
batch_size = batch_size,
steps_per_epoch = x_train.shape[0]//batch_size,
epochs = epochs,
verbose = 1,
callbacks=[learning_rate_reduction]
)<compute_test_metric>
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 print(device)
model.evaluate(x_test,y_test )<predict_on_test>
model = res18model(num_classes=10)
 model.to(device)
 criterion = nn.CrossEntropyLoss()
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters() , lr=learning_rate, momentum=0.9 )
test_pred = model.predict(data)
 test_pred = np.argmax(test_pred,axis=1)
 print(test_pred.shape )<load_from_csv>
count = 0
for epoch in range(num_epochs):
for i,(images, labels)in enumerate(train_loader):
train = images.view(100,1,28,28)
 train = train.to(device)
 labels = labels.to(device)
 optimizer.zero_grad()
outputs = model(train)
 loss = criterion(outputs, labels)
 loss.backward()
optimizer.step()
count += 1
if count % 500 == 0:
correct = 0
total = 0
for images, labels in valid_loader:
test = images.view(100,1,28,28)
 test = test.to(device)
 labels = labels.to(device)
 outputs = model(test)
 predicted = torch.max(outputs.data, 1)[1]
total += len(labels)
 correct +=(predicted == labels ).sum()
accuracy = 100 * correct / float(total)
 print('Iteration: {} Loss: {} Accuracy: {} %'.format(count, loss.data, accuracy))
sample_submission = pd.read_csv("/kaggle/input/digit-recognizer/sample_submission.csv")
 sample_submission<prepare_output>
test = pd.read_csv(r".. /input/digit-recognizer/test.csv",dtype = np.float32)
 test_image = test.loc[:,:].values/255
test_image = torch.from_numpy(test_image)
 test_loader = DataLoader(test_image, batch_size = batch_size, shuffle = False)
index = sample_submission.ImageId
data = {'ImageId' : index,'Label': test_pred}
df = pd.DataFrame(data)
 df.head<save_to_csv>
submission_df = pd.DataFrame(submission)
 submission_df.columns = submission_df.iloc[0]
submission_df = submission_df.drop(0, axis=0)
 submission_df.to_csv("submission.csv", index=False )