text_plain_output_1.png
from sklearn.model_selection import train_test_split

from torch.utils.data import Dataset, DataLoader

import matplotlib.image as Image

import os

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import torch

import torch.nn as nn

import torchvision.transforms as transforms

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as Image
import os
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms

data_dir = '../input'
train_dir = data_dir + '/train/train'
test_dir = data_dir + '/test/test'

labels = pd.read_csv(data_dir + '/train.csv')

train, valid = train_test_split(labels, stratify=labels.has_cactus, test_size=0.2)

num_epochs = 25
num_classes = 2
batch_size = 128
learning_rate = 0.0001
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
device

class cactData(Dataset):
    def __init__(self, split_data, data_root='./', transform=None):
        super().__init__()
        self.df = split_data.values
        self.data_root = data_root
        self.transform = transform
    def __len__(self):
        return len(self.df)
    def __getitem__(self, index):
        img_name, label = self.df[index]
        img_path = os.path.join(self.data_root, img_name)
        image = Image.imread(img_path)
        if self.transform is not None:
            image = self.transform(image)
        return (image, label)

mean = [0.5, 0.5, 0.5]
std = [0.5, 0.5, 0.5]
train_transf = transforms.Compose([transforms.ToPILImage(), transforms.ToTensor()])
valid_transf = transforms.Compose([transforms.ToPILImage(), transforms.ToTensor()])

train_data = cactData(train, train_dir, train_transf)
valid_data = cactData(valid, train_dir, valid_transf)
train_loader = DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True, num_workers=0)
valid_loader = DataLoader(dataset=valid_data, batch_size=batch_size // 2, shuffle=False, num_workers=0)

class CactCNN(nn.Module):
    def __init__(self):
        super(CactCNN, self).__init__()
        self.conv1 = nn.Sequential(nn.Conv2d(3, 32, 4, 2, 0), nn.BatchNorm2d(32), nn.ReLU())
        self.conv2 = nn.Sequential(nn.Conv2d(32, 64, 3, 2, 0), nn.BatchNorm2d(64), nn.ReLU())
        self.conv3 = nn.Sequential(nn.Conv2d(64, 128, 3, 2, 0), nn.BatchNorm2d(128), nn.ReLU())
        self.conv4 = nn.Sequential(nn.Conv2d(128, 256, 3, 2, 0), nn.BatchNorm2d(256), nn.ReLU())
        self.fc = nn.Sequential(nn.Linear(256 * 1 * 1, 1024), nn.ReLU(), nn.Dropout(p=0.2), nn.Linear(1024, 2))
    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = self.conv3(x)
        x = self.conv4(x)
        x = x.view(x.shape[0], -1)
        x = self.fc(x)
        return x

model = CactCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device)
        labels = labels.to(device)
        out = model(images)
        loss = criterion(out, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

model.eval()
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in valid_loader:
        images = images.to(device)
        labels = labels.to(device)
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()
    print('Test Accuracy: {} %'.format(100 * correct / total))