torch一些语法简单掌握 包含where mean

torch.where

import torch
>>> import numpy
>>> a=torch.rand(2,2)
>>> a
tensor([[6.0998e-01, 1.1539e-04],
        [6.8827e-01, 4.0862e-01]])
>>> b=torch.rand(2,2)
>>> b
tensor([[0.5579, 0.8235],
        [0.0321, 0.7925]])
>>> a=torch.rand(2,2)
>>> a
tensor([[0.5463, 0.1074],
        [0.8725, 0.4264]])
>>> c=torch.rand(2,2)
>>> c
tensor([[0.9275, 0.0640],
        [0.4547, 0.6653]])
>>> d=torch.where(c,a,b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Expected condition to have ScalarType Byte, but got ScalarType Float
>>> d=torch.where(c>0.5,a,b)
>>> d
tensor([[0.5463, 0.8235],
        [0.0321, 0.4264]])

类似于条件选择

torch.mean()

Python 3.8.10 (default, May 19 2021, 13:12:57) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32

Warning:
This Python interpreter is in a conda environment, but the environment has
not been activated.  Libraries may fail to load.  To activate this environment
please see https://conda.io/activation

Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.rand(4,4)
tensor([[0.0603, 0.8325, 0.9214, 0.8851],
        [0.9170, 0.1762, 0.9931, 0.1634],
        [0.6276, 0.4836, 0.4940, 0.7720],
        [0.2507, 0.7489, 0.3419, 0.3144]])
>>> a=torch.rand(4,4)
>>> a.mean()
tensor(0.4578)
>>> a=torch.tensor([[1,0],[0,1]])
>>> a
tensor([[1, 0],
        [0, 1]])
>>> a.mean()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Can only calculate the mean of floating types. Got Long instead.
>>> a=torch.tensor([[1,0],[0,1]],dtype=torch.float32)
>>> a
tensor([[1., 0.],
        [0., 1.]])
>>> a.mean()
tensor(0.5000)
>>> a=torch.tensor([[1,0],[0,4])
  File "<stdin>", line 1
    a=torch.tensor([[1,0],[0,4])
                               ^
SyntaxError: closing parenthesis ')' does not match opening parenthesis '['
>>>  a=torch.tensor([[1,0],[0,4.0]])
  File "<stdin>", line 1
    a=torch.tensor([[1,0],[0,4.0]])
    ^
IndentationError: unexpected indent
>>> a=torch.tensor([[1,0],[0,4.0]])
>>> a
tensor([[1., 0.],
        [0., 4.]])
>>> a.mean()
tensor(1.2500)
>>>

不加任何东西,直接返回所有维度的平均值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值