阅读 540

如何在 PyTorch 中访问和修改张量的值?

我们使用索引切片来访问张量的值。索引用于访问张量的单个元素的值,而切片用于访问元素序列的值。

我们使用赋值运算符来修改张量的值。使用赋值运算符分配新值/秒将使用新值/秒修改张量。

脚步

  • 导入所需的库。在这里,所需的库是torch

  • 定义PyTorch张量。

  • 使用索引访问特定索引处的单个元素的值或使用slicing访问元素序列的值。

  • 使用赋值运算符用新值修改访问的值。

  • 最后,打印张量以检查是否使用新值修改了张量。

示例 1


# Python program to access and modify values of a tensor in PyTorch# Import the librariesimport torch# Define PyTorch Tensora = torch.Tensor([[3, 5],[1, 2],[5, 7]])
print("a:\n",a)# Access a value at index [1,0]-> 2nd row, 1st Col using indexingb = a[1,0]
print("a[1,0]:\n", b)# Other indexing method to access valuec = a[1][0]
print("a[1][0]:\n",c)# Modifying the value 1 with new value 9# assignment operator is used to modify with new valuea[1,0] = 9
print("tensor 'a' after modifying value at a[1,0]:")
print("a:\n",a)

输出结果

a:
tensor([[3., 5.],
         [1., 2.],
         [5., 7.]])
a[1,0]:
   tensor(1.)
a[1][0]:
   tensor(1.)
tensor 'a' after modifying value at a[1,0]:
a:
tensor([[3., 5.],
         [9., 2.],
         [5., 7.]])


示例 2


# Python program to access and modify values of a tensor in PyTorch# Import necessary librariesimport torch# Define PyTorch Tensora = torch.Tensor([[3, 5],[1, 2],[5, 7]])print("a:\n", a)# Access all values of 2nd row using slicingb = a[1]print("a[1]:\n", a[1])# Access all values of 1st and 2nd rowsb = a[0:2]print("a[0:2]:\n" , a[0:2])# Access all values of 2nd colc = a[:,1]print("a[:,1]:\n", a[:,1])# Access values from first two rows but 2nd colprint("a[0:2, 1]:\n", a[0:2, 1])# assignment operator is used to modify with new value# Modifying the values of 2nd rowa[1] = torch.Tensor([9, 9])
print("After modifying a[1]:\n", a)# Modify values of first two rows but 2nd cola[0:2, 1] = torch.Tensor([4, 4])print("After modifying a[0:2, 1]:\n", a)

输出结果

a:tensor([[3., 5.],
         [1., 2.],
         [5., 7.]])a[1]:
   tensor([1., 2.])a[0:2]:
   tensor([[3., 5.],
         [1., 2.]])a[:,1]:
   tensor([5., 2., 7.])a[0:2, 1]:
   tensor([5., 2.])After modifying a[1]:
   tensor([[3., 5.],
            [9., 9.],
            [5., 7.]])After modifying a[0:2, 1]:tensor([[3., 4.],
         [9., 4.],
         [5., 7.]])


文章分类
百科问答
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐