博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python Numpy的简单使用
阅读量:1973 次
发布时间:2019-04-27

本文共 6494 字,大约阅读时间需要 21 分钟。

在这里不去详解numpy的各种方法的使用,而是通过几道小题来熟悉一下,最最简单的使用。

A.Write a function array_slicemean(a) that takes a given 3-D array (such as aa=np.arange(27).reshape((3,3,3))) and returns a vector containing the sum of each slice of the first dimension. For example, the result of applying array_slicemean to the example given here isnp.array([ 36, 117, 198]).

import numpy as npfrom numpy import randomdef array_sliceman(a):	'''		function name:array_sliceman		parameter:array-3d		return:returns a vector containing the sum of each slice of the first dimension	'''    tmp_array = a.sum(axis=2)    result = tmp_array.sum(axis=1)    return resultaa = np.arange(27).reshape((3,3,3))res = array_sliceman(aa)print res

B.Write a function array_poly(a,x) that takes a 2-dimensional array a and a scalar (floating-point) x and computes a vector of polynomials using each row as a separate set of coefficients. In other words, if a has three columns, then the i^{th} element of the returned array would be a[i,0]+a[i,1]*x+a[i,2]*x**2. For example, the results of

import numpy as npa = np.reshape(np.arange(9),(3,3))array_poly(a,2)

should be np.array([10, 31, 52]).

def array_poly(a,x):	'''		function name:array_poly		parameter:				a:a 2-dimensional array				x:a scalar(floating point)		return:computes a vector of polynomials using each row as a separate set of coefficients	'''    result = []    for item in a:		'''reverse coefficients: turn \' a[i,0]*x**2 + a[i,1]*x + a[i,2]\' into \'a[i,0]+a[i,1]*x+a[i,2]*x**2\''''        item_reverse = item[::-1]         p = np.poly1d(item_reverse)        result.append( p(x) )	'''transfer list into numpy array and return'''    return np.array(result)     bb = np.reshape( np.arange(9),(3,3) )print array_poly(bb,2)

C.Write a function, check_inverse(a,b,tol=1e-8) that takes two 2-dimensional square arrays (matrices) and returns a boolean value that reflects whether b is the matrix inverse of a, i.e. that numpy.dot(a,b) is equal, within tolerance tol, to an identity matrix of the same dimension (use np.eye()). Make sure to:

  • check that the arrays are both square and have the same dimensions, and raise a ValueError if not
  • use an appropriate test for floating-point near-equality; that is, return True if, for every  i i and  j j abs((AB)ijIij)<tol abs((AB)ij−Iij)<tol, and Falseotherwise.
def check_inverse(a,b,tol= 0.1**8):	'''		function name:check_inverse		parameter:				a,b:2-dimensional square arrays				tol:tolerance		return:true of false	'''    if a.shape[0]!=a.shape[1] or b.shape[0] != b.shape[1] or a.shape[0] != b.shape[1]:        raise ValueError("the arrays should be square and have the same dimensions")    inverse_a = np.linalg.inv(a)    '''compare b and inverse_a'''    diff = np.subtract(b,inverse_a)        for i in range(0,a.shape[0]):        for j in range(0,a.shape[1]):            if diff[i][j] >=  tol:                return False    return True'''test case 1:#matrix1 = np.array([[2,3],[4,5]])#matrix2 = np.array([[-2.5,  1.5],[ 3. , -1. ]])''''''test case 2:'''matrix1 = np.array([[2,3],[4,5]])matrix2 = np.array([[-2.5,  1.5],[ 2. , -1. ]])flag = check_inverse(matrix1,matrix2)print flag
D.Define a function 
maxrows(a,m)
 that returns an array comprising all the 
rows
 in the array whose mean is greater than 
m
. If we have the usual 
a = np.arange(9).reshape((3,3))
 then the result of 
maxval(a,2.1)
 should be 
np.array([[3, 4, 5], [6, 7, 8]])
.
def maxrow(a,m):	'''		function name:maxrow		parameter:				a:2d-array				m:value		return:returns an array comprising all the rows in the array whose mean is greater than m	'''    mid = a.sum(axis=1)/2.0    res = []    for i in range(a.shape[0]):        if mid[i] > m:            res.append( a[i] )    return np.array(res)a = np.arange(12).reshape(4,3)print maxrow(a,7)
综合完整代码:
#!/usr/bin/python'''	filename:XXX_hw5.py	author:XXX	date:2016-03-12'''import numpy as npfrom numpy import randomdef array_sliceman(a):	'''		function name:array_sliceman		parameter:array-3d		return:returns a vector containing the sum of each slice of the first dimension	'''    tmp_array = a.sum(axis=2)    result = tmp_array.sum(axis=1)    return resultdef test_func_array_slicemean():    aa = np.arange(27).reshape((3,3,3))    res = array_sliceman(aa)    print resdef array_poly(a,x):	'''		function name:array_poly		parameter:				a:a 2-dimensional array				x:a scalar(floating point)		return:computes a vector of polynomials using each row as a separate set of coefficients	'''    result = []    for item in a:		'''reverse coefficients: turn \' a[i,0]*x**2 + a[i,1]*x + a[i,2]\' into \'a[i,0]+a[i,1]*x+a[i,2]*x**2\''''        item_reverse = item[::-1]         p = np.poly1d(item_reverse)        result.append( p(x) )	'''transfer list into numpy array and return'''    return np.array(result)     def test_func_array_poly():    bb = np.reshape( np.arange(9),(3,3) )    print array_poly(bb,2)def check_inverse(a,b,tol= 0.1**8):	'''		function name:check_inverse		parameter:				a,b:2-dimensional square arrays				tol:tolerance		return:true of false	'''    if a.shape[0]!=a.shape[1] or b.shape[0] != b.shape[1] or a.shape[0] != b.shape[1]:        raise ValueError("the arrays should be square and have the same dimensions")    inverse_a = np.linalg.inv(a)    '''compare b and inverse_a'''    diff = np.subtract(b,inverse_a)        for i in range(0,a.shape[0]):        for j in range(0,a.shape[1]):            if diff[i][j] >=  tol:                return False    return Truedef test_func_check_inverse(): '''test case 1:#matrix1 = np.array([[2,3],[4,5]])#matrix2 = np.array([[-2.5,  1.5],[ 3. , -1. ]])''''''test case 2:'''matrix1 = np.array([[2,3],[4,5]])matrix2 = np.array([[-2.5,  1.5],[ 2. , -1. ]])flag = check_inverse(matrix1,matrix2)print flagdef maxrow(a,m):	'''		function name:maxrow		parameter:				a:2d-array				m:value		return:returns an array comprising all the rows in the array whose mean is greater than m	'''    mid = a.sum(axis=1)/2.0    res = []    for i in range(a.shape[0]):        if mid[i] > m:            res.append( a[i] )    return np.array(res)def test_func_maxrows():    a = np.arange(12).reshape(4,3)    print maxrow(a,7)def main():	'''test the function array_sliceman'''    test_func_array_slicemean()	'''test the function array_poly'''    test_func_array_poly()	'''test the function check_inverse'''    test_func_check_inverse()	'''test the function maxrow'''    test_func_maxrows()if __name__ == "__main__":	'''the main function.the entry of the process'''    main()

Author:忆之独秀

Email:leaguenew@qq.com

注明出处:

转载地址:http://qpnpf.baihongyu.com/

你可能感兴趣的文章
Linux png转jpg (convert命令)
查看>>
NAS (Network Attached Storage 网络附属存储)
查看>>
Ubuntu更新后终端中字体的颜色全是白色
查看>>
Ninja
查看>>
opencv相关操作(cv2) (python)
查看>>
lmdb数据库的读取与转换(二) —— 数据集操作
查看>>
Lua语言
查看>>
Python sys.path和模块搜索路径
查看>>
Python内置类属性(__dict__,__doc__,__name__,__module__,__bases__,__file_)
查看>>
linux中source、sh、bash、./有什么区别
查看>>
vscode git
查看>>
基于MATLAB的二进制数字调制与解调信号的仿真——2FSK
查看>>
基于MATLAB的二进制数字调制与解调信号的仿真——2PSK
查看>>
基于MATLAB的模拟调制信号与解调的仿真——AM
查看>>
基于MATLAB的模拟调制信号与解调的仿真——DSB
查看>>
基于MATLAB的模拟调制信号与解调的仿真——SSB
查看>>
POJ - 2299 Ultra-QuickSort 求逆序对数(树状数组离散化/归并排序)
查看>>
操作系统实验之生产者和消费者程序
查看>>
操作系统实验之猴子过桥问题的模拟程序
查看>>
POJ - 3067 Japan (树状数组 思维)
查看>>