python - 将张量附加到另一个张量的每个元素
问题描述
我有一个 pytorch 张量:x = torch.zeros(2, 2)
和另一个变量值张量:item = torch.tensor([[1, 2], [3, 4]])
,例如,我只是给出这个张量。
我想将张量添加item
为 x 张量的每个元素,这样
x = [[item, item],
[item, item]]
所以 x 是一个张量,里面有张量。我曾尝试item
直接分配给 x,但出现错误:RuntimeError: The expanded size of the tensor must match the existing size at non-singleton dimension
解决方案
使用torch.repeat()
,你的target_tensor
形状会torch.Size([2, 2, 2, 2])
。
item
张量形状已经torch.Size([2, 2])
利用 :
target_tensor = item.repeat(2, 2, 1, 1)
repeat() 函数的前两个参数是 x 的形状
推荐阅读
- java - 如何修复 Java appium 中的 DesiredCapabilities 错误?
- c# - 为什么 ReadFromEnumerable 方法不起作用?机器学习网络
- android - Android-Keyboard 随机显示 onResume
- assembly - MOV 从内存中注册不能在 nasm 中使用 BITS 32
- mongodb - 如何同时高效地将数据写入 NoSQL 和 RDBMS
- javascript - jQuery 代码没有运行 $(function(){...}); 但没有它会运行
- php - PHP POST 未填写
- php - 在 Woocommerce 客户处理和完成的电子邮件通知中更改文本
- java - Spring boot - 休眠配置问题(创建名称为“entityManagerFactory”的bean时出错)
- python - 通过遍历键列表并与另一个字典配对来使用键值对填充字典