日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

PyTorch基础-Tensor的属性,数据,运算-01

發布時間:2024/9/15 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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


矩陣相乘

tensor = torch.ones(3,5,dtype=int) tensor

a1 = torch.randint(1,5,(2,3)) a1

torch.matmul(a1,tensor)#矩陣相乘 2行3列 * 3行5列 = 2行5列

a1.T # 矩陣轉置 2行3列變為3行2列

sample = torch.rand(3,2) sample

torch.sum(sample) # 求和

torch.min(sample) #最小值

torch.max(sample) #最大值

torch.argmin(sample) # 求最小值所在的位置(索引)

torch.argmax(sample) # 求最大值所在的位置(索引)

torch.mean(sample)# 求平均值

torch.median(sample)# 求中位數

torch.sqrt(sample)# 每個值計算開方

sample ** 2 # 求每個值的平方








數據的索引

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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。