为了执行线性回归,我对每一个都进行了torch.stack和torch.cat操作,大约花了10分钟,所以我想找到一个最佳方法
from torch.utils.data import random_split // used random_split to
split data
train_ds, val_ds = random_split(dataset,[50000,10000])
len(train_ds) , len(val_ds)
#linear regression self
d = [ ]
n = len(train_ds)
for i in range(0,n):
label = train_ds[i][1]
d.append(label)
a = train_ds[0][0]
b = train_ds[1][0]
c = torch.stack((a,b))
for i in range(2,n):
l = train_ds[i][0].reshape(1,1,28,28)
c = torch.cat((c,l))
train_lables = torch.tensor(d)
耗时(10-15分钟(
在某些语言中,将数组重复串联在一起往往会很慢。如果您知道数据数组的大小,就可以预先分配内存以加快处理速度。
我无法确切地帮助说明细节,因为我不知道train_ds的形状,但优化可能看起来像这样:
n = len(train_ds)
# I'm not sure if this is the actual shape you need
# Adjust according
c = torch.zeros((n, 1, 28, 28))
for i in range(0, n):
c[i] = train_ds[i][0].reshape(1,1,28,28)
声明d
数组的另一种方法是这样调用:
d = [train_ds[i][1] for i in range(n)]
如果你事先知道形状更好,但如果你不知道,那可以这样处理:
c = torch.tensor([
image.reshape(1,1,28,28)
for (image, label) in train_ds
])
d = [label for (image, label) in train_ds]
您将一个python列表传递给torch.tensor
。您可以像这样构建列表(列表理解(,也可以从一个空列表[]
和.append
开始,然后将其传递给torch.tensor
。
还请注意我是如何迭代train_ds
的。你根本不需要摆弄指数。