text_plain_output_1.png
from time import time

from torch.utils.data import DataLoader

from torchvision.datasets import ImageFolder

from torchvision.transforms import Compose, CenterCrop, ToTensor,ColorJitter

import glob

import os

import shutil

import torch

import torch
use_cuda = torch.cuda.is_available()
if torch.cuda.is_available():
    device = torch.device('cuda')
else:
    device = torch.device('cpu')

import os
import glob
import shutil
train_data_dir = '/kaggle/input/1056lab-covid19-chest-xray-recognit/train'
working_dir = '/kaggle/working'
os.makedirs(working_dir + '/train')
os.makedirs(working_dir + '/train/COVID/')
os.makedirs(working_dir + '/train/Not_COVID/')
path_list = glob.glob(train_data_dir + '/COVID/*.png')
for path in path_list:
    shutil.copy(path, working_dir + '/train/COVID/')
for dir in ['Lung_Opacity', 'Normal', 'Viral_Pneumonia']:
    path_list = glob.glob(train_data_dir + '/' + dir + '/*.png')
    for path in path_list:
        shutil.copy(path, working_dir + '/train/Not_COVID/')

from torchvision.transforms import Compose, CenterCrop, ToTensor, ColorJitter
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader
train_data_dir = '/kaggle/working/train'
transform = Compose([CenterCrop(224), ToTensor()])
transforms = ColorJitter(contrast=1)
train_data = ImageFolder(train_data_dir, transform=transform)
train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
class_names = train_data.classes

from time import time
epoch_num = 10
start = time()
for epoch in range(1, epoch_num + 1):
    model_ft.train()
    sum_loss = 0.0
    count = 0
    optimizer.step()
    scheduler.step()
    for image, label in train_loader:
        if torch.cuda.is_available():
            image = image.cuda()
            label = label.cuda()
        y = model_ft(image)
        _, preds = torch.max(y, 1)
        loss = criterion(y, label)
        model_ft.zero_grad()
        loss.backward()
        optimizer.step()
        sum_loss += loss.item() * image.size(0)
        count += torch.sum(preds == label.data)
    train_loss = sum_loss / len(train_data)
    train_acc = float(count) / len(train_data)
    t = time() - start
    print(f'epoch: {epoch}, mean loss: {train_loss:.4f}, train accuracy: {train_acc:.4f}, elapsed_time :{t:.4f}')