1.問題描述
在使用numpy的時候,我們經常在debug的時候將numpy數組打印下來,但是有的時候數組里面都是小數,數組又比較大,打印下來的時候非常不適合觀察。這里主要講一下如何讓numpy打印的結果更加簡潔
2.問題解決
這里需要使用numpy的set_printoptions函數,對應numpy源碼如下所示:
def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None): """ Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed. Parameters ---------- precision : int, optional Number of digits of precision for floating point output (default 8). threshold : int, optional Total number of array elements which trigger summarization rather than full repr (default 1000). edgeitems : int, optional Number of array items in summary at beginning and end of each dimension (default 3). linewidth : int, optional The number of characters per line for the purpose of inserting line breaks (default 75). suppress : bool, optional Whether or not suppress printing of small floating point values using scientific notation (default False). nanstr : str, optional String representation of floating point not-a-number (default nan). infstr : str, optional String representation of floating point infinity (default inf). formatter : dict of callables, optional
這里我們主要用到其中的兩個屬性:
設置precision來控制小數點后面最多顯示的位數
設置suppress來取消使用科學計數法
2.1 簡單示例
一個簡單的利用set_printoptions的例子如下所示:
import numpy as npa = np.random.random(3)print('before set options: /n {}'.format(a))np.set_printoptions(precision=3, suppress=True)print('after set options: /n {}'.format(a))>>>before set options: [ 0.05856348 0.5417039 0.76520603]after set options: [ 0.059 0.542 0.765]
可以看到,設置了打印的options之后,打印下來的結果簡潔了很多,絕大多數時候我們只需要觀察簡潔的打印結果,太過精確的結果反而會因為占位太長不易于觀察
2.2完整示例
2.1的例子中存在的一個問題是,一旦我們在程序的某一行設置了printoptions之后,接下來所有的打印過程都會受到影響,然而有的時候我們并不希望如此,這個時候我們可以添加一個上下文管理器,只在規定的上下文環境當中設置我們需要的打印參數,其他地方仍然使用默認的打印參數,代碼如下:
import numpy as npfrom contextlib import contextmanager@contextmanagerdef printoptions(*args, **kwargs): original_options = np.get_printoptions() np.set_printoptions(*args, **kwargs) try: yield finally: np.set_printoptions(**original_options)x = np.random.random(3)y = np.array([1.5e-2, 1.5, 1500])print('-----------before set options-----------')print('x = {}'.format(x))print('y = {}'.format(y))with printoptions(precision=3, suppress=True): print('------------set options------------') print('x = {}'.format(x)) print('y = {}'.format(y))print('---------------set back options-------------')print('x = {}'.format(x))print('y = {}'.format(y))>>>-----------before set options-----------x = [ 0.3802371 0.7929781 0.14008782]y = [ 1.50000000e-02 1.50000000e+00 1.50000000e+03]------------set options------------x = [ 0.38 0.793 0.14 ]y = [ 0.015 1.5 1500. ]---------------set back options-------------x = [ 0.3802371 0.7929781 0.14008782]y = [ 1.50000000e-02 1.50000000e+00 1.50000000e+03]
新聞熱點
疑難解答