import torch
# 打印torch版本
print("Hello World, Hello PyTorch {}".format(torch.__version__))
# 打印cuda是否可用,打印cuda版本
print("\nCUDA is available:{}, version is {}".format(torch.cuda.is_available(), torch.version.cuda))
# 打印cuda名称
print("\ndevice_name: {}".format(torch.cuda.get_device_name(0)))
Hello World, Hello PyTorch 1.11.0
CUDA is available:True, version is 11.3
device_name: GeForce GTX 1050
import torch
import numpy as np
torch.manual_seed(1)
arr = np.ones((3, 3))
print("ndarray的数据类型:", arr.dtype)
t = torch.tensor(arr)
print(t)
ndarray的数据类型: float64
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
arr = np.array([[1, 2, 3], [4, 5, 6]])
t = torch.from_numpy(arr)
print("numpy array: ", arr)
print("tensor : ", t)
print("\n修改tensor")
t[0, 0] = -1
print("numpy array: ", arr)
print("tensor : ", t)
numpy array: [[1 2 3]
[4 5 6]]
tensor : tensor([[1, 2, 3],
[4, 5, 6]], dtype=torch.int32)
修改tensor
numpy array: [[-1 2 3]
[ 4 5 6]]
tensor : tensor([[-1, 2, 3],
[ 4, 5, 6]], dtype=torch.int32)
out_t = torch.tensor([1])
t = torch.zeros((3, 3), out=out_t)
print(t, '\n', out_t)
print(id(t), id(out_t), id(t) == id(out_t))
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
2717724706592 2717724706592 True
t = torch.full((3, 3), 1.) # 1.6之后若不指定dtype,就需要传入浮点数
print(t)
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
t = torch.arange(2, 10, 2)
print(t)
tensor([2, 4, 6, 8])
t = torch.linspace(2, 10, 6)
print(t)
tensor([ 2.0000, 3.6000, 5.2000, 6.8000, 8.4000, 10.0000])
(1)通过张量,张量创建
# mean:张量 std: 张量
mean = torch.arange(1, 5, dtype=torch.float)
std = torch.arange(1, 5, dtype=torch.float)
t_normal = torch.normal(mean, std)
print("mean:{}\nstd:{}".format(mean, std))
print(t_normal)
mean:tensor([1., 2., 3., 4.])
std:tensor([1., 2., 3., 4.])
tensor([1.6614, 2.5338, 3.1850, 6.4853])
(2)通过标量,标量创建
# mean:标量 std: 标量
t_normal = torch.normal(0., 1., size=(4,))
print(t_normal)
tensor([0.6614, 0.2669, 0.0617, 0.6213])
(3)通过张量,标量创建
# mean:张量 std: 标量
mean = torch.arange(1, 5, dtype=torch.float)
std = 1
t_normal = torch.normal(mean, std)
print("mean:{}\nstd:{}".format(mean, std))
print(t_normal)
mean:tensor([1., 2., 3., 4.])
std:1
tensor([1.6614, 2.2669, 3.0617, 4.6213])
a = torch.ones((2,5))
print(a)
tensor([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
a = torch.rand(4, 1) # 返回一个形状为(4,1)的张量,从0-1的均匀分布中抽取的一组随机数
print(a)
tensor([[0.5007],
[0.9894],
[0.7115],
[0.0602]])
a = torch.randn(4, 1) # 返回一个形状为(4,1)的,从标准正态分布(均值为0,方差为1)中抽取的一组随机数
print(a)
tensor([[ 0.9353],
[-0.2985],
[-0.4224],
[ 0.4048]])