Numpy 簡述

1、np.random

1.1 np.random.rand

np.random.rand(d0, d1, ..., dn)

Random values in a given shape.
Create an array of the given shape and populate it with random samples from a uniform distribution over [0,1).

參數:

  • d0, d1, …, dn [int, optional] The dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Returns:

  • out [ndarray, shape (d0, d1, …, dn)] 隨機參數值.
>>> np.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
	   [ 0.37601032, 0.25528411], #random
	   [ 0.49313049, 0.94909878]]) #random

1.2 np.random.randn

np.random.randn(d0, d1, ..., dn)

Return a sample (or samples) from the “standard normal” distribution.If positive, int_like or int-convertible arguments are provided, randn generates an array of shape (d0, d1,…, dn), filled with random floats sampled from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1 (if any of the 𝑒 𝑗 are floats, they are first converted to integers by truncation). A single float randomly sampled from the distribution is returned if no argument is provided.

This is a convenience function. If you want an interface that takes a tuple as the first argument, use numpy.
random.standard_normal instead.

參數:

  • d0, d1, …, dn [int, optional] The dimensions of the returned array, should be all positive. If no argument is given a single Python float is returned.

Returns:

  • Z [ndarray or float] A (d0, d1, …, dn)-shaped array of floating-point samples from the standard normal distribution, or a single such float if no parameters were supplied.

注意:
For random samples from N(μ,σ2)N( \mu ,\sigma^2 ), use:
sigma * np.random.randn(…) + mu

>>> np.random.randn()
2.1923875335537315 										   #random

>>> 2.5 * np.random.randn(2, 4) + 3
array([[-4.49401501, 4.00950034, -1.81814867, 7.29718677], #random
	   [ 0.39924804, 4.68456316, 4.99394529, 4.84057254]]) #random

1.3 np.random.random

np.random.random(size=None)

Return random floats in the half-open interval [0.0, 1.0).
Results are from the “continuous uniform” distribution over the stated interval. To sample 𝑉𝑜𝑗𝑔[𝑏,𝑐),𝑐 > 𝑏
multiply the output of random_sample by (b-a) and add a:
(b - a) * random_sample() + a

Parameters:

  • size [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Returns:

  • out [float or ndarray of floats] Array of random floats of shape size (unless size=None, in which case a single float is returned).

1.4 np.random.randint

np.random.randint(low, high=None, size=None, dtype=’l’)

Return random integers from low (inclusive) to high (exclusive).
Return random integers from the “discrete uniform”distribution of the specified dtype in the “half-open” interval [low, high). If high is None (the default), then results are from [0, low).

Parameters:

  • low [int] Lowest (signed) integer to be drawn from the distribution (unless high=None, in which case this parameter is one above the highest such integer).
  • high [int, optional] If provided, one above the largest (signed) integer to be drawn from the distribution (see above for behavior if high=None).
  • size [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.
  • dtype [dtype, optional] Desired dtype of the result. All dtypes are determined by their name,i.e., ‘int64’, ‘int’, etc, so byteorder is not available and a specific precision may have different C types depending on the platform. The default value is ‘np.int’.
    New in version 1.11.0.

Returns:
out [int or ndarray of ints] size-shaped array of random integers from the appropriate distribution, or a single such random int if size not provided.

>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
[3, 2, 2, 0]])

2、np.array

2.1 np.ones & np.zeros

方法 描述
eye(N[M, k, dtype, order]) 返回一個二維數組,對角線上有一個,其他地方爲零。
identity(n[ dtype]) 返回標識數組。
empty(shape[dtype, order]) 返回給定形狀和類型的新數組,而無需初始化條目。
empty_like(prototype[dtype, order, subok, …]) 返回形狀和類型與給定數組相同的新數組。
ones(shape[dtype, order]) 返回給定形狀和類型的新數組,並填充爲1。
ones_like(a[dtype, order, subok, shape]) 返回形狀與類型與給定數組相同的數組。
zeros(shape[dtype, order]) 返回給定形狀和類型的新數組,並用零填充。
zeros_like(a[dtype, order, subok, shape]) 返回形狀與類型與給定數組相同的零數組。
full(shape, fill_value[dtype, order]) 返回給定形狀和類型的新數組,並用fill_value填充。
full_like(a, fill_value[dtype, order, …]) 返回形狀和類型與給定數組相同的完整數組。

2.2 np.array

np.array(object, dtype=None, copy=True, order=’K’, subok=False, ndmin=0)
Create an array.

Parameters:

  • object [array_like] An array, any object exposing the array interface, an object whose __array __ method returns an array, or any (nested) sequence.
  • dtype [data-type, optional] The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.
  • copy [bool, optional] If true (default), then the object is copied. Otherwise, a copy will only be made if _array_ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.).
  • order [{‘K’, ‘A’, ‘C’, ‘F’}, optional] Specify the memory layout of the array. If object is not an array, the newly created array will be in C order (row major) unless ‘F’ is specified, in which case it will be in Fortran order (column major). If object is an array the following holds.
order no copy copy=True
‘K’ unchanged F & C order preserved, otherwise most similar order
‘A’ unchanged F order if input is F and not C, otherwise C order
‘C’ C order C order
‘F’ F order F order
  • When copy=False and a copy is made for other reasons, the result is the same as if copy=True, with some exceptions for A, see the Notes section. The default order is ‘K’.
  • subok [bool, optional] If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default).
  • ndmin [int, optional] Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.

Returns:
out [ndarray] An array object satisfying the specified requirements.

Examples:

>>> np.array([1, 2, 3])
array([1, 2, 3])

>>> np.array([1, 2, 3.0])
array([ 1., 2., 3.])

>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
[3, 4]])

>>> np.array([1, 2, 3], ndmin=2)
array([[1, 2, 3]])

>>> np.array([1, 2, 3], dtype=complex)
array([ 1.+0.j, 2.+0.j, 3.+0.j])

>>> x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
>>> x['a']
array([1, 3])

>>> np.array(np.mat('1 2; 3 4'))
array([[1, 2],
[3, 4]])

>>> np.array(np.mat('1 2; 3 4'), subok=True)
matrix([[1, 2],
[3, 4]])

2.3 np.ndarray

np.ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)

An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory,
whether it is an integer, a floating point number, or something else, etc.)

Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters given here refer to a low-level method (ndarray(…)) for instantiating an array.

For more information, refer to the numpy module and examine the methods and attributes of an array.

Parameters:

  • shape [tuple of ints] Shape of created array.
  • dtype [data-type, optional] Any object that can be interpreted as a numpy data type.
  • buffer [object exposing buffer interface, optional] Used to fill the array with data.
  • offset [int, optional] Offset of array data in buffer.
  • strides [tuple of ints, optional] Strides of data in memory.
  • order [{‘C’, ‘F’}, optional] Row-major (C-style) or column-major (Fortran-style) order.

Attributes:

  • T [ndarray] Same as self.transpose(), except that self is returned if self.ndim < 2.
  • data [buffer] Python buffer object pointing to the start of the array’s data.
  • dtype [dtype object] Data-type of the array’s elements.
  • flags [dict] Information about the memory layout of the array.
  • flat [numpy.flatiter object] A 1-D iterator over the array.
  • imag [ndarray] The imaginary part of the array.
  • real [ndarray] The real part of the array.
  • size [int] Number of elements in the array.
  • itemsize [int] Length of one array element in bytes.
  • nbytes [int] Total bytes consumed by the elements of the array.
  • ndim [int] Number of array dimensions.
  • shape [tuple of ints] Tuple of array dimensions.
  • strides [tuple of ints] Tuple of bytes to step in each dimension when traversing an array.
  • ctypes [ctypes object] An object to simplify the interaction of the array with the ctypes module.
  • base [ndarray] Base object if memory is from some other object.

Examples:

>>> np.ndarray(shape=(2,2), dtype=float, order='F')
array([[ -1.13698227e+002, 4.25087011e-303],
[ 2.88528414e-306, 3.27025015e-309]]) #random

>>> np.ndarray((2,), buffer=np.array([1,2,3]),
... offset=np.int_().itemsize,
... dtype=int) # offset = 1 * itemsize, i.e. skip first element
array([2, 3])

一個 ndarray是具有相同類型和大小的項目的多維容器。
尺寸和數組中的項目的數量是由它的shape定義, 它是由N個非負整數組成的tuple(元組),用於指定每個維度的大小。

不同的是,ndarrays可以共享相同的數據, 因此在一個ndarray中進行的更改可能在另一箇中可見。 也就是說,ndarray可以是另一個ndarray 的 “view” ,它所指的數據由 “base” ndarray處理。 ndarrays也可以是Python擁有的內存strings或實現 buffer 或數組接口的對象的視圖。

2.4 數組屬性

以下屬性包含有關數組內存佈局的信息:

方法 描述
ndarray.flags 有關數組內存佈局的信息
ndarray.shape 數組維度的元組
ndarray.strides 遍歷數組時每個維度中的字節元組
ndarray.ndim 數組維數
ndarray.data Python 緩衝區對象指向數組的數據的開頭
ndarray.size 數組中的元素數
ndarray.itemsize 一個數組元素的長度,以字節爲單位
ndarray.nbytes 數組元素消耗的總字節數
ndarray.base 如果內存來自其他對象,則爲基礎對象

3、創建矩陣

方法 描述
mat(data[, dtype]) 將輸入解釋爲矩陣。
bmat(obj[, ldict, gdict]) 從字符串,嵌套序列或數組構建矩陣對象。
diag(v[, k]) 提取對角線或構造對角線數組。
diagflat(v[, k]) 使用展平的輸入作爲對角線創建二維數組。
tri(N[, M, k, dtype]) 在給定對角線處及以下且在其他位置爲零的數組。
tril(m[, k]) 數組的下三角。
triu(m[, k]) 數組的上三角。
vander(x[, N, increasing]) 生成範德蒙矩陣。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章