官术网_书友最值得收藏!

Seeding random number generators and NumPy print options

For reproducible data analysis, we should prefer deterministic algorithms. Some algorithms use random numbers, but in practice we rarely use perfectly random numbers. The algorithms provided in numpy.random allow us to specify a seed value. For reproducibility, it is important to always provide a seed value but it is easy to forget. A utility function in sklearn.utils provides a solution for this issue.

NumPy has a set_printoptions() function, which controls how NumPy prints arrays. Obviously, printing should not influence the quality of your analysis too much. However, readability is important if you want people to understand and reproduce your results.

Getting ready

Install NumPy using the instructions in the Learning to log for robust error checking recipe. We will need scikit-learn, so have a look at http://scikit-learn.org/dev/install.html (retrieved July 2015). I have installed scikit-learn 0.16.1 via Anaconda.

How to do it...

The code for this example is in the configure_numpy.py file in this book's code bundle:

from sklearn.utils import check_random_state
import numpy as np
from dautil import options
from dautil import log_api

random_state = check_random_state(42)
a = random_state.randn(5)

random_state = check_random_state(42)
b = random_state.randn(5)

np.testing.assert_array_equal(a, b)

printer = log_api.Printer()
printer.print("Default options", np.get_printoptions())

pi_array = np.pi * np.ones(30)
options.set_np_options()
print(pi_array)

# Reset
options.reset_np_options()
print(pi_array)

The highlighted lines show how to get a NumPy RandomState object with 42 as the seed. In this example, the arrays a and b are equal, because we used the same seed and the same procedure to draw the numbers. The second part of the preceding program uses the following functions I defined in options.py:

def set_np_options():
    np.set_printoptions(precision=4, threshold=5,
                        linewidth=65)


def reset_np_options():
    np.set_printoptions(precision=8, threshold=1000,
                        linewidth=75)

Here's the output after setting the options:

[ 3.1416 3.1416 3.1416 ..., 3.1416 3.1416 3.1416] 

As you can see, NumPy replaces some of the values with an ellipsis and it shows only four digits after the decimal sign. The NumPy defaults are as follows:

'Default options'
{'edgeitems': 3,
 'formatter': None,
 'infstr': 'inf',
 'linewidth': 75,
 'nanstr': 'nan',
 'precision': 8,
 'suppress': False,
 'threshold': 1000}

See also

主站蜘蛛池模板: 无为县| 申扎县| 厦门市| 贺兰县| 宜丰县| 宝坻区| 四会市| 云龙县| 中阳县| 开江县| 泽库县| 涿州市| 南投市| 城市| 菏泽市| 宾阳县| 伊通| 扶风县| 康平县| 武平县| 泗水县| 剑阁县| 塔城市| 唐山市| 章丘市| 金坛市| 晋中市| 安多县| 濉溪县| 庆元县| 阜城县| 洮南市| 紫阳县| 娱乐| 巴东县| 和林格尔县| 太保市| 寿阳县| 哈巴河县| 定结县| 宜良县|