Numpy中的矩阵和数组
numpy包含两种基本的数据类型:数组(array)和矩阵(matrix)。无论是数组,还是矩阵,都由同种元素组成。
下面是测试程序:
# coding:utf-8 import numpy as np # print(dir(np)) M = 3 #---------------------------Matrix--------------------------- A = np.matrix(np.random.rand(M,M)) # 随机数矩阵 print('原矩阵:',A) # A矩阵 print('A矩阵维数:',A.shape) # 获取矩阵大小 print('A的转置:',A.T) # A的转置 print('sum=',np.sum(A,axis=1)) # 横着加 print('sorted=',np.sort(A,axis=1)) # 竖着排 print('sin(A[0])=',np.sin(A[0])) # 第一行元素取余弦值 print('A*A.T=',A*A.T) # A*A.T print('A.*A=',np.multiply(A,A)) # 点乘 print('mean(A)=',np.mean(A)) # 平均值,mean(A,axis=1)亦可 print('Rank(A)=',np.linalg.matrix_rank(A)) # 矩阵的秩
#--------------------------Array-----------------------------# B = np.array(np.random.randn(2,M,M)) # 可以是二维的 print('B =',B) # 原矩阵 print('Size(B)= [',B.shape[0],B.shape[1],B.shape[2],']; ndim(B)=',B.ndim) print('B[0]=',B[0]) # 第一维 Position = np.where(B[0]<0) #numpy.where和find用法相同 print('B[0]<0的位置:',Position[0],'(横坐标);',Position[1],'(纵坐标)') print('B[0][condition])=',B[0][B[0]<0]) # 找第一维数组中满足条件的元素 print('Dot(B[0][0],B[0][0])=',np.dot(B[0][0],B[0][0])) # 向量形式才计算内积
知识点:
(1)dir、shape、T、sum、sort、*、multiply、mean、linalg;
(2)创建array、dot、where、逻辑索引
运行结果:
原矩阵: [[0.47866118 0.35559024 0.29611557] [0.65120903 0.19081953 0.82391251] [0.57782583 0.31228507 0.33127398]] A矩阵维数: (3, 3) A的转置: [[0.47866118 0.65120903 0.57782583] [0.35559024 0.19081953 0.31228507] [0.29611557 0.82391251 0.33127398]] sum= [[1.130367 ] [1.66594107] [1.22138488]] sorted= [[0.29611557 0.35559024 0.47866118] [0.19081953 0.65120903 0.82391251] [0.31228507 0.33127398 0.57782583]] sin(A[0])= [[0.46059124 0.34814374 0.29180705]] A*A.T= [[0.44324538 0.62353537 0.4857237 ] [0.62353537 1.13931712 0.70881626] [0.4857237 0.70881626 0.54114711]] A.*A= [[0.22911653 0.12644442 0.08768443] [0.4240732 0.03641209 0.67883183] [0.33388269 0.09752197 0.10974245]] mean(A)= 0.4464103278030135 Rank(A)= 3
B = [[[-0.33149526 -0.1779488 -1.46461345] [ 2.04476951 0.57567528 1.99045816] [-0.17053449 -1.12967297 1.25256121]] [[ 0.88130117 2.2024554 -0.06824366] [-2.15066117 -0.74484564 -0.59614793] [ 0.53481679 0.42388459 0.2779472 ]]] Size(B)= [ 2 3 3 ]; ndim(B)= 3 B[0]= [[-0.33149526 -0.1779488 -1.46461345] [ 2.04476951 0.57567528 1.99045816] [-0.17053449 -1.12967297 1.25256121]] B[0]<0的位置: [0 0 0 2 2] (横坐标); [0 1 2 0 1] (纵坐标) B[0][condition])= [-0.33149526 -0.1779488 -1.46461345 -0.17053449 -1.12967297] Dot(B[0][0],B[0][0])= 2.2866474366446807
总结(上面的可以自己试一试,主要是这里):
- 学会索引方式(部分元素的检索)
- 学会获取matrix/array的维数(matrix只支持二维,array支持多维)
- 初始化操作
- 矩阵运算:转置,相乘,点乘,点积,求秩,求逆等等
- 和matlab常用的函数对比(右为matlab):
- zeros<->zeros
- eye<->eye
- ones<->ones
- mean<->mean
- where<->find
- sort<->sort
- sum<->sum
- 其他数学运算:sin,cos,arcsin,arccos,log等
此外,可以通过help(dir(numpy))查看numpy包中的函数:
['ALLOW_THREADS', 'AxisError', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MAY_SHARE_BOUNDS', 'MAY_SHARE_EXACT', 'MachAr', 'ModuleDeprecationWarning', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'TooHardError', 'True_', 'UFUNC_BUFSIZE_DEFAULT', 'UFUNC_PYVALS_NAME', 'VisibleDeprecationWarning', 'WRAP', '_NoValue', '__NUMPY_SETUP__', '__all__', '__builtins__', '__cached__', '__config__', '__doc__', '__file__', '__git_revision__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_distributor_init', '_globals', '_import_tools', '_mat', '_numpy_tester',
# a、b、c开头: 'abs', 'absolute', 'absolute_import', 'add', 'add_docstring', 'add_newdoc', 'add_newdoc_ufunc', 'add_newdocs', 'alen', 'all', 'allclose', 'alltrue', 'amax', 'amin', 'angle', 'any', 'append', 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin', 'argpartition', 'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal', 'array_equiv', 'array_repr', 'array_split', 'array_str', 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray', 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett', 'base_repr', 'bench', 'binary_repr', 'bincount', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman', 'block', 'bmat', 'bool', 'bool8', 'bool_', 'broadcast', 'broadcast_arrays', 'broadcast_to', 'busday_count', 'busday_offset', 'busdaycalendar', 'byte', 'byte_bounds', 'bytes0', 'bytes_' 'c_', 'can_cast', 'cast', 'cbrt', 'cdouble', 'ceil', 'cfloat', 'char', 'character', 'chararray', 'choose', 'clip', 'clongdouble', 'clongfloat', 'column_stack', 'common_type', 'compare_chararrays', 'compat', 'complex', 'complex128', 'complex64', 'complex_', 'complexfloating', 'compress', 'concatenate', 'conj', 'conjugate', 'convolve', 'copy', 'copysign', 'copyto', 'core', 'corrcoef', 'correlate', 'cos', 'cosh', 'count_nonzero', 'cov', 'cross', 'csingle', 'ctypeslib', 'cumprod', 'cumproduct', 'cumsum'
# d、e、f、g开头: 'datetime64', 'datetime_as_string', 'datetime_data', 'deg2rad', 'degrees', 'delete', 'deprecate', 'deprecate_with_doc', 'diag', 'diag_indices', 'diag_indices_from', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide', 'division', 'divmod', 'dot', 'double', 'dsplit', 'dstack', 'dtype','e', 'ediff1d', 'einsum', 'einsum_path', 'emath', 'empty', 'empty_like', 'equal', 'errstate', 'euler_gamma', 'exp', 'exp2', 'expand_dims', 'expm1', 'extract', 'eye', 'fabs', 'fastCopyAndTranspose', 'fft', 'fill_diagonal', 'find_common_type', 'finfo', 'fix', 'flatiter', 'flatnonzero', 'flexible', 'flip', 'fliplr', 'flipud', 'float', 'float16', 'float32', 'float64', 'float_', 'float_power', 'floating', 'floor', 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_float_positional', 'format_float_scientific', 'format_parser', 'frexp', 'frombuffer', 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'full', 'full_like', 'fv', 'generic', 'genfromtxt', 'geomspace', 'get_array_wrap', 'get_include', 'get_printoptions', 'getbufsize', 'geterr', 'geterrcall', 'geterrobj', 'gradient', 'greater', 'greater_equal'
# h、i、j、k、l、m、n开头: 'half', 'hamming', 'hanning', 'heaviside', 'histogram', 'histogram2d', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0', 'identity', 'iinfo', 'imag', 'in1d', 'index_exp', 'indices', 'inexact', 'inf', 'info', 'infty', 'inner', 'insert', 'int', 'int0', 'int16', 'int32', 'int64', 'int8', 'int_', 'int_asbuffer', 'intc', 'integer', 'interp', 'intersect1d', 'intp', 'invert', 'ipmt', 'irr', 'is_busday', 'isclose', 'iscomplex', 'iscomplexobj', 'isfinite', 'isfortran', 'isin', 'isinf', 'isnan', 'isnat', 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_', 'issubdtype', 'issubsctype', 'iterable', 'ix_', 'kaiser', 'kron' 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort', 'lib', 'linalg', 'linspace', 'little_endian', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace', 'long', 'longcomplex', 'longdouble', 'longfloat', 'longlong', 'lookfor', 'ma', 'mafromtxt', 'mask_indices', 'mat', 'math', 'matmul', 'matrix', 'matrixlib', 'max', 'maximum', 'maximum_sctype', 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid', 'mgrid', 'min', 'min_scalar_type', 'minimum', 'mintypecode', 'mirr', 'mod', 'modf', 'moveaxis', 'msort', 'multiply', 'nan', 'nan_to_num', 'nanargmax', 'nanargmin', 'nancumprod', 'nancumsum', 'nanmax', 'nanmean', 'nanmedian', 'nanmin', 'nanpercentile', 'nanprod', 'nanstd', 'nansum', 'nanvar', 'nbytes', 'ndarray', 'ndenumerate', 'ndfromtxt', 'ndim', 'ndindex', 'nditer', 'negative', 'nested_iters', 'newaxis', 'nextafter', 'nonzero', 'not_equal', 'nper', 'npv', 'numarray', 'number'
# o、p、q、r、s、t开头: 'obj2sctype', 'object', 'object0', 'object_', 'ogrid', 'oldnumeric', 'ones', 'ones_like', 'outer', 'packbits', 'pad', 'partition', 'percentile', 'pi', 'piecewise', 'pkgload', 'place', 'pmt', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv', 'polyfit', 'polyint', 'polymul', 'polynomial', 'polysub', 'polyval', 'positive', 'power', 'ppmt', 'print_function', 'prod', 'product', 'promote_types', 'ptp', 'put', 'putmask', 'pv', 'r_', 'rad2deg', 'radians', 'random', 'rank', 'rate', 'ravel', 'ravel_multi_index', 'real', 'real_if_close', 'rec', 'recarray', 'recfromcsv', 'recfromtxt', 'reciprocal', 'record', 'remainder', 'repeat', 'require', 'reshape', 'resize', 'result_type', 'right_shift', 'rint', 'roll', 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_', 'safe_eval', 'save', 'savetxt', 'savez', 'savez_compressed', 'sctype2char', 'sctypeDict', 'sctypeNA', 'sctypes', 'searchsorted', 'select', 'set_numeric_ops', 'set_printoptions', 'set_string_function', 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj', 'setxor1d', 'shape', 'shares_memory', 'short', 'show_config', 'sign', 'signbit', 'signedinteger', 'sin', 'sinc', 'single', 'singlecomplex', 'sinh', 'size', 'sometrue', 'sort', 'sort_complex', 'source', 'spacing', 'split', 'sqrt', 'square', 'squeeze', 'stack', 'std', 'str', 'str0', 'str_', 'string_', 'subtract', 'sum', 'swapaxes', 'sys', 'take', 'tan', 'tanh', 'tensordot', 'test', 'testing', 'tile', 'timedelta64', 'trace', 'tracemalloc_domain', 'transpose', 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from', 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from', 'true_divide', 'trunc', 'typeDict', 'typeNA', 'typecodes', 'typename'
# u、v、w、x、y、z开头: 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16', 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong', 'unicode', 'unicode_', 'union1d', 'unique', 'unpackbits', 'unravel_index', 'unsignedinteger', 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize', 'version', 'void', 'void0', 'vsplit', 'vstack', 'warnings', 'where', 'who', 'zeros', 'zeros_like']