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

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

使用 索引切片 访问张量值。索引用于访问张量的单个元素的值,而切片用于访问一系列元素的值。

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

步骤

  • 导入所需库。这里,需要使用的库是 torch
  • 定义一个 PyTorch 张量。
  • 使用 索引 访问特定索引处的单个元素的值或使用 切片 访问元素序列的值。
  • 使用 赋值 运算符修改访问的值与新值。
  • 最后,打印张量以检查张量是否使用新值进行修改。

例子1

# Python program to access and modify values of a tensor in PyTorch
# Import the libraries
import torch

# Define PyTorch Tensor
a = torch.Tensor([[3, 5],[1, 2],[5, 7]])
print("a:\n",a)

# Access a value at index [1,0]-> 2nd row, 1st Col using indexing
b = a[1,0]
print("a[1,0]:\n", b)

# Other indexing method to access value
c = 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 value
a[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 libraries
import torch

# Define PyTorch Tensor
a = torch.Tensor([[3, 5],[1, 2],[5, 7]])
print("a:\n", a)

# Access all values of 2nd row using slicing
b = a[1]
print("a[1]:\n", a[1])

# Access all values of 1st and 2nd rows
b = a[0:2]
print("a[0:2]:\n" , a[0:2])

# Access all values of 2nd col
c = a[:,1]
print("a[:,1]:\n", a[:,1])

# Access values from first two rows but 2nd col
print("a[0:2, 1]:\n", a[0:2, 1])

# assignment operator is used to modify with new value
# Modifying the values of 2nd row
a[1] = torch.Tensor([9, 9])
print("After modifying a[1]:\n", a)

# Modify values of first two rows but 2nd col
a[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.]])

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程