PyTorch基础-Tensor的属性,数据,运算-01
生活随笔
收集整理的這篇文章主要介紹了
PyTorch基础-Tensor的属性,数据,运算-01
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Tensor的屬性
import torch a = torch.tensor([1,2,3],dtype=int) # 創建一個整數tensor print(a) print(a.dtype) b = torch.tensor([1,2,3],dtype=float)# 創建一個浮點數tensor print(b) print(b.dtype) c = torch.tensor([[1,2,3],[4,5,6]])# # 創建一個二維tensor print(c) print(c.ndim)# 數據維度 print(c.shape) # 數據形狀 print(c.dtype) # 數據類型Tensor的數據創建
import torch torch.ones(2,3) # 創建一個2行3列全為1的數據 torch.zeros(3,3) # 創建一個3行3列全為0的數據 torch.rand(3,4)# 生成一個3行4列的隨機數(0-1之間) torch.randint(0,10,(2,3))# 生成一個0-10之間的2行3列的整數 torch.randn(3,4) # 生成一個3行4列正態分布的隨機數 a = torch.tensor([[1,2],[3,4],[5,6]]) a b = torch.randn_like(a,dtype=float)# 生成一個和a形狀一樣的隨機數數據類型float b # 查看數據形狀 print(b.shape) print(b.size()) # 修改數據形狀 view相當于reshape c = b.view(6) # 把b修改成1維的 c d = b.view(2,3) # 修改成2行3列 d d1 = b.reshape(6) d1 d1[1]# 切片 d1[1].item() # 標準數值 item只能修改一個值為標準數值 import numpy as np np.array(d1) # 把tensor變成array類型 array = np.array([1,2,3]) tensor = torch.tensor(array) # 把array變成tensor類型 tensor基本運算操作
import torch a = torch.randint(1,5,(2,3)) # 隨機生成2行3列1-5的數值 b = torch.randint(1,5,(2,3)) print(a) print(b) a+b # 矩陣相加 torch.add(a,b) # 矩陣相加 result = torch.zeros(2,3) # 生成一個2行3列全為0的矩陣 result torch.add(a,b,out=result) # a+b 的結果(out=result)輸出到 result中 result # a = a+b # 注意任何使用張量tensor會發生變化的操作都有一個前綴"_",列入a.add_()加法,b.sub_()減法 a.add_(b) a-b a.sub_(b) a,b a*b a/b # 取余除 a%b # 取整除 a//b
矩陣相乘
數據的索引
import torch tensor = torch.arange(2,14) # 生成2-14的數據arange取左不取右 print(tensor) # 列表索引從左開始就是0 ,1,2,3 從右開始就是-1,-2,-3 print(tensor[2]) # 切片第2個數值 print(tensor[-2])# 切片倒數第2個數值 print(tensor[1:4]) # 切片 第一個到第四個 print(tensor[2:-1]) print(tensor[:5]) print(tensor[:-3]) index = [1,3,4,5,5] tensor[index] for t in tensor:print(t)
自動求導
import torch x = torch.ones((2,2),requires_grad=True) # requires_grad=True 自動梯度機制開始記錄追蹤這個張量tensor x y = x + 2 y z = y*y*3 z out = z.mean()# 求z的平均值 out out.backward() # backward 計算梯度的值 print(x.grad) 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的PyTorch基础-Tensor的属性,数据,运算-01的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OpenCV-图像特征harris角点检
- 下一篇: PyTorch基础-线性回归以及非线性回