07_创建tensor,从numpy创建,从List创建,设置默认类型,rand/rand_like,randint,full,arange,linspace/logspace,linspace等等
1.7.創(chuàng)建Tensor
1.7.1.Import from numpy
1.7.2.Import from List
1.7.3.set default type
1.7.4.rand/rand_like,randint
1.7.5.full()
1.7.6.arange()
1.7.7.linspace/logspace
1.7.7.1.torch.linspace()
1.7.7.2.torch.logspace()
1.7.8.ones/zeros/eye
1.7.8.1.ones
1.7.8.2.zeros
1.7.8.3.eye
1.7.9.torch.randperm()
1.7.10.sin
1.7.11.Sinh
1.7.12.Cosh
1.7.13.Tanh
1.7.14.cons
1.7.15.Tan
1.7.16.Asin
1.7.17.acos
1.7.18.atan
1.7.創(chuàng)建Tensor
1.7.1.Import from numpy
從numpy引入數(shù)據(jù)
# -*- coding: UTF-8 -*-import numpy as np import torcha = np.array([2, 3.3]) print(torch.from_numpy(a)) """ tensor([2.0000, 3.3000], dtype=torch.float64) """a = np.ones([2, 3]) print(torch.from_numpy(a)) """ tensor([[1., 1., 1.],[1., 1., 1.]], dtype=torch.float64) """1.7.2.Import from List
隨機生成pytorch的數(shù)據(jù)。
import torchprint(torch.empty(1)) """ tensor([-24217520.]) """print(torch.Tensor(2, 3)) """ tensor([[0., 0., 0.],[0., 0., 0.]]) """print(torch.IntTensor(2, 3)) """ tensor([[0, 0, 0],[0, 0, 0]], dtype=torch.int32) """print(torch.FloatTensor(2, 3)) """ tensor([[0., 0., 0.],[0., 0., 0.]]) """1.7.3.set default type
設(shè)置pytorch的默認類型
import torch# torch中的默認類型是torch.FloatTensor類型 print(torch.tensor([1.2, 3]).type()) """ torch.FloatTensor """# 將torch的默認值設(shè)置成torch.DoubleTensor torch.set_default_tensor_type(torch.DoubleTensor) print(torch.tensor([1.2, 3]).type()) """ torch.DoubleTensor """1.7.4.rand/rand_like,randint
torch.rand和torch.randn有什么區(qū)別?
一個是均勻分布,一個是標(biāo)準正態(tài)分布。
torch.rand()
均勻分布
torch.rand(*sizes, out=None)–>Tensor
返回一個張量,包含了從區(qū)間[0, 1)的均勻分布中抽取的一組隨機數(shù)。張量的形狀由參數(shù)sizes定義。
參數(shù):
?sizes(int…) - 整數(shù)序列,定義了輸出張量的形狀
?out(Tensor,optinal) - 結(jié)果張量
*randn(size, out=None, dtype=None)和randn_like(input, dtype=None)
標(biāo)準正態(tài)分布
torch.randn(*sizes, out=None)–>Tensor
返回一個張量,包含了從標(biāo)準正態(tài)分布(均值為0,方差1,即高斯白噪聲)中抽取的一組隨機數(shù)。張量的形狀由參數(shù)sizes定義。
參數(shù):
?sizes(int…) - 整數(shù)序列,定義了輸出張量的形狀
?out(Tensor, optinal) - 結(jié)果張量
torch.randint(), torch.randint_like()
import torch# randint(low=0, high, size, out=None, dtype=None) # randint_like(input, low=0, high, dtype=None) # 整數(shù)范圍[low, high] t1 = torch.randint(1,4,(2,3,2)) # 形狀寫入[2, 3, 2]也行 t2 = torch.randint_like(t1, 4) print(t1) """ tensor([[[2, 2],[3, 1],[3, 2]],[[1, 1],[1, 3],[2, 2]]]) """print(t2) """ tensor([[[2, 3],[1, 2],[0, 2]],[[3, 1],[1, 1],[0, 2]]]) """1.7.5.full()
PyTorch是由Facebook開發(fā)的開源機器學(xué)習(xí)庫。它用于深度神經(jīng)網(wǎng)絡(luò)和自然語言處理。
功能torch.full()返回一個大小為fill_value的張量的張量。
用法:torch.ones(size, fill_value, out=None)
參數(shù):
size: 定義輸出張量形狀的整數(shù)序列。
fill_value:用于填充輸出張量的數(shù)字。
out(Tensor, optional) : 輸出張量
返回類型:張量
輸出結(jié)果:
a = tensor([[3, 3, 3, 3],[3, 3, 3, 3],[3, 3, 3, 3]]) b = tensor([[3.5000, 3.5000, 3.5000, 3.5000, 3.5000],[3.5000, 3.5000, 3.5000, 3.5000, 3.5000]])1.7.6.arange()
功能torch.arange()返回大小的一維張量(end - start)/ step,從間隔的值[start , end]從開始就采取共同的差異步驟。
用法:torch.arange(start=0, end, step=1, out=None)
參數(shù):
start: 點集的起始值。默認值:0
end : 點集的最終值
step : 每對相鄰點之間的間隙。默認值:1
out(Tensor, optional) : 輸出張量
返回類型:張量
代碼1:
1.7.7.linspace/logspace
1.7.7.1.torch.linspace()
torch.linespace()返回一維步長張量,該步張量在起點和終點之間等距。
輸出張量是尺寸步長的一維。
用法:torch.linspace(start, end, steps=100, out=None)
參數(shù):
start: 點集的起始值。
end : 點集的最終值。
steps : 每對相鄰點之間的間隙。默認值:100
out(Tensor, optional): 輸出張量
返回類型:張量
代碼1:
代碼2:可視化
# -*- coding: UTF-8 -*-import torch import numpy as np 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])1.7.7.2.torch.logspace()
功能torch.logspace()返回一階步張量的一維張量,與之間的底數(shù)成對數(shù)間隔
輸出張量是尺寸步長的一維。
用法:torch.logspace(start, end, steps=100, base=10, out=None)
參數(shù):
start: 點集的起始值
end: 點集的最終值
steps: 在開始和結(jié)束之間要采樣的點數(shù)。默認值:100
base:對數(shù)函數(shù)的基數(shù)。默認值:10.0
out(Tensor, optional) : 輸出張量
返回類型:張量
代碼1:
輸出結(jié)果:
a = tensor([1.0000e+03, 5.6234e+04, 3.1623e+06, 1.7783e+08, 1.0000e+10]) """b = torch.logspace(start=-10, end=10, steps=5) print("b = ", b) """輸出結(jié)果:
b = tensor([1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10])
“”"
代碼2:可視化
# -*- coding: UTF-8 -*-import torch import numpy as np import matplotlib.pyplot as plt# Applying the logspace function to get a tensor of size 15 with values from -5 to 5 using base 2 a = torch.logspace(-5, 5, 15, 2) 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([3.1250e-02, 5.1271e-02, 8.4119e-02, 1.3801e-01, 2.2643e-01, 3.7150e-01,6.0951e-01, 1.0000e+00, 1.6407e+00, 2.6918e+00, 4.4164e+00, 7.2458e+00,1.1888e+01, 1.9504e+01, 3.2000e+01])1.7.8.ones/zeros/eye
1.7.8.1.ones
torch.eye()返回a返回大小為n * m的2-D張量,對角線為1,其他位置為零。
用法:torch.eye(n, m, out=None)
參數(shù):
n : 行數(shù)
m : 列數(shù)。默認值-n
out(Tensor, optional) : 輸出張量
返回類型:二維張量
代碼1:
輸出:
a = tensor([[1., 0., 0., 0.],[0., 1., 0., 0.],[0., 0., 1., 0.]]) b = tensor([[1., 0., 0.],[0., 1., 0.],[0., 0., 1.]]) c = tensor([[1.],[0.],[0.],[0.],[0.]])1.7.8.2.zeros
torch.zeros()返回一個由標(biāo)量值0填充的張量,其形狀由變量參數(shù)size定義。
用法:torch.zeros(size, out=None)
參數(shù):
size: 定義輸出張量形狀的整數(shù)序列
out(Tensor, optional): 輸出張量
返回類型:一個張量,其標(biāo)量值為0,形狀與尺寸相同。
輸出結(jié)果:
a = tensor([[0., 0., 0., 0.],[0., 0., 0., 0.],[0., 0., 0., 0.]]) b = tensor([[0., 0., 0., 0., 0.]]) c = tensor([[0.],[0.],[0.],[0.],[0.]]) d = tensor([[[0., 0.],[0., 0.],[0., 0.]],[[0., 0.],[0., 0.],[0., 0.]],[[0., 0.],[0., 0.],[0., 0.]]])1.7.8.3.eye
torch.eye()返回a返回大小為n * m的2-D張量,對角線為1,其他位置為零。
用法:torch.eye(n, m, out=None)
參數(shù):
n : 行數(shù)
m : 行列。默認值-n
out (Tensor, optional):輸出張量
返回類型:二維張量
代碼1:
輸出:
a = tensor([[1., 0., 0., 0.],[0., 1., 0., 0.],[0., 0., 1., 0.]]) b = tensor([[1., 0., 0.],[0., 1., 0.],[0., 0., 1.]]) c = tensor([[1.],[0.],[0.],[0.],[0.]])1.7.9.torch.randperm()
randperm(n, out=None, dtype=torch.int64)–>LongTensor
# torch中沒有random.shuffle # y = torch.randperm(n) y是把1到n這些數(shù)隨機打亂得到的一個數(shù)字序列 import torch# randperm(n, out=None, dtype=torch.int64) -->LongTensor idx = torch.randperm(3) a = torch.Tensor(4, 2) print(a) print(idx, idx.type()) print(a[idx])輸出結(jié)果:
tensor([[0., 0.],[0., 0.],[0., 0.],[0., 0.]]) tensor([2, 0, 1]) torch.LongTensor tensor([[0., 0.],[0., 0.],[0., 0.]])1.7.10.sin
torch.sin()提供對PyTorch中正弦函數(shù)的支持。它期望輸入為弧度形式,并輸出范圍為[-1, 1]
輸入類型為張量,如果輸入包含多個元素,則將按元素計算正弦。
用法:torch.sin(x,out=None)
參數(shù):
X: 輸入張量
name(可選) : 輸出張量
返回類型:與X具有相同類型的張量。
代碼1:
輸出:
tensor([ 1.0000, -0.5000, 3.4000, -2.1000, 0.0000, -6.5000]) tensor([ 0.8415, -0.4794, -0.2555, -0.8632, 0.0000, -0.2151])代碼2:可視化
# -*- coding: UTF-8 -*-import torch import numpy as np import matplotlib.pyplot as plt# A vector of size 15 with values from -5 to 5 a = np.linspace(-5, 5, 15)# Applying the sine function and storing the result in 'b' b = torch.sin(torch.FloatTensor(a)) print(b)# Plotting plt.plot(a, b.numpy(), color='red', marker="o") plt.title("torch.sin") plt.xlabel("X") plt.ylabel("Y")plt.show()輸出結(jié)果:
tensor([ 0.9589, 0.9103, 0.4167, -0.2806, -0.8408, -0.9899, -0.6551, 0.0000,0.6551, 0.9899, 0.8408, 0.2806, -0.4167, -0.9103, -0.9589])1.7.11.Sinh
torch.sinh()為PyTorch中的雙曲正弦函數(shù)提供支持。它期望以弧度形式輸入。輸入類型為張量,如果輸入包含多個元素,則將計算按元素的雙曲正弦值。
用法:torch.sinh(x, out=None)
參數(shù):
X:輸入張量
name(可選):輸出張量
返回類型:與x具有相同類型的張量
代碼1:
輸出結(jié)果:
tensor([ 1.0000, -0.5000, 3.4000, -2.1000, 0.0000, -6.5000]) tensor([ 1.1752, -0.5211, 14.9654, -4.0219, 0.0000, -332.5701])代碼2:可視化
# -*- coding: UTF-8 -*-import torch import numpy as np import matplotlib.pyplot as plt# A vector of size 15 with values from -5 to 5 a = np.linspace(-5, 5, 15) print(a)# Applying the hyperbolic sine function and storing the result in 'b' b = torch.sinh(torch.FloatTensor(a)) print(b)# Plotting plt.plot(a, b.numpy(), color = 'red', marker = "o") plt.title("torch.sinh") plt.xlabel("X") plt.ylabel("Y")plt.show()輸出結(jié)果:
[-5. -4.28571429 -3.57142857 -2.85714286 -2.14285714 -1.42857143-0.71428571 0. 0.71428571 1.42857143 2.14285714 2.857142863.57142857 4.28571429 5. ] tensor([-74.2032, -36.3203, -17.7696, -8.6771, -4.2032, -1.9665, -0.7766,0.0000, 0.7766, 1.9665, 4.2032, 8.6771, 17.7696, 36.3203,74.2032])1.7.12.Cosh
torch.cosh()為PyTorch中的雙曲余弦功能提供支持。它期望以弧度形式輸入。輸入類型為張量,如果輸入包含多個元素,則將計算按元素的雙曲余弦值。
用法:torch.cosh(x, out=None)
參數(shù):
X: 輸入張量。
name(可選):輸出張量。
返回類型:與X具有相同類型的張量。
代碼1:
輸出結(jié)果:
tensor([ 1.0000, -0.5000, 3.4000, -2.1000, 0.0000, -6.5000]) tensor([ 1.5431, 1.1276, 14.9987, 4.1443, 1.0000, 332.5716])代碼2:可視化
# Importing the PyTorch library import torch# Importing the NumPy library import numpy as np# Importing the matplotlib.pylot function import matplotlib.pyplot as plt# A vector of size 15 with values from -1 to 1 a = np.linspace(-1, 1, 15)# Applying the hyperbolic cosine function and storing the result in 'b' b = torch.cosh(torch.FloatTensor(a))print(b)# Plotting plt.plot(a, b.numpy(), color='red', marker="o") plt.title("torch.cosh") plt.xlabel("X") plt.ylabel("Y")plt.show()1.7.13.Tanh
許多激活函數(shù)之一是雙曲正切函數(shù)(也稱為tanh),其定義為:
雙曲正切函數(shù)的輸出范圍為(-1,1),因此將強負輸入映射為負值。與sigmoid函數(shù)不同,僅將接近零的值映射到接近零的輸出,這在某種程度上解決了"vanishing gradients"問題。雙曲正切函數(shù)在每個點都是微分的,其導(dǎo)數(shù)為:
由于表達式包含tanh函數(shù),因此可以重用其值以使向后傳播更快。
盡管與S形函數(shù)相比,網(wǎng)絡(luò)獲得”stuck”的機會較低,但是雙曲正切函數(shù)仍然受到”vanishing gradients”的影響。整流線性單元(ReLU)可用于克服此問題。
功能torch.tanh()為PyTorch中的雙曲正切函數(shù)提供支持。它期望輸入為弧度形式,并且輸出在[-∞,∞]范圍內(nèi)。輸入類型為張量,如果輸入包含多個元素,則將計算按元素的雙曲正切值。
用法:torch.tanh(x, out=None)
參數(shù):
X: 輸出張量
name(可選):輸出張量
返回類型:與X具有相同類型的張量。
代碼1:
輸出:
tensor([ 1.0000, -0.5000, 3.4000, -2.1000, 0.0000, -6.5000]) tensor([ 0.7616, -0.4621, 0.9978, -0.9705, 0.0000, -1.0000])代碼2:可視化
# Importing the PyTorch library import torch import numpy as np import matplotlib.pyplot as plt# A vector of size 15 with values from -5 to 5 a = np.linspace(-5, 5, 15)# Applying the hyperbolic tangent function and storing the result in 'b' b = torch.tanh(torch.FloatTensor(a)) print(b)# Plotting plt.plot(a, b.numpy(), color='red', marker='o') plt.title("torch.tanh") plt.xlabel("X") plt.ylabel("Y")plt.show()輸出結(jié)果:
tensor([-0.9999, -0.9996, -0.9984, -0.9934, -0.9728, -0.8914, -0.6134, 0.0000,0.6134, 0.8914, 0.9728, 0.9934, 0.9984, 0.9996, 0.9999])1.7.14.cons
torch.cos()為PyTorch中的余弦函數(shù)提供支持。它期望輸入為弧度形式,并且輸出范圍為[-1, 1]。
輸入類型為張量,如果輸入包含多個元素,則將計算按元素的余弦值。
用法:torch.cos(x, out=None)
參數(shù):
X: 輸入張量
name(可選):輸出張量
返回類型:與x具有相同類型的張量。
代碼1:
輸出:
tensor([ 1.0000, -0.5000, 3.4000, -2.1000, 0.0000, -6.5000]) tensor([ 0.5403, 0.8776, -0.9668, -0.5048, 1.0000, 0.9766])代碼2:可視化
# Importing the PyTorch library import torch import numpy as np import matplotlib.pyplot as plt a = np.linspace(-5, 5, 15)# Applying the consine function and storing the result in 'b' b = torch.cos(torch.FloatTensor(a)) print(b)# Plotting plt.plot(a, b.numpy(), color='red', marker="o") plt.title("torch.cos") plt.xlabel("X") plt.ylabel("Y")plt.show()輸出:
tensor([ 0.2837, -0.4138, -0.9090, -0.9598, -0.5414, 0.1417, 0.7556, 1.0000,0.7556, 0.1417, -0.5414, -0.9598, -0.9090, -0.4138, 0.2837])1.7.15.Tan
功能torch.tan()提供對PyTorch中切線功能的支持。它期望輸入為弧度形式,并且輸出在[-∞,∞]范圍內(nèi)。輸入類型為張量,如果輸入包含多個元素,則將計算按元素的切線。
用法:torch.tan(x, out=None)
參數(shù):
X: 輸入張量
name(可選):輸出張量
返回類型:與X具有相同類型的張量。
代碼1:
輸出:
tensor([ 1.0000, -0.5000, 3.4000, -2.1000, 0.0000, -6.5000]) tensor([ 1.5574, -0.5463, 0.2643, 1.7098, 0.0000, -0.2203])代碼2:可視化
# Importing the PyTorch libraryimport torch import numpy as np import matplotlib.pyplot as plt# A vector of size 15 with values from -1 to 1 a = np.linspace(-1, 1, 15)# Applying the tangent function and storing the result in 'b' b = torch.tan(torch.FloatTensor(a))print(b)# Plotting plt.plot(a, b.numpy(), color='red', marker='o') plt.title("torch.tanh") plt.xlabel("X") plt.ylabel("Y")plt.show()輸出:
tensor([-1.5574, -1.1549, -0.8670, -0.6430, -0.4569, -0.2938, -0.1438, 0.0000,0.1438, 0.2938, 0.4569, 0.6430, 0.8670, 1.1549, 1.5574])1.7.16.Asin
torch.asin()為PyTorch中的反正弦函數(shù)提供支持。它期望輸入在[-1,1]范圍內(nèi),并以弧度形式給出輸出。如果輸入不在[-1,1]范圍內(nèi),則返回nan。輸入類型為張量,如果輸入包含多個元素,則將計算按元素的反正弦值。
用法:torch.asin(x, out=None)
參數(shù):
X: 輸入張量
name(可選):輸出張量
返回類型:與x具有相同類型的張量。
代碼1:
輸出:
tensor([ 1.0000, -0.5000, 3.4000, 0.2000, 0.0000, -2.0000]) tensor([ 1.5708, -0.5236, nan, 0.2014, 0.0000, nan])代碼2:可視化
# Importing the PyTorch library import torch# Importing the NumPy library import numpy as np# Importing the matplotlib.pylot function import matplotlib.pyplot as plt# A vector of size 15 with values from -1 to 1 a = np.linspace(-1, 1, 15)# Applying the inverse sine function and # storing the result in 'b' b = torch.asin(torch.FloatTensor(a))print(b)# Plotting plt.plot(a, b.numpy(), color='red', marker="o") plt.title("torch.asin") plt.xlabel("X") plt.ylabel("Y")plt.show()輸出結(jié)果:
tensor([-1.5708, -1.0297, -0.7956, -0.6082, -0.4429, -0.2898, -0.1433, 0.0000,0.1433, 0.2898, 0.4429, 0.6082, 0.7956, 1.0297, 1.5708])1.7.17.acos
torch.acos()為PyTorch中的反余弦函數(shù)提供支持。它期望輸入在[-1,1]范圍內(nèi),并以弧度形式給出輸出。如果輸入不在[-1,1]范圍內(nèi),則返回nan。輸入類型為張量,如果輸入包含多個元素,則將計算按元素的反余弦值。
用法:torch.acos(x, out=None)
參數(shù):
返回類型:與X具有相同類型的張量。
代碼1:
輸出結(jié)果:
tensor([3.1416, 2.6005, 2.3664, 2.1790, 2.0137, 1.8605, 1.7141, 1.5708, 1.4274,1.2810, 1.1279, 0.9626, 0.7752, 0.5411, 0.0000])1.7.18.atan
torch.atan()為PyTorch中的反正切函數(shù)提供支持。它以弧度形式給出輸出。輸入類型為張量,如果輸入包含多個元素,則將計算按元素的反正切
參數(shù):
X: 輸入張量
name(可選):輸出張量
返回類型:與x具有相同類型的張量。
代碼1:
輸出:
tensor([ 1.0000, -0.5000, 3.4000, 0.2000, 0.0000, -2.0000]) tensor([ 0.7854, -0.4636, 1.2847, 0.1974, 0.0000, -1.1071])代碼2:可視化
# Importing the PyTorch library import torch# Importing the NumPy library import numpy as np# Importing the matplotlib.pylot function import matplotlib.pyplot as plt# A vector of size 15 with values from -5 to 5 a = np.linspace(-5, 5, 15)# Applying the inverse tangent function and # storing the result in 'b' b = torch.atan(torch.FloatTensor(a))print(b)# Plotting plt.plot(a, b.numpy(), color='red', marker="o") plt.title("torch.atan") plt.xlabel("X") plt.ylabel("Y")plt.show()輸出結(jié)果:
tensor([-1.3734, -1.3416, -1.2978, -1.2341, -1.1342, -0.9601, -0.6202, 0.0000,0.6202, 0.9601, 1.1342, 1.2341, 1.2978, 1.3416, 1.3734]) 與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的07_创建tensor,从numpy创建,从List创建,设置默认类型,rand/rand_like,randint,full,arange,linspace/logspace,linspace等等的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 湖南耒阳市女子征兵有多少名额?
- 下一篇: 陆军第74军湘西会战阵亡将士纪念塔位于哪