<gh_stars>0
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import pandas as pd
import numpy as np
import os


# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

print(device)

# Hyper parameters
num_epochs = 10
num_classes = 6
batch_size = 10
learning_rate = 0.0001

# Load data

def read_list(path):
	"Reads list stored in txt file"
	list_enzymes = open(path,'r')
	list_enzymes = list_enzymes.read()
	return list(list_enzymes.split(", "))

class MatrixDataset(torch.utils.data.Dataset):
    def __init__(self, list_file, label_file, data_path, transform=None):
        self.data_path = data_path
        self.transform = transform
        self.pdb_list = read_list(list_file)
        self.labels = pd.read_csv(label_file, index_col="pdb_id")
        print(self.labels)

        print(len(self.pdb_list))

    def __getitem__(self, index):
        # TODO
        # 1. Read one data from file (e.g. using numpy.fromfile, PIL.Image.open).
        # 2. Preprocess the data (e.g. torchvision.Transform).
        # 3. Return a data pair (e.g. image and label).

        pdb_id = self.pdb_list[index]

        matrix_path = self.data_path + pdb_id + ".npy"
        matrix = np.load(matrix_path)

        if self.transform:
            matrix = self.transform(matrix)

        try:
            y_label = torch.tensor(int(self.labels.loc[pdb_id.upper(), "EC"][1])-1)
        except:
            y_label = torch.tensor(1)

        return (matrix, y_label)

    def __len__(self):
        return len(self.pdb_list)

matrix_dataset = MatrixDataset(list_file="training.txt",
                                label_file="dataset_all.csv",
                                data_path="C:/Users/Charlie/OneDrive - Imperial College London/Python/DMCNN/files/precomputed/",
                                transform=transforms.ToTensor())

train_set, test_set = torch.utils.data.random_split(matrix_dataset, [16563, 2000])

train_loader = torch.utils.data.DataLoader(dataset=train_set,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_set,
                                           batch_size=batch_size,
                                           shuffle=True)


# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 64, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer3 = nn.Sequential(
            nn.Conv2d(64, 512, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(512),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.fc1 = nn.Linear(73728, 1000)
        self.fc2 = nn.Linear(1000, num_classes)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = self.layer3(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc1(out)
        out = F.relu(out)
        out = self.fc2(out)
        return out

model = ConvNet(num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device).float()
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

# Test the model
model.eval()  # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.to(device).float()
        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 of the model on the 10000 test images: {} %'.format(round(100 * correct / total), 5))

# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')

import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import pandas as pd
import numpy as np
import os


# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

print(device)

# Hyper parameters
num_epochs = 10
num_classes = 6
batch_size = 10
learning_rate = 0.0001

# Load data

def read_list(path):
	"Reads list stored in txt file"
	list_enzymes = open(path,'r')
	list_enzymes = list_enzymes.read()
	return list(list_enzymes.split(", "))

class MatrixDataset(torch.utils.data.Dataset):
    def __init__(self, list_file, label_file, data_path, transform=None):
        self.data_path = data_path
        self.transform = transform
        self.pdb_list = read_list(list_file)
        self.labels = pd.read_csv(label_file, index_col="pdb_id")
        print(self.labels)

        print(len(self.pdb_list))

    def __getitem__(self, index):
        # TODO
        # 1. Read one data from file (e.g. using numpy.fromfile, PIL.Image.open).
        # 2. Preprocess the data (e.g. torchvision.Transform).
        # 3. Return a data pair (e.g. image and label).

        pdb_id = self.pdb_list[index]

        matrix_path = self.data_path + pdb_id + ".npy"
        matrix = np.load(matrix_path)

        if self.transform:
            matrix = self.transform(matrix)

        try:
            y_label = torch.tensor(int(self.labels.loc[pdb_id.upper(), "EC"][1])-1)
        except:
            y_label = torch.tensor(1)

        return (matrix, y_label)

    def __len__(self):
        return len(self.pdb_list)

matrix_dataset = MatrixDataset(list_file="training.txt",
                                label_file="dataset_all.csv",
                                data_path="C:/Users/Charlie/OneDrive - Imperial College London/Python/DMCNN/files/precomputed/",
                                transform=transforms.ToTensor())

train_set, test_set = torch.utils.data.random_split(matrix_dataset, [16563, 2000])

train_loader = torch.utils.data.DataLoader(dataset=train_set,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_set,
                                           batch_size=batch_size,
                                           shuffle=True)


# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        self.layer1 = nn.Sequential(
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 64, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer3 = nn.Sequential(
            nn.Conv2d(64, 512, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(512),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.fc1 = nn.Linear(73728, 1000)
        self.fc2 = nn.Linear(1000, num_classes)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = self.layer3(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc1(out)
        out = F.relu(out)
        out = self.fc2(out)
        return out

model = ConvNet(num_classes).to(device)

# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        images = images.to(device).float()
        labels = labels.to(device)

        # Forward pass
        outputs = model(images)
        loss = criterion(outputs, labels)

        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if (i+1) % 100 == 0:
            print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
                   .format(epoch+1, num_epochs, i+1, total_step, loss.item()))

# Test the model
model.eval()  # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
with torch.no_grad():
    correct = 0
    total = 0
    for images, labels in test_loader:
        images = images.to(device).float()
        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 of the model on the 10000 test images: {} %'.format(round(100 * correct / total), 5))

# Save the model checkpoint
torch.save(model.state_dict(), 'model.ckpt')
# Device configuration # Hyper parameters # Load data # TODO # 1. Read one data from file (e.g. using numpy.fromfile, PIL.Image.open). # 2. Preprocess the data (e.g. torchvision.Transform). # 3. Return a data pair (e.g. image and label). # Convolutional neural network (two convolutional layers) # Loss and optimizer # Train the model # Forward pass # Backward and optimize # Test the model # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance) # Save the model checkpoint