colab里的numpy笔记

01 Sep 2020 Skill, Note, and Python

From CS5242 Neural Networks and Deep Learning - Lecture1 colab


np.random.seed(1234)
x = np.random.normal(loc=0, scale=1, size=(3, 1))
A = np.random.normal(loc=0, scale=1, size=(2, 3))
u = np.matmul(A, x)
b = np.random.normal(loc=0, scale=1, size=(2, 1))
y = np.linalg.norm(u - b, ord=2) ** 2

numpy.matmul


numpy.matmul(x1, x2, /, out=None, *, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) = <ufunc ‘matmul’>

Matrix product of two arrays. 两个numpy array矩阵相乘。

Parameters

x1, x2: array_like

Input arrays, scalars not allowed.

out: ndarray, optional A location into which the result is stored. If provided, it must have a shape that matches the signature (n,k),(k,m)->(n,m). If not provided or None, a freshly-allocated array is returned.

**kwargs For other keyword-only arguments, see the ufunc docs.

New in version 1.16: Now handles ufunc kwargs

Returns

y: ndarray

The matrix product of the inputs. This is a scalar only when both x1, x2 are 1-d vectors.

Raises

ValueError If the last dimension of a is not the same size as the second-to-last dimension of b.

If a scalar value is passed in.


numpy.ndarray.T


ndarray.T

The transposed array. 转置矩阵。

Same as self.transpose().

Examples

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

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

numpy.linalg.norm


numpy.linalg.norm(x, ord=None, axis=None, keepdims=False)

Matrix or vector norm. 求矩阵或向量的范数。

This function is able to return one of eight different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ord parameter.

Parameters

x: array_like

Input array. If axis is None, x must be 1-D or 2-D, unless ord is None. If both axis and ord are None, the 2-norm of x.ravel will be returned.

ord: {non-zero int, inf, -inf, ‘fro’, ‘nuc’}, optional

Order of the norm (see table under Notes). inf means numpy’s inf object. The default is None.

axis: {None, int, 2-tuple of ints}, optional.

If axis is an integer, it specifies the axis of x along which to compute the vector norms. If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If axis is None then either a vector norm (when x is 1-D) or a matrix norm (when x is 2-D) is returned. The default is None.

New in version 1.8.0.

keepdims: bool, optional

If this is set to True, the axes which are normed over are left in the result as dimensions with size one. With this option the result will broadcast correctly against the original x.


Returns

nfloat or ndarray Norm of the matrix or vector(s).

Notes

For values of ord < 1, the result is, strictly speaking, not a mathematical ‘norm’, but it may still be useful for various numerical purposes.

The following norms can be calculated:

ord		norm for matrices			 norm for vectors
None	Frobenius norm	 			 2-norm
'fro'	Frobenius norm				 –
'nuc'	nuclear norm				 –
inf		max(sum(abs(x), axis=1))	 max(abs(x))
-inf	min(sum(abs(x), axis=1))	 min(abs(x))
0		–							 sum(x != 0)
1		max(sum(abs(x), axis=0))	 as below
-1		min(sum(abs(x), axis=0))	 as below
2		2-norm (largest sing. value) as below
-2		smallest singular value		 as below
other	–					sum(abs(x)**ord)**(1./ord)

From CS5340 - Assignment 1


numpy.nuion1d


计算两个函数的并集,唯一化并排序。

numpy.argmax


numpy.argmax(a, axis=None, out=None)

Returns the indices of the maximum values along an axis.

Parameters

a: array_like Input array.

axis: int, optional By default, the index is into the flattened array, otherwise along the specified axis. 为0代表列方向,为1代表行方向。返回每行/列最大值索引。

out: array, optional If provided, the result will be inserted into this array. It should be of the appropriate shape and dtype.

Returns index_arrayndarray of ints Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed.

Example

>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10, 11, 12],
       [13, 14, 15]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])

np.prod()

计算所有元素的乘积,对于有多个维度的数组可以指定轴,如axis=1指定计算每一行的乘积

[None, :] None整体作为数组元素处理。表示该维不进行切片,而是将该维 所以,[:,None]的效果就是将二维数组按每行分割,最后形成一个三维数组

其中: 是特殊的。它会构造一个 slice 对象。完整的语法是:start:stop:step,省略的部分取默认值 None。省略 step 时也可以省掉它前边的冒号。

arr = np.arange(12).reshape((3, 4))
out:
array([[ 0, 1, 2, 3],
		[ 4, 5, 6, 7],
		[ 8, 9, 10, 11]])

arr[i, :] #取第i行数据
arr[i:j, :] #取第i行到第j行的数据

arr[:,0] # 取第0列的数据,以行的形式返回的
out:
array([0, 4, 8])

arr[:,:1] # 取第0列的数据,以列的形式返回的
out:
array([[0],
		[4],
		[8]])

删除numpy array里的指定元素:

import numpy as np

>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])

From CS5242 Neural Networks and Deep Learning - Assignment 1


numpy.reshape(a, newshape, order=’C’)[source] Gives a new shape to an array without changing its data.

Parameters

a: array_like Array to be reshaped.

newshape: int or tuple of ints The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

order{‘C’, ‘F’, ‘A’}, optional Read the elements of a using this index order, and place the elements into the reshaped array using this index order. ‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest. ‘F’ means to read / write the elements using Fortran-like index order, with the first index changing fastest, and the last index changing slowest. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array, and only refer to the order of indexing. ‘A’ means to read / write the elements in Fortran-like index order if a is Fortran contiguous in memory, C-like order otherwise.

Returns reshaped_arrayndarray This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

reshape前后数组元素数量相等。当reshape的其中一个参数为-1时,会根据另一个参数计算另一个维度的参数值。

Example:

>>> z = np.array([[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]])
 
>>> print(z)
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]
>>> print(z.shape)
(4, 4)
>>> print(z.reshape(-1))
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
>>> print(z.reshape(-1,1))  #我们不知道z的shape属性是多少,
                            #但是想让z变成只有一列,行数不知道多少,
                            #通过`z.reshape(-1,1)`,Numpy自动计算出有16行,
                            #新的数组shape属性为(16, 1),与原来的(4, 4)配套。
[[ 1]
 [ 2]
 [ 3]
 [ 4]
 [ 5]
 [ 6]
 [ 7]
 [ 8]
 [ 9]
 [10]
 [11]
 [12]
 [13]
 [14]
 [15]
 [16]]
>>> print(z.reshape(2,-1))
[[ 1  2  3  4  5  6  7  8]
 [ 9 10 11 12 13 14 15 16]]

Official Document’s Example:

>>> a = np.array([[1,2,3], [4,5,6]])

>>> np.reshape(a, (3,-1))       # the unspecified value is inferred to be 2
array([[1, 2],
       [3, 4],
       [5, 6]])

关于np.sum()的axis参数表示的方向

Consider a less trivial two-dimensional case:

In [20]: b = np.array([[1,2,3],[4,5,6]])

In [21]: b
Out[21]: 
array([[1, 2, 3],
       [4, 5, 6]])

In [22]: b.shape
Out[22]: (2, 3) The first axis is the "rows". Sum along the rows:

In [23]: b.sum(axis=0)
Out[23]: array([5, 7, 9]) The second axis are the "columns". Sum along the columns:

In [24]: b.sum(axis=1)
Out[24]: array([ 6, 15])

关于矩阵里的乘法

np.dot(A, B):对于二维矩阵,做矩阵乘法。对于一维矩阵,计算两者的内积。

实现对应元素相乘,可以通过np.multiply()或者*。他们完全等效。

Comments