The error message "TypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool." indicates that the data type of the labels array is not supported by the torch.tensor() function. The supported data types are float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

You are encountering this issue because the labels array contains data of type numpy.object_, which is not directly convertible to a PyTorch tensor. This typically occurs when the labels are read from a CSV file where the values are interpreted as strings or objects.

To resolve this, you need to convert the labels array to a supported data type before creating the tensor. Since you mentioned the labels are integers, you can use the astype() function from the NumPy library to convert the data type.

Here's how to modify your code:

self.labels.append(torch.tensor(labels.values.astype(int), dtype=torch.float))

This code will:

  1. Convert the labels array to integers: labels.values.astype(int) converts the elements of the labels array to integers.
  2. Create a PyTorch tensor: torch.tensor(..., dtype=torch.float) creates a PyTorch tensor from the converted integer array, specifying the desired data type as torch.float.

By making this change, you'll ensure that the labels are in a compatible data type for PyTorch tensors, eliminating the TypeError.

Remember: If your labels are not integers, you'll need to adjust the astype() method accordingly. For example, if your labels are floating-point numbers, use labels.values.astype(float).

This solution should help you successfully load and process your data for use in your PyTorch model.

TypeError: Can't Convert NumPy Array of Type 'numpy.object_' to Torch Tensor

原文地址: https://www.cveoy.top/t/topic/pahx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录