我正在尝试为我的神经网络实现自定义数据集。但是在运行转发功能时出现此错误。代码如下。
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import numpy as np
class ParamData(Dataset):
def __init__(self,file_name):
self.data = torch.Tensor(np.loadtxt(file_name,delimiter = ',')) #first place
def __len__(self):
return self.data.size()[0]
def __getitem__(self,i):
return self.data[i]
class Net(nn.Module):
def __init__(self,in_size,out_size,layer_size=200):
super(Net,self).__init__()
self.layer = nn.Linear(in_size,layer_size)
self.out_layer = nn.Linear(layer_size,out_size)
def forward(self,x):
x = F.relu(self.layer(x))
x = self.out_layer(x)
return x
datafile = 'data1.txt'
net = Net(100,1)
dataset = ParamData(datafile)
n_samples = len(dataset)
#dataset = torch.Tensor(dataset,dtype=torch.double) #second place
#net.float() #thrid place …
Run Code Online (Sandbox Code Playgroud) 我是 PyTorch 的初学者,我只是在此网页上尝试一些示例。但由于此错误,我似乎无法运行“super_resolution”程序:
RuntimeError: DataLoader worker (pid(s) 15332) exited unexpectedly
我在网上搜索,发现有人建议设置num_workers
为0
. 但是如果我这样做,程序会告诉我内存不足(CPU 或 GPU):
RuntimeError: [enforce fail at ..\c10\core\CPUAllocator.cpp:72] data. DefaultCPUAllocator: not enough memory: you tried to allocate 9663676416 bytes. Buy new RAM!
或者
RuntimeError: CUDA out of memory. Tried to allocate 1024.00 MiB (GPU 0; 4.00 GiB total capacity; 2.03 GiB already allocated; 0 bytes free; 2.03 GiB reserved in total by PyTorch)
我该如何解决?
我在 Win10(64 位)和 pytorch 1.4.0 上使用 python 3.8。
更完整的错误信息( …
所以我有一个 python 程序,它读取这样的配置文件:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', type=str, help='config file', required=True)
args = parser.parse_args()
cfg_filename = args.config
Run Code Online (Sandbox Code Playgroud)
我希望能够在 bash 中自动完成路径。例如,假设调用了上面的程序,main.py
并且有一个名为 的配置文件config_1.txt
,其结构如下:
folder/
main.py
configs/
config_1.txt
Run Code Online (Sandbox Code Playgroud)
假设在我的终端中它看起来像
folder/
main.py
configs/
config_1.txt
Run Code Online (Sandbox Code Playgroud)
我希望按一个选项卡会给出:
user@host:~/folder$ python main.py -c con
Run Code Online (Sandbox Code Playgroud)
然后另一个选项卡给出
user@host:~/folder$ python main.py -c config/
Run Code Online (Sandbox Code Playgroud)
我尝试过添加
import argcomplete
argcomplete.autocomplete(parser)
Run Code Online (Sandbox Code Playgroud)
但没有用。
假设我layer
在 Torch 模块中有一个层,并在一个forward
步骤中使用它两次或更多次,这样输出的结果layer
稍后会再次输入到相同的layer
. pytorch 能否正确autograd
计算该层权重的梯度?
这是我正在谈论的内容:
import torch
import torch.nn as nn
import torch.nn.functional as F
class net(nn.Module):
def __init__(self,in_dim,out_dim):
super(net,self).__init__()
self.layer = nn.Linear(in_dim,out_dim,bias=False)
def forward(self,x):
x = self.layer(x)
x = self.layer(x)
return x
input_x = torch.tensor([10.])
label = torch.tensor([5.])
n = net(1,1)
loss_fn = nn.MSELoss()
out = n(input_x)
loss = loss_fn(out,label)
n.zero_grad()
loss.backward()
for param in n.parameters():
w = param.item()
g = param.grad
print('Input = %.4f; label = …
Run Code Online (Sandbox Code Playgroud) 根据官方文档,使用train()
或eval()
会对某些模块产生影响。但是,现在我希望用我的自定义模块实现类似的功能,即它在train()
打开时执行某些操作,而在eval()
打开时执行一些不同的操作。我怎样才能做到这一点?
一个mwe如下:
import torch
import torch.nn as nn
class model(nn.Module):
def __init__(self):
super(model,self).__init__()
self.mat = torch.randn(2,2)
def forward(self,x):
print('self.mat.device is',self.mat.device)
x = torch.mv(self.mat,x)
return x
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
m = model()
m.to(device)
x = torch.tensor([2.,1.])
x = x.to(device)
m(x)
Run Code Online (Sandbox Code Playgroud)
输出是
self.mat.device is cpu
Run Code Online (Sandbox Code Playgroud)
紧接着
Traceback (most recent call last):
File "Z:\cudatest.py", line 21, in <module>
print(m(x))
File "E:\Python37\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
result = self.forward(*input, **kwargs)
File "Z:\cudatest.py", line 11, in forward
x = torch.mv(self.mat,x)
RuntimeError: Expected …
Run Code Online (Sandbox Code Playgroud) 假设我有一个x
shape 的numpy 数组[1,5]
。我想沿轴 0 扩展它,使得生成的数组y
具有形状 [10,5] 并且对于每个 i 都y[i:i+1,:]
等于x
。
如果x
是一个 pytorch 张量我可以简单地做
y = x.expand(10,-1)
Run Code Online (Sandbox Code Playgroud)
但是 numpy 中没有expand
,并且那些看起来像它(expand_dims
和repeat
)的行为似乎不像它。
例子:
y = x.expand(10,-1)
Run Code Online (Sandbox Code Playgroud) 我正在为 pytorch 编写一个 C++ 扩展,其中我需要通过索引访问张量的元素,并且还需要将元素转换为标准 C++ 类型。这是一个简短的例子。假设我有一个二维张量a
,我需要访问a[i][j]
它并将其转换为浮点数。
#include <torch/extension.h>\n\nfloat get(torch::Tensor a, int i, int j) {\n return a[i][j];\n}\n
Run Code Online (Sandbox Code Playgroud)\n上面的内容被放入一个名为tensortest.cpp
. 在另一个文件中setup.py
我写
from setuptools import setup, Extension\nfrom torch.utils import cpp_extension\n\nsetup(name=\'tensortest\',\n ext_modules=[cpp_extension.CppExtension(\'tensortest_cpp\', [\'tensortest.cpp\'])],\n cmdclass={\'build_ext\': cpp_extension.BuildExtension})\n
Run Code Online (Sandbox Code Playgroud)\n当我运行python setup.py install
编译器时报告以下错误
running install\nrunning bdist_egg\nrunning egg_info\ncreating tensortest.egg-info\nwriting tensortest.egg-info/PKG-INFO\nwriting dependency_links to tensortest.egg-info/dependency_links.txt\nwriting top-level names to tensortest.egg-info/top_level.txt\nwriting manifest file \'tensortest.egg-info/SOURCES.txt\'\n/home/trisst/.local/lib/python3.8/site-packages/torch/utils/cpp_extension.py:335: UserWarning: Attempted to use ninja as the BuildExtension backend but we could not find …
Run Code Online (Sandbox Code Playgroud) 假设我有一个 C++std::list
对象,其中包含一些元素和一个指向it
其中一个元素的迭代器。如何从列表中删除此元素但仍然能够访问它?换句话说,我希望它从列表中取消链接,但不取消分配。
奇怪的是,使用list::erase
似乎确实实现了这一点:
#include <iostream>
#include <cstdio>
#include <list>
using namespace std;
int main() {
std::list<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
auto it = (--a.end());
a.erase(it);
cout << *it << endl; /// outputs '3' anyway, without any error
}
Run Code Online (Sandbox Code Playgroud)
但我认为这并不安全?
问题:
是否保证被删除的元素list::erase
仍然可以被原始迭代器访问?
如果是,我怎样才能释放它的内存?
如果不是,如何删除某些元素而不释放其内存并在删除后能够访问它?
我记得看到过一些像这样工作的命令:
g++ main.cpp `some_forgotten_command --some_forgotten_options some_library`
Run Code Online (Sandbox Code Playgroud)
当命令运行时,它将用-I/path/to/some_library/include
and替换 `` 括起来的部分-L/path/to/some_library/lib/
(或者类似的东西,我不太记得了)。但我不记得是什么some_forgotten_command
了。