{"id":272,"hash":"35e68693b53d96d5478c715ab6a5b6d3eee50ad8004436fbed42cb31ea6c3b4a","pattern":"How to fix RuntimeError &quot;Expected object of scalar type Float but got scalar type Double for argument&quot;?","full_message":"I'm trying to train a classifier via PyTorch. However, I am experiencing problems with training when I feed the model with training data.\nI get this error on y_pred = model(X_trainTensor):\n\n  RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'\n\nHere are key parts of my code:\n\n# Hyper-parameters \nD_in = 47  # there are 47 parameters I investigate\nH = 33\nD_out = 2  # output should be either 1 or 0\n\n# Format and load the data\ny = np.array( df['target'] )\nX = np.array( df.drop(columns = ['target'], axis = 1) )\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8)  # split training/test data\n\nX_trainTensor = torch.from_numpy(X_train) # convert to tensors\ny_trainTensor = torch.from_numpy(y_train)\nX_testTensor = torch.from_numpy(X_test)\ny_testTensor = torch.from_numpy(y_test)\n\n# Define the model\nmodel = torch.nn.Sequential(\n    torch.nn.Linear(D_in, H),\n    torch.nn.ReLU(),\n    torch.nn.Linear(H, D_out),\n    nn.LogSoftmax(dim = 1)\n)\n\n# Define the loss function\nloss_fn = torch.nn.NLLLoss() \n\nfor i in range(50):\n    y_pred = model(X_trainTensor)\n    loss = loss_fn(y_pred, y_trainTensor)\n    model.zero_grad()\n    loss.backward()\n    with torch.no_grad():       \n        for param in model.parameters():\n            param -= learning_rate * param.grad","ecosystem":"pypi","package_name":"neural-network","package_version":null,"solution":"Reference is from this github issue.\n\nWhen the error is RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1', you would need to use the .float() function since it says Expected object of scalar type Float.\n\nTherefore, the solution is changing y_pred = model(X_trainTensor) to y_pred = model(X_trainTensor.float()).\n\nLikewise, when you get another error for loss = loss_fn(y_pred, y_trainTensor), you need y_trainTensor.long() since the error message says Expected object of scalar type Long.\n\nYou could also do model.double(), as suggested by @Paddy\n.","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/56741087/how-to-fix-runtimeerror-expected-object-of-scalar-type-float-but-got-scalar-typ","votes":127,"created_at":"2026-04-19T04:41:44.166763+00:00","updated_at":"2026-04-19T04:51:56.197998+00:00"}