📜  Python Pytorch linspace() 方法

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

Python Pytorch linspace() 方法

PyTorch 是 Facebook 开发的开源机器学习库。它用于深度神经网络和自然语言处理目的。

函数torch.linspace()返回起点和终点之间等距点的一维张量。

输出张量是一维尺寸步长。

代码#1:

Python3
# Importing the PyTorch library
import torch
  
# Applying the linspace function and
# storing the resulting tensor in 't'
a = torch.linspace(3, 10, 5)
print("a = ", a)
  
b = torch.linspace(start =-10, end = 10, steps = 5)
print("b = ", b)


Python3
# Importing the PyTorch library
import torch
# Importing the NumPy library
import numpy as np
  
# Importing the matplotlib.pyplot function
import matplotlib.pyplot as plt
  
# Applying the linspace function to get a tensor of size 15 with values from -5 to 5
a = torch.linspace(-5, 5, 15)
print(a)
  
# Plotting
plt.plot(a.numpy(), np.zeros(a.numpy().shape), color = 'red', marker = "o") 
plt.title("torch.linspace") 
plt.xlabel("X") 
plt.ylabel("Y") 
  
plt.show()


输出:

a =  tensor([ 3.0000,  4.7500,  6.5000,  8.2500, 10.0000])
b =  tensor([-10.,  -5.,   0.,   5.,  10.])

代码 #2:可视化

Python3

# Importing the PyTorch library
import torch
# Importing the NumPy library
import numpy as np
  
# Importing the matplotlib.pyplot function
import matplotlib.pyplot as plt
  
# Applying the linspace function to get a tensor of size 15 with values from -5 to 5
a = torch.linspace(-5, 5, 15)
print(a)
  
# Plotting
plt.plot(a.numpy(), np.zeros(a.numpy().shape), color = 'red', marker = "o") 
plt.title("torch.linspace") 
plt.xlabel("X") 
plt.ylabel("Y") 
  
plt.show()

输出:

tensor([-5.0000, -4.2857, -3.5714, -2.8571, -2.1429, -1.4286, -0.7143,  0.0000,
         0.7143,  1.4286,  2.1429,  2.8571,  3.5714,  4.2857,  5.0000])

[torch.FloatTensor of size 15]