《Python数据分析基础教程:Numpy学习指南》- 速记 - 第八章

8.1 断言函数

numpy.testing包:
- assert_almost_equal 如果两个数字的近似程度没有达到指定精度,就抛出异常
- assert_approx_equal 如果两个数字的近似程度没有达到指定有效数字,就抛出异常
- assert_array_almost_equal 如果两个数组中元素的近似程度没有达到指定精度,就抛出异常
- assert_array_equal 如果两个数组对象不相同,就抛出异常
- assert_array_less 两个数组必须形状一致,并且第一个数组的元素严格小于第二个数组的元素,否则就抛出异常
- assert_equal 如果两个对象不相同,就抛出异常
- assert_raises 若用填写的参数调用函数没有抛出指定的异常,则测试不通过
- assert_warns 若没有抛出指定的警告,则测试不通过
- assert_string_equal 断言两个字符串变量完全相同
- assert_allclose 如果两个对象的近似程度超出了指定的容差限,就抛出异常

8.2 使用assert_almost_equal 断言近似相等

(1) 调用函数,指定较低的精度(小数点后7位):

print "Decimal 6", np.testing.assert_almost_equal(0.123456789, 0.123456780,decimal=7)
#output
Decimal 6 None

(2) 调用函数,指定较高的精度(小数点后8位):

print "Decimal 7", np.testing.assert_almost_equal(0.123456789, 0.123456780,decimal=8)

#output
Decimal 7
Traceback (most recent call last):
...
raiseAssertionError(msg)
AssertionError:
Arrays are not almost equal
ACTUAL: 0.123456789
DESIRED: 0.12345678

8.4 使用assert_approx_equal 断言近似相等

与assert_almost_equal 类似,以小数点后7位为分界点。

8.6 断言数组近似相等

assert_array_almost_equal函数将抛出异常。该函数首先检查两个数组的形状是否一致,然后逐一比较两个数组中的元素。
(1) 调用函数,指定较低的精度:

print "Decimal 8", np.testing.assert_array_almost_equal([0, 0.123456789], [0,
0.123456780], decimal=8)
#output
Decimal 8 None

print "Decimal 9", np.testing.assert_array_almost_equal([0, 0.123456789], [0,0.123456780], decimal=9)

#output
Decimal 9
Traceback (most recent call last):
...
assert_array_compare
raiseAssertionError(msg)
AssertionError:
Arrays are not almost equal
(mismateh 50.0%)
x: array([ 0. , 0.12345679])
y: array([ 0. , 0.12345678])

8.8 比较数组相等

(1) 调用assert_allclose函数:

print "Pass", np.testing.assert_allclose([0, 0.123456789, np.nan], [0, 0.123456780,np.nan], rtol=1e-7, atol=0)
#output
Pass None

(2) 调用assert_array_equal函数:

print "Fail", np.testing.assert_array_equal([0, 0.123456789, np.nan], [0, 0.123456780,np.nan])
#output
Fail
Traceback (most recent call last):
...
assert_array_compare
raiseAssertionError(msg)
AssertionError:
Arrays are not equal
(mismatch 50.0%)
x: array([ 0. ,0.12345679, nan]
y: array([ 0. ,0.12345678, nan])

8.10 核对数组排序

两个数组必须形状一致并且第一个数组的元素严格小于第二个数组的元素,否则assert_array_less函数将抛出异常。

print "Pass", np.testing.assert_array_less([0, 0.123456789, np.nan], [1, 0.23456780,np.nan])
#output
Pass None

8.12 比较对象

如果两个对象不相同,assert_equal函数将抛出异常。这里的对象不一定为NumPy数组,也可以是Python中的列表、元组或字典。

(1) 调用assert_equal函数:
print "Equal?", np.testing.assert_equal((1, 2), (1, 3))

#output
Equal?
Traceback (most recent call last):
...
raiseAssertionError(msg)
AssertionError:
Items are not equal:
item=1
ACTUAL: 2
DESIRED: 3

8.14 比较字符串

assert_string_equal函数断言两个字符串变量完全相同。如果测试不通过,将会抛出异常并显示两个字符串之间的差异。该函数区分字符大小写。

print "Fail", np.testing.assert_string_equal("NumPy", "Numpy")

#output
Fail
Traceback (most recent call last):
...
raiseAssertionError(msg)
AssertionError: Differences in strings:
- NumPy? ^
+ Numpy?

8.15 浮点数比较

浮点数在计算机中是以不精确的方式表示的,这给比较浮点数带来了问题。NumPy中的assert_array_almost_equal_nulp和assert_array_max_ulp函数可以提供可靠的浮点数比较功能。ULP是Unit of Least Precision的缩写,即浮点数的最小精度单位。根据IEEE 754标准,四则运算的误差必须保持在半个ULP之内。你可以用刻度尺来做对比。公制刻度尺的刻度通常精确到毫米,而更高精度的部分只能估读,误差上界通常认为是最小刻度值的一半,即半毫米。
机器精度(machine epsilon)是指浮点运算中的相对舍入误差上界。机器精度等于ULP相对于1的值。NumPy中的finfo函数可以获取机器精度。Python标准库也可以给出机器精度值,并应该与NumPy给出的结果一致。

8.16 使用assert_array_almost_equal_nulp 比较浮点数(略)

8.18 设置maxulp 并比较浮点数(略)

8.20 编写单元测试

import numpy as np
import unittest

def factorial(n):
    if n == 0:
        return 1
    if n < 0:
        raise ValueError, "Unexpected negative value"
    return np.arange(1, n+1).cumprod()

class FactorialTest(unittest.TestCase):
    def test_factorial(self):
    # 计算3的阶乘,测试通过
    self.assertEqual(6, factorial(3)[-1])
    np.testing.assert_equal(np.array([1, 2, 6]), factorial(3))

    def test_zero(self):
    # 计算0的阶乘,测试通过
    self.assertEqual(1, factorial(0))

    def test_negative(self):
    # 计算负数的阶乘,测试不通过
    # 这里应抛出ValueError异常,但我们断言其抛出IndexError异常
    self.assertRaises(IndexError, factorial(-10))

if _name_ == '_main_':
unittest.main()

8.21 nose 和测试装饰器

nose也是一种Python框架,使得(单元)测试更加容易。nose可以帮助你组织测试代码。根据nose的文档,任何能够匹配testMatch正则表达式(默认为(?:^|[b_.-])[Tt]est)的Python源代码文件、文件夹或库都将被收集用于测试。nose充分利用了装饰器(decorator)。Python装饰器是有一定含义的对函数或方法的注解。numpy.testing模块中有很多装饰器。

8.22 使用测试装饰器(略)

8.24 执行文档字符串测试

文档字符串(docstring)是内嵌在Python代码中的类似交互式会话的字符串。这些字符串可以用于某些测试,也可以仅用于提供使用示例。numpy.testing模块中有一个函数可以运行这些测试。

docstringtest.py

import numpy as np
def factorial(n):
    """
    Test for the factorial of 3 that should pass.
    >>> factorial(3)
    6
    Test for the factorial of 0 that should fail.
    >>> factorial(0)
    1
    """
return np.arange(1, n+1).cumprod()[-1]
>>>from numpy.testing import rundocs
>>>rundocs('docstringtest.py')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值