Hi all, I have pre-processed my dataset to obtained three sets as train test and validation. The shapes and type of each of them are as follows.
Shape of X_train: (3441, 7, 1, 128, 128)
type(X_train): numpy.ndarray
Shape of X_val: (143, 7, 1, 128, 128)
type(X_val): numpy.ndarray
Shape of X_test: (150, 7, 1, 128, 128)
type(X_test): numpy.ndarray
The class Dataset
is created as given:
import torch
from torch.utils.data import Dataset
class Dataset(Dataset):
def __init__(this, X=None, y=None, mode="train"):
this.mode = mode
this.X = X
if mode == "train":
this.y = y
def __len__(this):
return this.X.shape[0]
def __getitem__(this, idx):
if this.mode == "train":
return torch.FloatTensor(this.X[idx]), torch.LongTensor(this.y[idx])
else:
return torch.FloatTensor(this.X[idx])
Then I have use PytorchDataloader
as
train_set = Dataset(X=X_train, y=Y_train,mode="train")
tr_loader = DL(train_set, batch_size=32, shuffle=True)
test_set = Dataset(X=X_test, y=Y_test,mode="train")
ts_loader = DL(test_set, batch_size=32, shuffle=False)
Everything is working fine uptill now, (I think so :)). Then for training I used the code below.
verbose=True
Losses = []
Accuracies = []
epochs=10
DLS = {"train": tr_loader, "valid": ts_loader}
start_time = time.time()
for e in range(epochs):
epochLoss = {"train": 0, "valid": 0}
epochAccs = {"train": 0, "valid": 0}
for phase in ["train", "valid"]:
if phase == "train":
model.train()
else:
model.eval()
lossPerPass = []
accuracy = []
for X, y in DLS[phase]:
X, y = X.to(device), y.to(device).view(-1)
optimizer.zero_grad()
alpha=1.0
beta=1.0
with torch.set_grad_enabled(phase == "train"):
pred_emo= model(X)
emotion_loss = criterion(pred_emo,y)
total_loss = alpha*emotion_loss
if phase == "train":
total_loss.backward()
optimizer.step()
lossPerPass.append(total_loss.item())
accuracy.append(accuracy_score(torch.argmax(torch.exp(pred_emo.detach().cpu()), dim=1), y.cpu()))
torch.save(model.state_dict(),"E:/Python_On_All_Dataset/IEMO/long_codes/Kosta.jo/model_checkpoint_spec/Epoch_{}.pt".format(e+1))
epochLoss[phase] = np.mean(np.array(lossPerPass))
epochAccs[phase] = np.mean(np.array(accuracy))
Losses.append(epochLoss)
Accuracies.append(epochAccs)
if verbose:
print("Epoch : {} | Train Loss : {:.5f} | Valid Loss : {:.5f} \
| Train Accuracy : {:.5f} | Valid Accuracy : {:.5f}".format(e + 1, epochLoss["train"], epochLoss["valid"],
epochAccs["train"], epochAccs["valid"]))
Then I am getting this error traceback:
File “”, line 21, in
for X, y in DLS[phase]:
File “C:\Users\krishna\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py”, line 517, in next
data = self._next_data()
File “C:\Users\krishna\Anaconda3\lib\site-packages\torch\utils\data\dataloader.py”, line 557, in _next_data
data = self._dataset_fetcher.fetch(index) # may raise StopIteration
File “C:\Users\krishna\Anaconda3\lib\site-packages\torch\utils\data_utils\fetch.py”, line 47, in fetch
return self.collate_fn(data)
File “C:\Users\krishna\Anaconda3\lib\site-packages\torch\utils\data_utils\collate.py”, line 83, in default_collate
return [default_collate(samples) for samples in transposed]
File “C:\Users\krishna\Anaconda3\lib\site-packages\torch\utils\data_utils\collate.py”, line 83, in
return [default_collate(samples) for samples in transposed]
File “C:\Users\krishna\Anaconda3\lib\site-packages\torch\utils\data_utils\collate.py”, line 55, in default_collate
return torch.stack(batch, 0, out=out)
RuntimeError: stack expects each tensor to be equal size, but got [0] at entry 0 and [3] at entry 1
Can someone comment on this, Is there any problem with class Dataset
or in training
. The tittle of the problem can be changed on suggestions.
please guide
Regards