Sure! Something like this should work to reassign a new parameter to a model: a = torch.randn(...) model = ConvAutoencoder() model.conv3.weight = nn.Parameter(a) Answer from ptrblck on discuss.pytorch.org
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-cant-assign-a-numpyndarray-to-a-torchfloattensor
How to Fix "Can't Assign a numpy.ndarray to a torch.FloatTensor"? - GeeksforGeeks
July 23, 2025 - The error "Can't assign a numpy.ndarray to a torch.FloatTensor" occurs when you attempt to assign a NumPy array to a PyTorch tensor directly, which is not allowed. PyTorch and NumPy are different libraries with different data structures, so ...
🌐
PyTorch Forums
discuss.pytorch.org › t › cant-convert-a-given-np-ndarray-to-a-tensor › 21321
Can't convert a given np.ndarray to a tensor - PyTorch Forums
July 18, 2018 - RuntimeError: can't convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8 · Can you print the type of your data? you might have to cast it as a one of the accepted ...
Discussions

TypeError: cannot assign 'torch.FloatTensor' as parameter 'weight' (torch.nn.Parameter or None expected)
Hello, I want to changed layer replace to this layer but I get this error! I want to shift one hidden layer in row and column… please help me. import numpy as np import torch import torch.nn as nn import torch.nn.funct… More on discuss.pytorch.org
🌐 discuss.pytorch.org
15
0
April 27, 2021
python - How do I assign a numpy.int64 to a torch.cuda.FloatTensor? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow Internal More on stackoverflow.com
🌐 stackoverflow.com
TypeError: can't assign a numpy.ndarray to a torch.ByteTensor
Habitat-Lab and Habitat-Sim versions habitat 0.2.1 habitat-sim 0.2.1 ❓ Questions and Help I have questions when I run the habitat baseline, after I download the test dataset and unzip it correctly ... More on github.com
🌐 github.com
4
October 1, 2021
Error when converting np.float32 array to torch.cuda.FloatTensor
There was an error while loading. Please reload this page · Hi, for some reason it fails, only float64 can be converted More on github.com
🌐 github.com
10
July 30, 2017
🌐
GitHub
github.com › jwyang › faster-rcnn.pytorch › issues › 452
TypeError: can't assign a numpy.int64 to a torch.FloatTensor · Issue #452 · jwyang/faster-rcnn.pytorch
February 28, 2019 - Traceback (most recent call last): File "trainval_net.py", line 209, in imdb.num_classes, training=True) File "/home/NewPartion/pycharm/faster-rcnn.pytorch/lib/roi_data_layer/roibatchLoader.py", line 54, in init self.ratio_list_batch[left_idx:(right_idx+1)] = target_ratio TypeError: can't assign a numpy.int64 to a torch.FloatTensor
Author   jwyang
🌐
PyTorch Forums
discuss.pytorch.org › t › typeerror-cannot-assign-torch-floattensor-as-parameter-weight-torch-nn-parameter-or-none-expected › 119462
TypeError: cannot assign 'torch.FloatTensor' as parameter 'weight' (torch.nn.Parameter or None expected) - PyTorch Forums
April 27, 2021 - Hello, I want to changed layer replace to this layer but I get this error! I want to shift one hidden layer in row and column… please help me. import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import matplotlib.pyplot as plt from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data import DataLoader from torchvision import datasets, transforms #%% #Converting data to torch.FloatTensor transform = transforms....
🌐
GitHub
github.com › facebookresearch › habitat-lab › issues › 742
TypeError: can't assign a numpy.ndarray to a torch.ByteTensor · Issue #742 · facebookresearch/habitat-lab
October 1, 2021 - TypeError: can't assign a numpy.ndarray to a torch.ByteTensor#742 · #744 · Copy link · JiayunjieJYJ · opened · on Oct 1, 2021 · Issue body actions · habitat 0.2.1 habitat-sim 0.2.1 · python -u habitat_baselines/run.py --exp-config habitat_baselines/config/pointnav/ppo_pointnav_example.yaml --run-type train ·
Author   facebookresearch
🌐
GitHub
github.com › pytorch › pytorch › issues › 2246
Error when converting np.float32 array to torch.cuda.FloatTensor · Issue #2246 · pytorch/pytorch
July 30, 2017 - Hi, for some reason it fails, only float64 can be converted. torch.cuda.FloatTensor(np.random.rand(10,2).astype(np.float32)) gives RuntimeError: tried to construct a tensor from a nested float sequence, but found an item of type numpy.fl...
Author   pytorch
🌐
Fast.ai
forums.fast.ai › part 1 (2018) › beginner (2018)
np.ndArray in tensor - Beginner (2018)
November 28, 2017 - Hi everyone, I am trying to run Resnet18 on STL_10, but get the following error message: RuntimeError: can’t convert a given np.ndarray to a tensor - it has an invalid type. The only supported types are: double, float, int64, int32, and uint8.
Find elsewhere
🌐
PyTorch Forums
discuss.pytorch.org › vision
Creating tensor TypeError: can't convert np.ndarray of type numpy.object_ - vision - PyTorch Forums
July 4, 2021 - X = final_df.values y = df['Target'].values from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.4, random_state=42) train_inputs = torch.tensor(X_train,dtype=torch.float).tag("#iot", "#network","#data","#train") train_labels ...
🌐
GitHub
github.com › vwxyzjn › cleanrl › issues › 26
TypeError: can't assign a list to a torch.cuda.FloatTensor · Issue #26 · vwxyzjn/cleanrl
August 14, 2020 - TypeError: can't assign a list to a torch.cuda.FloatTensor#26 · Copy link · Kimonili · opened · on Aug 14, 2020 · Issue body actions · I got the above error in the line · cleanrl/cleanrl/ppo.py · Line 217 in bb18a39 · obs[step] = next_obs · as my state space is a list [Box(4,)]. In order to address it, I converted next_obs to a tensor before assigning it to the obs tensor's selected index.
Author   vwxyzjn
🌐
GitHub
github.com › pytorch › pytorch › issues › 135836
TypeError: expected np.ndarray (got numpy.ndarray) · Issue #135836 · pytorch/pytorch
September 12, 2024 - import numpy as np import torch import torch.nn as nn x = np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=np.float32) y = torch.from_numpy(x)
Author   pytorch
🌐
Reddit
reddit.com › r/pytorch › typeerror: input tensor should be a float tensor. got torch.uint8.
r/pytorch on Reddit: TypeError: Input tensor should be a float tensor. Got torch.uint8.
March 28, 2023 -

I am going round in circles with this error. Could anyone offer a pointer? I'm new to python and pytorch.

import os
import cv2
import numpy as np
import skops.io as sio  # to load the saved model
from PIL import Image
from skimage.filters import laplace, sobel, roberts
from torchvision import transforms

# Load the saved SVM model
svm_model = sio.load("svm_model_trained.skops", trusted=True)

# Define the path to the directory containing the test images
test_images_dir = '/Users/test/project_dataset/archive'

# Define the label names for the predicted classes
label_names = ['Sharp', 'Defocussed', 'Motion_blurred']

# Define the transformation to be applied to each image
transform = transforms.Compose({
    transforms.PILToTensor(),
    transforms.Resize((224, 224)),
    transforms.Normalize(mean=(0, 0, 0), std=(1, 1, 1)),
    transforms.ToTensor(),

})

# Loop over each image in the test directory and predict its class
for img_name in os.listdir(test_images_dir):
if not img_name.startswith('.'):
    img_path = os.path.join(test_images_dir, img_name)
    img = Image.open(img_path)
    img = transform(img)
    img = np.array([img.numpy()])

    features = []

    image_gray = cv2.cvtColor(img[0], cv2.COLOR_RGB2GRAY)
    lap_feat = laplace(image_gray)
    sob_feat = sobel(image_gray)
    rob_feat = roberts(image_gray)
    features.extend([lap_feat.mean(), lap_feat.var(), np.amax(lap_feat),
                     sob_feat.mean(), sob_feat.var(), np.max(sob_feat),
                     rob_feat.mean(), rob_feat.var(), np.max(rob_feat)])
    features = np.array([features])
    pred = svm_model.predict(features)
    print(f"Image {img_name} is classified as {label_names[pred[0]]}")
🌐
PyTorch Forums
discuss.pytorch.org › t › typeerror-cant-convert-np-ndarray-of-type-numpy-bool-the-only-supported-types-are-double-float-float16-int64-int32-and-uint8 › 88440
TypeError: can't convert np.ndarray of type numpy.bool_. The only supported types are: double, float, float16, int64, int32, and uint8 - PyTorch Forums
July 8, 2020 - Hello, I get an error (TypeError: can’t convert np.ndarray of type numpy.bool_. The only supported types are: double, float, float16, int64, int32, and uint8) when running my DataLoader in the line where the indices are…
🌐
PyTorch Forums
discuss.pytorch.org › t › avoid-writeable-warning-when-copying-numpy-into-pytorch-tensor › 133223
Avoid writeable warning when copying numpy into pytorch tensor - PyTorch Forums
September 30, 2021 - Hey, I’m trying to optimize my data loading pipeline, and I’ve run into this warning: UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors.
🌐
PyTorch Forums
discuss.pytorch.org › vision
How to make a Tensor from ndarray of type object - vision - PyTorch Forums
July 29, 2021 - I am new to PyTorch. I have an array of length 6 and shape (6, ) when I run torch.from_numpy(data_array), I got this error: TypeError: can’t convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, ...
🌐
Stack Abuse
stackabuse.com › numpy-array-to-tensor-and-tensor-to-numpy-array-with-pytorch
To convert a Numpy array to a PyTorch tensor
May 22, 2023 - # Create tensor on the GPU tensor = torch.tensor([1, 2, 3, 4, 5], dtype=torch.float32, requires_grad=True).cuda() np_b = tensor.detach().numpy() # TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
🌐
PyTorch Forums
discuss.pytorch.org › t › issue-with-conversion-from-numpy › 6345
Issue with conversion from Numpy - PyTorch Forums
August 17, 2017 - I created a very simple autoencoder and have been looking to feed in data that I have converted from Numpy. I found that when I convert from numpy “float” array using torch.from_numpy it gives me an array of torch DoubleTensor. When I feed this into my model it causes problems with the linear layer, giving the message: torch.addmm received an invalid combination of arguments… when I convert the torch double tensor to type float this error goes away.
🌐
Stack Overflow
stackoverflow.com › questions › 74669588 › error-in-converting-torch-tensor-to-numpy-ndarray
python - Error in converting torch tensor to numpy.ndarray - Stack Overflow
December 3, 2022 - 188 Pytorch tensor to numpy array · 17 TypeError: tensor is not a torch image · 1 RuntimeError: Expected a Tensor of type torch.FloatTensor but found a type torch.IntTensor for sequence element · 2 How can I convert numpy.ndarray having type object to torch.tensor?