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()