torch.max()和torch.mean()的用法

torch.max()和torch.mean()的用法

import torch
import torch.nn as nn
## 原文地址https://blog.csdn.net/liuweiyuxiang/article/details/84668269
## 这里是来输入tensor,然后是来返回tensor中所对应的最大值
a = torch.randn(1, 3)  ## 这里是来随机生成3个数
print(a)

print(torch.max(a))

## 然后是对应按维度来返回最大值,并且来返回相应的索引的过程的
a = torch.randn(3,3)
print(a)
## 其中dim是对应的相应的维度的,其中是返回每一列中所对应的最大值,并且来返回索引(返回最大元素,在这一行所对应的函数索引)
print(torch.max(a,0))
## 返回是数组元素中每一行所对应的最大值,并且是返回在这一行上的最大元素,所对应的列索引的
print(torch.max(a,1))
#原文地址https://blog.csdn.net/u013049912/article/details/105628097
## 这里是来求出相应的均值的过程的。
x=torch.arange(12).view(4,3) ## 按照排列的方式来对数据就进行赋值,并且在转换为(4,3)列时所对应的矩阵的
'''
注意:在这里使用的时候转一下类型,否则会报RuntimeError: Can only calculate the mean of floating types. Got Long instead.的错误。
查看了一下x元素类型是torch.int64,根据提示添加一句x=x.float()转为tensor.float32就行
'''
x=x.float() ## 这里是来把x转换为float()来进行计算
x_mean=torch.mean(x)  ## 这里是返回所有元素的平均值
x_mean0=torch.mean(x,dim=0,keepdim=True)  ## 先对第1列求平均值,在对第2列求平均值,在对第3列求平均值 返回的是行
x_mean1=torch.mean(x,dim=1,keepdim=True)  ##  先对第1行求平均值,在来对第2行求平均孩子,在对第3行求平均值,在对第4行求平均值,返回的是列
print('x:')
print(x)
print('x_mean0:')
print(x_mean0)
print('x_mean1:')
print(x_mean1)
print('x_mean:')
print(x_mean)

进度条和torch.cat()用法

#原文地址cnblogs.com/JeasonIsCoding/p/10162356.html
pbar = tqdm(total=100)
for i in range(10):  ## 总共是来循环10次
    pbar.update(10)  ## 这样每一次是更新10个
pbar.close()

import torch

A=torch.ones(2,3) ## 这里是输出2行3列全是1的向量
print(A)

B=2*torch.ones(4,3)  ## 然后是输出4行3列的向量后在来乘以2
print(B)

C=torch.cat((A,B),0) ## 是来进行竖着拼接  这里是要列数相同才能够进行拼接
print(C.size())

print(C)

D=2*torch.ones(2,4) #2x4的张量(矩阵)
C=torch.cat((A,D),1)#按维数1(列)拼接  这里是要行数相同才能够进行拼接的。
print(C)
print(C.size())

## 其中cat还可以把list中的tensor拼接起来
x = torch.Tensor([[1],[2],[3]])
print(x)
x2 = torch.cat([x*2 for i in range(1,4)],1)
print(x2) ## 是按照列的方法是来进行连接后进行拼接起来

你可能感兴趣的:(机器学习,python)