我正在处理文本并使用torchtext.data.Dataset. 创建数据集需要相当长的时间。对于只是运行程序,这仍然是可以接受的。但我想调试神经网络的火炬代码。如果 Python 在调试模式下启动,数据集创建大约需要 20 分钟 (!!)。这只是为了获得一个工作环境,我可以在其中调试神经网络代码。
我想保存数据集,例如使用泡菜。此示例代码取自此处,但我删除了此示例不需要的所有内容:
from torchtext import data
from fastai.nlp import *
PATH = 'data/aclImdb/'
TRN_PATH = 'train/all/'
VAL_PATH = 'test/all/'
TRN = f'{PATH}{TRN_PATH}'
VAL = f'{PATH}{VAL_PATH}'
TEXT = data.Field(lower=True, tokenize="spacy")
bs = 64;
bptt = 70
FILES = dict(train=TRN_PATH, validation=VAL_PATH, test=VAL_PATH)
md = LanguageModelData.from_text_files(PATH, TEXT, **FILES, bs=bs, bptt=bptt, min_freq=10)
with open("md.pkl", "wb") as file:
pickle.dump(md, file)
Run Code Online (Sandbox Code Playgroud)
要运行代码,您需要 aclImdb 数据集,可以从这里下载。将其解压缩data/到此代码片段旁边的文件夹中。代码在最后一行产生错误,其中使用了pickle:
Traceback (most recent call last):
File "/home/lhk/programming/fastai_sandbox/lesson4-imdb2.py", line …Run Code Online (Sandbox Code Playgroud) 我尝试了几种解决方案,这些解决方案暗示了当 CUDA GPU 可用并且安装了 CUDA 但Torch.cuda.is_available()返回False. 他们确实提供了帮助,但只是暂时的,这意味着torch.cuda-is_available()报告 True 但过了一段时间,它又切换回 False。我使用 CUDA 9.0.176 和 GTX 1080。我应该怎么做才能获得永久效果?
我尝试了以下方法:
https://forums.fast.ai/t/torch-cuda-is-available-returns-false/16721/5 https://github.com/pytorch/pytorch/issues/15612
注意:当torch.cuda.is_available()工作正常但在某些时候切换到 时False,我必须重新启动计算机,然后它再次工作(一段时间)。
PyTorch 输入的维度不是模型所期望的,我不确定为什么。
以我的理解...
in_channels 首先是我们想要传递给模型的一维输入的数量,并且是所有后续层的前一个 out_channel。
out_channels 是所需的内核数(过滤器)。
kernel_size 是每个过滤器的参数数量。
因此,我们期望,随着数据向前传递,具有 7 个 1D 通道(即 2D 输入)的数据集。
但是,下面的代码抛出了一个与我期望的不一致的错误,代码如下:
import numpy
import torch
X = numpy.random.uniform(-10, 10, 70).reshape(-1, 7)
# Y = np.random.randint(0, 9, 10).reshape(-1, 1)
class Simple1DCNN(torch.nn.Module):
def __init__(self):
super(Simple1DCNN, self).__init__()
self.layer1 = torch.nn.Conv1d(in_channels=7, out_channels=20, kernel_size=5, stride=2)
self.act1 = torch.nn.ReLU()
self.layer2 = torch.nn.Conv1d(in_channels=20, out_channels=10, kernel_size=1)
def forward(self, x):
x = self.layer1(x)
x = self.act1(x)
x = self.layer2(x)
log_probs = torch.nn.functional.log_softmax(x, dim=1)
return log_probs
model = Simple1DCNN()
print(model(torch.tensor(X)).size)
Run Code Online (Sandbox Code Playgroud)
抛出以下错误:
---------------------------------------------------------------------------
RuntimeError …Run Code Online (Sandbox Code Playgroud) 在 Python 中:
>>> import numpy as np
>>> x0=np.random.rand(3000,3000)
>>> t=time.perf_counter(); y0=np.matmul(x0,x0); time.perf_counter()-t
0.8358144999947399
>>> import torch
>>> x=torch.rand(3000,3000)
>>> t=time.perf_counter(); y0=np.matmul(x,x); time.perf_counter()-t
0.4304323000833392
Run Code Online (Sandbox Code Playgroud)
在 R 中:
> a=matrix(runif(9000000), 3000, 3000)
> a1=a%*%a
> system.time({a1=a%*%a})
user system elapsed
16.53 0.04 16.57
Run Code Online (Sandbox Code Playgroud)
为什么 numpy 的差异是 20 倍,而 Torch 的差异是 40 倍?
我正在开发一个基于火炬的库,用于使用表格数据集构建自动编码器。
一大特点是学习分类特征的嵌入。
然而,在实践中,同时训练许多嵌入层会造成一些减速。我正在使用 for 循环来执行此操作,并且在每次迭代中运行 for 循环是(我认为)导致速度变慢的原因。
在构建模型时,我将嵌入层与用户数据集中的每个分类特征相关联:
for ft in self.categorical_fts:
feature = self.categorical_fts[ft]
n_cats = len(feature['cats']) + 1
embed_dim = compute_embedding_size(n_cats)
embed_layer = torch.nn.Embedding(n_cats, embed_dim)
feature['embedding'] = embed_layer
Run Code Online (Sandbox Code Playgroud)
然后,调用 .forward():
embeddings = []
for i, ft in enumerate(self.categorical_fts):
feature = self.categorical_fts[ft]
emb = feature['embedding'](codes[i])
embeddings.append(emb)
#num and bin are numeric and binary features
x = torch.cat(num + bin + embeddings, dim=1)
Run Code Online (Sandbox Code Playgroud)
然后x进入密集层。
这完成了工作,但在每次前向传递期间运行此 for 循环确实会减慢训练速度,尤其是当数据集具有数十或数百个分类列时。
有人知道像这样矢量化的方法吗?谢谢!
更新:为了更清晰,我绘制了我如何将分类特征输入网络的草图。您可以看到每个分类列都有自己的嵌入矩阵,而数字特征在传递到前馈网络之前直接连接到它们的输出。
我们可以在不迭代每个嵌入矩阵的情况下做到这一点吗?
我在 C++ 中有一个自定义的LSTMpytorch模型。训练后,我使用保存模型
torch::save(lstmNetwork, 'model.pt');
Run Code Online (Sandbox Code Playgroud)
其中lstmNetwork是std::shared_ptr<LSTMNetwork>;
class LSTMNetwork : public torch::nn::Module {
public:
LSTMNetwork(const torch::nn::LSTMOptions &lstmOpts1,
const torch::nn::LSTMOptions &lstmOpts2,
const torch::nn::LinearOptions &linearOpts);
~LSTMNetwork();
torch::Tensor forward(const torch::Tensor &x);
private:
torch::nn::LSTM lstm1;
torch::nn::LSTM lstm2;
torch::nn::Linear linear;
};
LSTMNetwork::LSTMNetwork(const torch::nn::LSTMOptions &lstmOpts1,
const torch::nn::LSTMOptions &lstmOpts2,
const torch::nn::LinearOptions &linearOpts)
: torch::nn::Module(),
lstm1(register_module("lstm1", torch::nn::LSTM(lstmOpts1))),
lstm2(register_module("lstm2", torch::nn::LSTM(lstmOpts2))),
linear(register_module("linear", torch::nn::Linear(linearOpts))) {}
LSTMNetwork::~LSTMNetwork() {}
torch::Tensor LSTMNetwork::forward(const torch::Tensor &input) {
torch::nn::RNNOutput lstm_out = this->lstm1->forward(input);
lstm_out = this->lstm2->forward(lstm_out.output);
torch::Tensor y_pred = this->linear(lstm_out.output[-1]);
return …Run Code Online (Sandbox Code Playgroud) 我有一个带有 PyTorch 和 Tensorflow 的 conda 环境,它们都需要 CUDA 9.0(来自 conda 的~cudatoolkit 9.0)。在使用torchvision和cudatoolkit(就像他们在他们的网站上提供的)安装pytorch之后,我想安装Tensorflow,这里的问题是我收到这个错误:
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: /
Found conflicts! Looking for incompatible packages.
This can take several minutes. Press CTRL-C to abort.
failed
UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment: …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 protobuf 序列化火炬张量,但似乎BytesIO与 with 一起使用torch.save()不起作用。我试过了:
import torch
import io
x = torch.randn(size=(1,20))
buff = io.BytesIO()
torch.save(x, buff)
print(f'buffer: {buff.read()}')
Run Code Online (Sandbox Code Playgroud)
无济于事,因为它会导致b''输出!我该怎么办?
我正在尝试在 Google Colab 上运行以下内容:
!pip install torch_sparse
起初,它似乎工作正常:
Collecting torch_sparse
Downloading https://files.pythonhosted.org/packages/9a/86/699eb78ea7ce259da7f9953858ec2a064e4e5f5e6bf7de53aa6c8bb8b9a8/torch_sparse-0.6.9.tar.gz
Requirement already satisfied: scipy in /usr/local/lib/python3.7/dist-packages (from torch_sparse) (1.4.1)
Requirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.7/dist-packages (from scipy->torch_sparse) (1.19.5)
Building wheels for collected packages: torch-sparse
Run Code Online (Sandbox Code Playgroud)
但从这里开始,它会一直运行,不会输出任何错误消息,并且轮子永远不会被构建。
我的 Colab 环境是托管的并使用 GPU 加速器。我也可以预先安装火炬并初始化 cuda,但它不会改变任何东西。
torch ×10
pytorch ×7
python ×6
autoencoder ×1
c++ ×1
conda ×1
embedding ×1
lua ×1
numpy ×1
performance ×1
pickle ×1
r ×1
tensorflow ×1
torchtext ×1