Pytorch創(chuàng)建隨機(jī)值張量的過程詳解
2-Pytorch創(chuàng)建隨機(jī)值張量
1 導(dǎo)入必備庫
import torch import numpy as np
2 使用torch.rand()創(chuàng)建0-1均勻分布的隨機(jī)數(shù)
t = torch.rand(2,3) print(t)
輸出:
tensor([[0.1452, 0.1435, 0.2124],
[0.6646, 0.5232, 0.1572]])
3 使用torch.randn()創(chuàng)建正態(tài)分布的隨機(jī)數(shù)
t = torch.randn(2,3) print(t)
輸出:
tensor([[-0.5325, -0.4938, 0.6301],
[-0.6313, -0.1412, 2.2926]])
4 使用torch.zeros()創(chuàng)建全0張量
t = torch.zeros(3) print(t) print(t.dtype)
輸出:
tensor([0., 0., 0.])
torch.float32
5 使用torch.ones()創(chuàng)建全1張量
t = torch.ones(3) print(t) print(t.dtype)
輸出:
tensor([1., 1., 1.])
torch.float32
6 從另一個張量創(chuàng)建新的張量
x = torch.zeros_like(t) print(x) x = torch.rand_like(t) print(x)
輸出:
tensor([0., 0., 0.])
tensor([0.6516, 0.5740, 0.6379])
7 張量的屬性:
tensor.shape返回張量的形狀,與tensor.size()方法等價,tensor.dtype返回當(dāng)前張量的類型
t = torch.ones(2,3,dtype= torch.float64) print(t.shape) print(t.size()) print(t.size(1)) # 返回第二維度大小 print(t.dtype) print(t.device)
輸出:
torch.Size([2, 3])
torch.Size([2, 3])
3
torch.float64
cpu
8 將張量移動到顯存,使用tensor.to()方法將張量移動到GPU上
# 如果GPU可用,將張量移動到顯存
# 設(shè)置使用哪塊芯片,多塊GPU使用逗號隔開
# import os
# os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 多塊GPU設(shè)置,如:'0,1,2'
if torch.cuda.is_available():
t = t.to('cuda')
print(t.device)輸出:
cuda:0
9 更穩(wěn)妥的移動顯存方法,無論是否有GPU都能保證運行
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 啟動cuda
print("Using {} device".format(device)) # 打印當(dāng)前設(shè)備
t = t.to(device)
print(t.device)輸出:
Using cuda device
cuda:0
到此這篇關(guān)于Pytorch創(chuàng)建隨機(jī)值張量的文章就介紹到這了,更多相關(guān)Pytorch隨機(jī)值張量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python虛擬環(huán)境virualenv的安裝與使用
virtualenv 是一個創(chuàng)建隔絕的Python環(huán)境的工具。virtualenv創(chuàng)建一個包含所有必要的可執(zhí)行文件的文件夾,用來使用Python工程所需的包。下面這篇文章就給大家介紹了python虛擬環(huán)境virualenv的安裝與使用,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-12-12
Python計算一個點到所有點的歐式距離實現(xiàn)方法
今天小編就為大家分享一篇Python計算一個點到所有點的歐式距離實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python 實現(xiàn)局域網(wǎng)遠(yuǎn)程屏幕截圖案例
這篇文章主要介紹了Python 實現(xiàn)局域網(wǎng)遠(yuǎn)程屏幕截圖案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
python實現(xiàn)向ppt文件里插入新幻燈片頁面的方法
這篇文章主要介紹了python實現(xiàn)向ppt文件里插入新幻燈片頁面的方法,涉及Python操作ppt文檔添加幻燈片的相關(guān)技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04

