我的任務是創建一個資料集來測驗我們正在處理的代碼的功能。
資料集必須有一組張量,稍后將在生成模型中使用。
我正在嘗試將張量保存到 .pt 檔案中,但我正在覆寫張量,從而創建一個只有一個的檔案。我已經閱讀過,torch.utils.data.dataset但我無法自己弄清楚如何使用它。
這是我的代碼:
import torch
import numpy as np
from torch.utils.data import Dataset
#variables that will be used to create the size of the tensors:
num_jets, num_particles, num_features = 1, 30, 3
for i in range(100):
#tensor from a gaussian dist with mean=5,std=1 and shape=size:
tensor = torch.normal(5,1,size=(num_jets, num_particles, num_features))
#We will need the tensors to be of the cpu type
tensor = tensor.cpu()
#save the tensor to 'tensor_dataset.pt'
torch.save(tensor,'tensor_dataset.pt')
#open the recently created .pt file inside a list
tensor_list = torch.load('tensor_dataset.pt')
#prints the list. Just one tensor inside .pt file
print(tensor_list)
uj5u.com熱心網友回復:
原因:你在回圈中每次都覆寫x了張量,因此你沒有得到你的串列,你最后只有 x。
解決方案:你有張量的大小,你可以先初始化一個張量并迭代lst_tensors:
import torch
import numpy as np
from torch.utils.data import Dataset
num_jets, num_particles, num_features = 1, 30, 3
lst_tensors = torch.empty(size=(100,num_jets, num_particles, num_features))
for i in range(100):
lst_tensors[i] = torch.normal(5,1,size=(num_jets, num_particles, num_features))
lst_tensors[i] = lst_tensors[i].cpu()
torch.save(lst_tensors,'tensor_dataset.pt')
tensor_list = torch.load('tensor_dataset.pt')
print(tensor_list.shape) # [100,1,30,3]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/433629.html
上一篇:RidgeCV()和GridSearchCV()的區別
下一篇:Conv2D與GAN中的層不兼容
