python - 创建变压器无峰值掩码时如何修复 numpy 中的 "TypeError: data type not understood"

标签 python numpy deep-learning pytorch

我正在尝试通过博客文章实现和训练 NMT 变压器,一切正常,除了我无法创建无峰值掩模,因为我收到此错误:“TypeError:数据类型不理解”

代码:

target_seq = batch.Python.transpose(0,1)
target_pad = PY_TEXT.vocab.stoi['<pad>']
target_msk = (target_seq != target_pad).unsqueeze(1)
size = target_seq.size(1) # get seq_len for matrix
nopeak_mask = np.triu(np.ones(1, size, size),
k=1).astype('uint8')
nopeak_mask = Variable(torch.from_numpy(nopeak_mask) == 0)
target_msk = target_msk & nopeak_mask

错误消息:

TypeError                                 Traceback (most recent call last)
<ipython-input-36-e19167b74ba0> in <module>()
      4 target_msk = (target_seq != target_pad).unsqueeze(1)
      5 size = target_seq.size(1) # get seq_len for matrix
----> 6 nopeak_mask = np.triu(np.ones(1, size, size),
      7 k=1).astype('uint8')
      8 nopeak_mask = Variable(torch.from_numpy(nopeak_mask) == 0)

~/.local/lib/python3.6/site-packages/numpy/core/numeric.py in ones(shape, dtype, order)
    201 
    202     """
--> 203     a = empty(shape, dtype, order)
    204     multiarray.copyto(a, 1, casting='unsafe')
    205     return a

TypeError: data type not understood

最佳答案

np.triu 的第一个输入应该是所需大小的元组,而不是 numpy 数组。

尝试:

np.triu((1, size, size), k=1).astype("uint8")

关于python - 创建变压器无峰值掩码时如何修复 numpy 中的 "TypeError: data type not understood",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55694263/

相关文章:

python - pandas - 从一个子组中取出最后 N 行

python - pandas DataFrame 中 bool 数组的按行求和

python - np.expand_dims(X_val, -1) 执行什么操作?不明白-1的意义

swift - CoreML Vision 人脸检测的输入图像大小要求是多少

python - 一起使用 Vue.js 和 Flask

python - 在 keras 的预训练密集层之间添加 dropout 层

python - 内核 GridSearchCV 参数

java - 在Python中重写Java BigInteger函数

python - 在tensorflow中将一个2d张量动态划分为多个张量

python - tf.layers.conv2d和tf.contrib.slim.conv2d之间的区别