當(dāng)前位置:
首頁(yè) >
pytorch基础一:张量
發(fā)布時(shí)間:2024/7/5
39
豆豆
生活随笔
收集整理的這篇文章主要介紹了
pytorch基础一:张量
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
簡(jiǎn)單記錄以便查閱
張量
一、創(chuàng)建張量
x = torch.empty(5,3) # 創(chuàng)建未初始化矩陣張量 x = torch.rand(5,3) # 創(chuàng)建初始化隨機(jī)矩陣張量 x = torch.zeros(5,3,dtype=torch.long) # 創(chuàng)建0填充矩陣張量 x = torch.tensor([5.5,3]) # 使用現(xiàn)有數(shù)據(jù)初始化張量 x = x.new_ones(5,3, dtype=torch.double) # 使用new_*來(lái)創(chuàng)建對(duì)象 x = torch.randn_like(x, dtype=torch.float) # 根據(jù)現(xiàn)有張量創(chuàng)建張量torch.arange(start, end, step=1, dtype=torch.int32) torch.full(size, fill_value) # 張量填充 torch.normal(mean, std, out=None) # 正態(tài)分布二、張量尺寸
x.size() x.shape三、張量維度
x = torch.squeeze(x) # 去掉大小為1的維度 x = torch.unsqueeze(x,3) # 在第三維增加1個(gè)維度 x = torch.transpose(x, 1, 2) # 交換維度1和維度2 x = torch.permute(1,2,3,0) # 交換多個(gè)維度/維度重組四、張量操作
x + y / torch.add(x, y) / y.add_(x) # 四則運(yùn)算 x[:, 1] # 切片操作 x = x.view(-1, 8) # 改變維度(-1維度自動(dòng)推斷) x = x.reshape(8,-1) # 改變維度 x.item() # 取張量的數(shù)值(前提:張量只有一個(gè)元素) torch.cat((x,y), dim=0) # 張量拼接(在原有的某一維度上進(jìn)行連接) torch.stack((x,y), dim=0) # 張量拼接(創(chuàng)建一個(gè)新的維度,將原有維度在這個(gè)維度上進(jìn)行順序排列)[詳細(xì)](https://blog.csdn.net/TH_NUM/article/details/83088915) torch.chunk(a, chunk_num, dim=0) # 張量拆分(在指定維度上將a變成chunk_num個(gè)大小相等的chunk,返回一個(gè)tuple。如果最后一個(gè)不夠chunk_num,就返回剩下的) torch.split(a, chunk_size, dim=0) # 張量拆分(同上)五、張量類型轉(zhuǎn)換
1.Torch Tensor與NumPy數(shù)組共享底層內(nèi)存地址 b = a.numpy() # tensor 轉(zhuǎn) numpy b = torch.from_numpy(a) # numpy 轉(zhuǎn) tensorb = a.long() # torch.int64 c = a.half() # torch.float16 d = a.int() # torch.int32 e = a.double() # torch.float64 f = a.float() # torch.float32 g = a.char() # torch.int8 h = a.byte() # torch.uint8 j = a.short() # torch.int16 c = a.type_as(c) # 轉(zhuǎn)化 a 的數(shù)據(jù)格式與 c 相同六、CUDA 張量
# is_available 函數(shù)判斷是否有cuda可以使用 # ``torch.device``將張量移動(dòng)到指定的設(shè)備中 if torch.cuda.is_available():device = torch.device("cuda") # a CUDA 設(shè)備對(duì)象y = torch.ones_like(x, device=device) # 直接從GPU創(chuàng)建張量x = x.to(device) # 或者直接使用``.to("cuda")``將張量移動(dòng)到cuda中z = x + yprint(z)print(z.to("cpu", torch.double)) # ``.to`` 也會(huì)對(duì)變量的類型做更改總結(jié)
以上是生活随笔為你收集整理的pytorch基础一:张量的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android官方开发文档Trainin
- 下一篇: 笔记:《幸福的方法》