本文共 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:
ValueError
if notTrue
if, for every i i and j j, abs((AB)ij−Iij)<tol abs((AB)ij−Iij)<tol, and False
otherwise.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
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/