标签: pytorch

PyTorch 相当于`numpy.unpackbits`?

我正在 GPU 上训练神经网络。它使用了很多二进制输入功能。

由于将数据移入/移出 GPU 的成本很高,因此我正在寻找使初始表示更紧凑的方法。现在,我将我的特征编码为int8,将它们移到 GPU 上,然后扩展为float32

# create int8
features = torch.zeros(*dims, dtype=torch.int8)

# fill in some data (set some features to 1.)
…

# move int8 to GPU
features = features.to(device=cuda, non_blocking=True)

# expand int8 as float32
features = features.to(dtype=float32)
Run Code Online (Sandbox Code Playgroud)

现在,我正在寻找将这些二进制特征压缩为位而不是字节的方法。

NumPy 有函数packbitsunpackbits

>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, …
Run Code Online (Sandbox Code Playgroud)

pytorch

7
推荐指数
1
解决办法
528
查看次数

是否可以在不首先在本地持久化的情况下从 GCS 存储桶 URL 加载预训练的 Pytorch 模型?

我是在 Google Dataflow 的背景下问这个问题的,但也是一般的。

使用 PyTorch,我可以引用包含多个文件的本地目录,这些文件构成一个预训练模型。我碰巧使用的是 Roberta 模型,但其他人的界面是一样的。

ls some-directory/
      added_tokens.json
      config.json             
      merges.txt              
      pytorch_model.bin       
      special_tokens_map.json vocab.json
Run Code Online (Sandbox Code Playgroud)
ls some-directory/
      added_tokens.json
      config.json             
      merges.txt              
      pytorch_model.bin       
      special_tokens_map.json vocab.json
Run Code Online (Sandbox Code Playgroud)

但是,我的预训练模型存储在 GCS 存储桶中。让我们称之为gs://my-bucket/roberta/

在 Google Dataflow 中加载这个模型的上下文中,我试图保持无状态并避免持久化到磁盘,所以我更喜欢直接从 GCS 获取这个模型。据我了解,PyTorch 通用接口方法from_pretrained()可以采用本地目录或 URL 的字符串表示形式。但是,我似乎无法从 GCS URL 加载模型。

from pytorch_transformers import RobertaModel

# this works
model = RobertaModel.from_pretrained('/path/to/some-directory/')
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用目录 blob 的公共 https URL,它也会失败,尽管这可能是由于缺乏身份验证,因为在可以创建客户端的 python 环境中引用的凭据不会转换为公共请求https://storage.googleapis

# this fails, probably due to auth
bucket = gcs_client.get_bucket('my-bucket')
directory_blob = bucket.blob(prefix='roberta')
model = RobertaModel.from_pretrained(directory_blob.public_url)
# …
Run Code Online (Sandbox Code Playgroud)

python google-cloud-storage google-cloud-dataflow pytorch

7
推荐指数
1
解决办法
2850
查看次数

如何实现强大的背景去除?

我发现基于深度学习的方法(例如,1)比基于非深度学习的方法(例如,2,使用 OpenCV)健壮得多。

  1. https://www.remove.bg
  2. 如何从这种图像中删除背景?

在 OpenCV 示例中,Canny 用于检测边缘。但是这一步可能对图像非常敏感。轮廓检测可能会以错误的轮廓结束。也很难确定应该保留哪些轮廓。

如何实现稳健的深度学习方法?有什么好的示例代码吗?谢谢。

computer-vision deep-learning keras tensorflow pytorch

7
推荐指数
1
解决办法
4495
查看次数

如何修复pytorch中的“输入和隐藏张量不在同一设备上”

当我想将模型放在 GPU 上时,出现以下错误:

“运行时错误:输入张量和隐藏张量不在同一设备上,在 cuda:0 处找到输入张量,在 cpu 处找到隐藏张量”

但是,以上所有内容都已放在 GPU 上:

for m in model.parameters():
    print(m.device) #return cuda:0
Run Code Online (Sandbox Code Playgroud)
for m in model.parameters():
    print(m.device) #return cuda:0
Run Code Online (Sandbox Code Playgroud)

Windows 10 服务器
Pytorch 1.2.0 + cuda 9.2
cuda 9.2
cudnn 7.6.3 for cuda 9.2

python gpu python-3.x lstm pytorch

7
推荐指数
1
解决办法
1万
查看次数

NLP Transformers:获得固定句子嵌入向量形状的最佳方法?

我正在从火炬中心加载语言模型(CamemBERT是基于法语 RoBERTa 的模型)并使用它嵌入一些法语句子:

import torch
camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0')
camembert.eval()  # disable dropout (or leave in train mode to finetune)


def embed(sentence):
   tokens = camembert.encode(sentence)
   # Extract all layer's features (layer 0 is the embedding layer)
   all_layers = camembert.extract_features(tokens, return_all_hiddens=True)
   embeddings = all_layers[0]
   return embeddings

# Here we see that the shape of the embedding vector depends on the number of tokens in the sentence

u = embed(sentence="Bonjour, ça va ?")
u.shape # torch.Size([1, 7, 768])
v = …
Run Code Online (Sandbox Code Playgroud)

nlp machine-learning deep-learning word-embedding pytorch

7
推荐指数
2
解决办法
7110
查看次数

如何修改 Torch Hub 模型的下载路径

当我通过 Torch Hub 下载模型时,模型会自动以/home/me/.cache/torch.

如何修改此行为?

path pytorch

7
推荐指数
1
解决办法
2632
查看次数

我们如何将 .pth 模型转换为 .pb 文件?

我已经通过使用 pytorch 获得了完整的模型,但是我想将 .pth 文件转换为 .pb,它可以在 Tensorflow 中使用。有没有人有一些想法?

tensorflow pytorch

7
推荐指数
1
解决办法
6511
查看次数

在C++中将pytorch张量转换为opencv mat,反之亦然

我想在 C++ 中将 pytorch 张量转换为 opencv mat,反之亦然。我有这两个功能:

cv::Mat TensorToCVMat(torch::Tensor tensor)
{
    std::cout << "converting tensor to cvmat\n";
    tensor = tensor.squeeze().detach().permute({1, 2, 0});
    tensor = tensor.mul(255).clamp(0, 255).to(torch::kU8);
    tensor = tensor.to(torch::kCPU);
    int64_t height = tensor.size(0);
    int64_t width = tensor.size(1);
    cv::Mat mat(width, height, CV_8UC3);
    std::memcpy((void *)mat.data, tensor.data_ptr(), sizeof(torch::kU8) * tensor.numel());
    return mat.clone();
}

torch::Tensor CVMatToTensor(cv::Mat mat)
{
    std::cout << "converting cvmat to tensor\n";
    cv::cvtColor(mat, mat, cv::COLOR_BGR2RGB);
    cv::Mat matFloat;
    mat.convertTo(matFloat, CV_32F, 1.0 / 255);
    auto size = matFloat.size();
    auto nChannels = matFloat.channels();
    auto tensor …
Run Code Online (Sandbox Code Playgroud)

c++ memory opencv pytorch

7
推荐指数
1
解决办法
2895
查看次数

Pytorch 中的缓冲区是什么?

我了解register_buffer 的作用以及register_buffer 和 register_parameters之间的区别。

但是 PyTorch 中缓冲区的准确定义是什么?

python pytorch

7
推荐指数
1
解决办法
2477
查看次数

Pytorch 中 [-1,0] 的维度范围是多少?

所以我很难理解一些关于 Pytorch 集合的术语。我不断遇到关于我的张量范围不正确的相同类型的错误,当我尝试谷歌寻找解决方案时,解释往往更加混乱。

下面是一个例子:

m = torch.nn.LogSoftmax(dim=1)
input = torch.tensor([0.3300, 0.3937, -0.3113, -0.2880])
output = m(input)
Run Code Online (Sandbox Code Playgroud)

我没有发现上面的代码有什么问题,我已经定义LogSoftmax了接受一维输入。所以根据我使用其他编程语言的经验,集合[0.3300, 0.3937, -0.3113, -0.2880]是一个单一的维度。

以上触发了以下错误m(input)

IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
Run Code Online (Sandbox Code Playgroud)

这意味着什么?

我传入了一个一维张量,但它告诉我它期望的范围是[-1, 0], but got 1.

  • 什么范围?
  • 为什么比较1to的维度会出现错误[-1, 0]
  • 这两个数字[-1, 0]是什么意思?

我搜索了这个错误的解释,我发现像这个链接这样的东西对我作为一个程序员来说毫无意义:

https://github.com/pytorch/pytorch/issues/5554#issuecomment-370456868

因此,我能够通过向张量数据添加另一个维度来修复上述代码。

IndexError: Dimension out of range (expected to be in range of …
Run Code Online (Sandbox Code Playgroud)

python softmax pytorch tensor

7
推荐指数
1
解决办法
2419
查看次数