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

📅  最后修改于: 2022-05-13 01:55:22.401000             🧑  作者: Mango

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

在本文中,我们将了解如何使用Python在 PyTorch 中访问和修改张量的值。

我们可以使用索引和切片来访问张量的值。索引用于访问张量中的单个值。切片用于访问张量中的值序列。我们可以使用赋值运算符来修改张量。在张量中分配一个新值将使用新值修改张量。

导入 Torch 库,然后创建一个 PyTorch 张量。访问张量的值。使用赋值运算符用新值修改值。

示例 1:使用索引访问和修改值。在下面的示例中,我们正在访问和修改张量的值。

Python
# Import torch libraries
import torch
 
# create PyTorch tensor
tens = torch.Tensor([1, 2, 3, 4, 5])
 
# print tensor
print("Original tensor:", tens)
 
# access a value by there index
temp = tens[2]
print("value of tens[2]:", temp)
 
 
# modify a value.
tens[2] = 10
 
# print tensor after modify the value
print("After modify the value:", tens)


Python
# Import torch libraries
import torch
 
# create PyTorch Tensor
tens = torch.Tensor([[1, 2, 3], [4, 5, 6]])
 
# Print the tensor
print("Original tensor: ", tens)
 
 
# Access all values of only second row
# using slicing
a = tens[1]
print("values of only second row: ", a)
 
# Access all values of only third column
b = tens[:, 2]
print("values of only third column: ", b)
 
# Access values of second row and first
# two column
c = tens[1, 0:2]
print("values of second row and first two column: ", c)
 
# Modifying all the values of second row
tens[1] = torch.Tensor([40, 50, 60])
print("After modifying second row:  ", tens)
 
# Modify values of first rows and last
# two column
tens[0, 1:3] = torch.Tensor([20, 30])
print("After modifying first rows and last two column ", tens)


输出:

示例 2:使用切片访问和修改张量中的值序列。

Python

# Import torch libraries
import torch
 
# create PyTorch Tensor
tens = torch.Tensor([[1, 2, 3], [4, 5, 6]])
 
# Print the tensor
print("Original tensor: ", tens)
 
 
# Access all values of only second row
# using slicing
a = tens[1]
print("values of only second row: ", a)
 
# Access all values of only third column
b = tens[:, 2]
print("values of only third column: ", b)
 
# Access values of second row and first
# two column
c = tens[1, 0:2]
print("values of second row and first two column: ", c)
 
# Modifying all the values of second row
tens[1] = torch.Tensor([40, 50, 60])
print("After modifying second row:  ", tens)
 
# Modify values of first rows and last
# two column
tens[0, 1:3] = torch.Tensor([20, 30])
print("After modifying first rows and last two column ", tens)

输出: