神经网络学习--PyTorch学习01

 PyTorch中的数据类型

分为浮点型和整数型两种:

import torch
# 浮点型
float_a = torch.FloatTensor(4, 5)  # size为2*3的矩阵
float_b = torch.FloatTensor([1, 2, 3, 4])  # [1,2,3,4]矩阵

# 整形
int_a = torch.IntTensor(4, 5)
int_b = torch.IntTensor([1, 2, 3, 4])

初始化数组有以下四种方式

import torch

# 随机生成浮点型Tensor
rand_a = torch.rand(2, 3)

# 随机生成E=0,D=1 正态分布的Tensor
randn_a = torch.randn(2, 3)

# 设定起始值、结束值、步长 的Tensor 此方法在0.5版本将被更改
range_a = torch.range(1, 20, 1)

# 设定数据为0的Tensor
zeros_a=torch.zeros(2, 3)

  

 运算

torch.abs取绝对值;torch.add相加;torch.clamp裁剪;torch.div求商;torch.mul求积;torch.pow求幂;torch.mm矩阵相乘;torch.mv矩阵和向量相乘(前后位置不能换)

 

import torch
# 取绝对值
abs_b = torch.abs(torch.randn(2, 3))
print(abs_b)

# 相加
add_b = torch.add(torch.randn(2, 3), torch.randn(2, 3))  # 矩阵相加
add_c = torch.add(torch.randn(2, 3), 10)  # 矩阵和数字相加
print(add_b)
print(add_c)

# 裁剪
clamp_b = torch.clamp(torch.randn(2, 3), -0.1, 0.1)  # 输入被裁剪矩阵,裁剪边界
print(clamp_b)

# 相除
div_b = torch.div(torch.randn(2, 3), torch.randn(2, 3))  # 矩阵相除
div_c = torch.div(torch.randn(2, 3), 10)  # 矩阵和数相除

# 求积
mul_b = torch.mul(torch.randn(2, 3), torch.randn(2, 3))  # 矩阵对应位置相乘
mul_c = torch.mul(torch.randn(2, 3), 10)  # 矩阵和数字相乘

# 求幂
pow_b = torch.pow(torch.randn(2, 3), 2)

# 矩阵乘法
mm_b = torch.mm(torch.randn(2, 3), torch.randn(3, 2))  # t()为矩阵转置

# 矩阵向量乘法 
mv_b = torch.mv(torch.randn(2, 3), torch.randn(3))

 

posted @ 2019-09-03 11:40  键盘已坏  阅读(246)  评论(0编辑  收藏  举报