Hello! I have problem with my code:
import numpy as np
import os
import torch
from torch.utils.data import Dataset, DataLoader
import torchvision.models as models
import torchvision as trv
import torch.nn as nn
from sklearn.model_selection import train_test_split
import torch.optim as optim
import argparse
class CustomData(Dataset):
def __init__(self, path, transform=None):
try:
self.path = path
self.data = np.load(path).astype('float32')
self.data = self.data.astype(np.int_)
self.transform = transform
except:
print("error")
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
features = torch.tensor(self.data[idx, 2:])
label = self.data[idx, 1]
if self.transform:
features = self.transform(features)
return features, label
class CNN(nn.Module):
def __init__(self, input_size, num_classes):
super(CNN, self).__init__()
self.conv1 = nn.Conv1d(1, 10, 1)
self.conv2 = nn.Conv2d(1, 20, 45)
self.fc1 = nn.Linear(45 * 20, 50)
self.fc2 = nn.Linear(50, num_classes)
self.bn1 = nn.BatchNorm1d(10)
self.bn2 = nn.BatchNorm1d(20)
self.bn3 = nn.BatchNorm1d(50)
self.activation = nn.Sigmoid()
def forward(self, x):
x = x.unsqueeze(1)
x = x.unsqueeze(1)
x = self.activation(self.bn1(self.conv1(x)))
x = self.activation(self.bn2(self.conv2(x)))
x = x.view(-1, x.shape[1] * x.shape[2])
x = self.activation(self.bn3(self.fc1(x)))
x = self.fc2(x)
return x
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
parser = argparse.ArgumentParser(description='PyTorch Feature Extraction')
parser.add_argument('--path', metavar='DIR',
help='path to dataset')
parser.add_argument('--j', '--workers', default=4, type=int, metavar='N',
help='number of data loading workers (default: 4)')
parser.add_argument('--b', '--batch-size', default=10, type=int,
metavar='N', help='mini-batch size (default: 256)')
args = parser.parse_args()
path = "final_relebeled_dataset.npy"
dataset = CustomData(path, transform=None)
dataloader = DataLoader(dataset, batch_size=args.b, shuffle=True, num_workers=args.j, drop_last=True)
# num_classes = 41
num_classes = 24
input_size = 53
# model = Simple_FC(input_size = input_size, num_classes = num_classes).to(device)
model = CNN(input_size=input_size, num_classes=num_classes).to(device)
lr = 0.01
momentum = 0.9
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=lr, momentum=momentum)
def train(epoch):
model.train()
for (features, labels) in enumerate(dataloader):
features = torch.tensor([features])
labels = labels[0]
print(type(features))
features = features.type(torch.LongTensor)
print(type(features))
features, labels = features.to(device), labels.to(device)
optimizer.zero_grad()
print(features)
output = model(features)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
print(loss)
if __name__ == '__main__':
for epoch in range(0, 10):
train(epoch)
After I have started my code I see error :" RuntimeError: expected scalar type Long but found Float ". Could you help me solve my problem ?? Thank you !!!