deep learning project3 语法、用法总结(pytorch)

  1. 多元素比较用.all()或者.any()。例如:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 2, 4])
if a == b:
    print('Yes!')
else:
    print('No!')

报错:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()。
应该写成如下方式:

import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 2, 4])
if (a == b).all():
    print('Yes!')
else:
    print('No!')

见link.

  1. 不能将多个tensor合并成np.array
a = torch.Tensor([1, 2])
b = torch.Tensor([3, 4])
c = np.array([a, b])

报错:ValueError: only one element tensors can be converted to Python scalars
应写成如下方式:

a = torch.Tensor([1, 2])
b = torch.Tensor([3, 4])
a, b = np.array(a), np.array(b)
c = np.array([a, b])
  1. nn.Embedding(vocabulary_size, vector_size)中,被embedding的单词数量必须不超过vocabulary size。
encoder = nn.Embedding(2, 5)
words = torch.LongTensor([1, 2, 3])
embedded = encoder(words)

报错:RuntimeError: index out of range at c:\programdata\miniconda3\conda-bld\pytorch-cpu_1532498166916\work\aten\src\th\generic/THTensorMath.cpp:352
应写成如下方式:embedding

encoder = nn.Embedding(10, 5)  # 10 can be any number larger than 2
words = torch.LongTensor([1, 2, 3])
embedded = encoder(words)
  1. 跨多个维度使用.view()时,要加上.contiguous(),见link的第五条。

你可能感兴趣的:(python)