RuntimeError: expected scalar type Long but found Float for GRU

Hi, I am having a tensor-type issue with my GRU. I know that similar issues have been solved here before but I cant seem to bring the same solution to my problem. Any help would be greatly appreciated.

import pandas as pd
import numpy as np
import torch
import torchvision  # torch package for vision related things
import torch.nn.functional as F  # Parameterless functions, like (some) activation functions
import torchvision.datasets as datasets  # Standard datasets
import torchvision.transforms as transforms  # Transformations we can perform on our dataset for augmentation
from torch import optim  # For optimizers like SGD, Adam, etc.
from torch import nn  # All neural network modules
from import Dataset, DataLoader  # Gives easier dataset managment by creating mini batches etc.
from tqdm import tqdm  # For a nice progress bar
from sklearn.preprocessing import StandardScaler

# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# Hyperparameters
input_size = 24
hidden_size = 128
num_layers = 1
num_classes = 2
sequence_length = 1
learning_rate = 0.005
batch_size = 8
num_epochs = 3

# Recurrent neural network with GRU (many-to-one)
class RNN_GRU(nn.Module):
    def __init__(self, input_size, hidden_size, num_layers, num_classes):
        super(RNN_GRU, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers
        self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_size * sequence_length, num_classes)

    def forward(self, x):
        # Set initial hidden and cell states
        x = x.unsqueeze(1)
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device)
        # Forward propagate GRU
        out, _ = self.gru(x, h0)
        out = out[:, -1, :]

        # Decode the hidden state of the last time step
        out = self.fc(out)
        return out

class MyDataset(Dataset):
  def __init__(self,file_name):
  def __len__(self):
    return len(self.y_train)
  def __getitem__(self,idx):
    return self.x_train[idx],self.y_train[idx]


# Initialize network 
model = RNN_GRU(input_size, hidden_size, num_layers, num_classes).to(device)

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

# Train Network
for epoch in range(num_epochs):
    for batch_idx, (data, targets) in enumerate(tqdm(train_loader)):
        # Get data to cuda if possible
        data =
        targets =

        # forward
        scores = model(data)
        loss = criterion(scores, targets)

        # backward

        # gradient descent update step/adam step

# Check accuracy on training & test to see how good our model
def check_accuracy(loader, model):
    num_correct = 0
    num_samples = 0

    # Set model to eval

    with torch.no_grad():
        for x, y in loader:
            x =
            y =

            scores = model(x)
            _, predictions = scores.max(1)
            num_correct += (predictions == y).sum()
            num_samples += predictions.size(0)

    # Toggle model back to train
    return num_correct / num_samples

print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:2f}")
print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}")

Here is the error

(FYP) C:\Users\steph\FYP>python
  0%|                                                                                                                                                                                       | 0/8 [00:00<?, ?it/s]
Traceback (most recent call last):
  File "", line 86, in <module>
    scores = model(data)
  File "C:\Users\steph\anaconda3\envs\FYP\lib\site-packages\torch\nn\modules\", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "", line 42, in forward
    out, _ = self.gru(x, h0)
  File "C:\Users\steph\anaconda3\envs\FYP\lib\site-packages\torch\nn\modules\", line 889, in _call_impl
    result = self.forward(*input, **kwargs)
  File "C:\Users\steph\anaconda3\envs\FYP\lib\site-packages\torch\nn\modules\", line 821, in forward
    result = _VF.gru(input, hx, self._flat_weights, self.bias, self.num_layers,
RuntimeError: expected scalar type Long but found Float

Based on your code snippet you are storing the input data as LongTensors in:


while the nn.GRU layer has floating point parameters and also expects floating point inputs.
Use dtype=torch.float32 while creating the tensor and it should work.