【问题标题】:how to convert series numpy array into tensors using pytorch如何使用 pytorch 将系列 numpy 数组转换为张量
【发布时间】:2019-10-23 12:41:27
【问题描述】:

我正在尝试将图像标签转换为张量,但出现了一些错误,请帮我转换为张量: 这是我的代码:

features_train, features_test, targets_train, targets_test = train_test_split(X,Y,test_size=0.2,
                                                                              random_state=42)
X_train = torch.from_numpy(features_train)
X_test = torch.from_numpy(features_test)

Y_train =torch.from_numpy(targets_train).type(torch.IntTensor) 
Y_test = torch.from_numpy(targets_test).type(torch.IntTensor)
train = torch.utils.data.TensorDataset(X_train,Y_train)
test = torch.utils.data.TensorDataset(X_test,Y_test)


train_loader = torch.utils.data.DataLoader(train, batch_size = train_batch_size, shuffle = False)
test_loader = torch.utils.data.DataLoader(test, batch_size = test_batch_size, shuffle = False)

这是我的错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-f1578581ff5c> in <module>()
      5 X_test = torch.from_numpy(features_test)
      6 
----> 7 Y_train =torch.from_numpy(targets_train).type(torch.IntTensor)
      8 Y_test = torch.from_numpy(targets_test).type(torch.IntTensor)
      9 train = torch.utils.data.TensorDataset(X_train,Y_train)

TypeError: expected np.ndarray (got Series)

这是我的数组值:

targets_train
478     1
5099    3
1203    2
5674    2
142     1
4836    2
4031    1
1553    3
4416    1
605     5
1194    3
4319    4
1498    5

【问题讨论】:

标签: python numpy pytorch fast-ai


【解决方案1】:

我会这样做:

import torch
import numpy as np
n = np.arange(10)
print(n) #[0 1 2 3 4 5 6 7 8 9]
t1 = torch.Tensor(n)  # as torch.float32
print(t1) #tensor([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
t2 = torch.from_numpy(n)  # as torch.int32
print(t2) #tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=torch.int32)

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 2019-04-27
    • 2020-03-16
    • 2020-06-27
    • 2021-02-24
    • 2021-04-28
    • 2021-01-08
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多