shape,size,type 以及 random 的一些总结(numpy / pytorch)

1.numpy 与 pytorch中的 shape , size() , type()

array是一个方法,通过np.array这个方法生成ndarray数组

numpy中,ndarray.shape 可以得到矩阵的维度大小;而np.size(ndarray)得到的是矩阵中数据的个数。type(ndarray) 可以查看变量类型;ndarray.dtype 查看ndarray中数据值的类型。

>>> import numpy as np
>>> np.array((2, 3, 4, 5)).reshape(2, 2)
array([[2, 3],
       [4, 5]])

# ndarray.shape
>>> np.array((2,3)).shape
(2,)
>>> np.array((2, 3, 4, 5)).reshape(2, 2).shape
(2, 2)

>>> np.array((2, 3, 4, 5)).reshape(2, 2).size()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

# np.size(ndarray)
>>> y = np.array((2,3))
>>> np.size(y)
2
>>> z = np.array((2, 3, 4, 5)).reshape(2, 2)
>>> np.size(z)
4

# ndarray.dtype【data type】--type(ndarray)【ndarray type】
>>> np.array((2,3)).dtype
dtype('int32')
>>> type(np.array((2,3)))
<class 'numpy.ndarray'>

在torch中,tensor.size() 可以查看当前tensor维度;tensor.shape 与 tensor.size() 输出相同;tensor.type() 可查看tensor类型

# torch中的用法
>>> import torch
>>> torch.Tensor(2, 3)
tensor([[0., 0., 0.],
        [0., 0., 0.]])

>>> (torch.Tensor(2, 3)).size()
torch.Size([2, 3])

>>> (torch.Tensor(2, 3)).shape
torch.Size([2, 3])

>>> torch.Tensor(2, 3).type()
'torch.FloatTensor'

2. numpy.random.randint 与 random.randint 的区别

numpy.random.randint(a, b, size = None):使用前需要调用numpy库(import numpy),返回的是随机整数m ∈ [a, b) --- a的值可以取到,b的值取不到 ; 如果指定size,会返回size个随机整数。

(import numpy as np)
# 生成随机整数
>>> amplitudes = np.random.randint(33,37,300*25*2)
>>> print(amplitudes)
[33 34 36 ... 33 34 36]
>>> print(amplitudes.shape)
(15000,)

#除100以生成随机小数
>>> amplitudes = np.random.randint(33,37,300*25*2)/100
>>> print(amplitudes, amplitudes.shape)
[0.36 0.35 0.33 ... 0.35 0.35 0.36] (15000,)

# 想生成随机小数出错
>>> amplitudes = np.random.randint(0.33,0.37,300*25*2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 992, in mtrand.RandomState.randint
ValueError: Range cannot be empty (low >= high) unless no samples are taken

random.randint(a, b): 使用前需要调用random库(import random),返回的是一个随机整数n, n ∈ [a, b]   ---可以取到 a 和 b 的值。

>>> import random
>>> random.randint(33, 37)
37
>>> random.randint(0.33,0.37)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\anaconda\lib\random.py", line 222, in randint
    return self.randrange(a, b+1)
  File "D:\anaconda\lib\random.py", line 186, in randrange
    raise ValueError("non-integer arg 1 for randrange()")
ValueError: non-integer arg 1 for randrange()

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值