Removing infinity values of a function using exception handling, *args, and **kwargs
我目前正在阅读Joel Grus的《数据科学》一书,我遇到了一个我不太理解的功能:
1 2 3 4 5 6 7 | def safe(f): def safe_f(*args, **kwargs): try: return f(*args, **kwargs) except: return float('inf') return safe_f |
在梯度下降算法中调用安全函数来删除无穷大的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def minimize_batch(target_fn, gradient_fn, theta_0, tolerance=0.000001): step_sizes = [100, 10, 1, 0.1, 0.001, 0.0001, 0.00001] theta = theta_0 target_fn = safe(target_fn) value = target_fn(theta) while True: gradient = gradient_fn(theta) next_thetas = [step(theta, gradient, -step_size) for step_size in step_sizes] next_theta = min(next_thetas, key=target_fn) next_value = target_fn(next_theta) if abs(value - next_value) < tolerance: return theta else: theta, value = next_theta, next_value |
我知道保险箱在做什么,但我不明白它是怎么做的。例如,如果没有目标的输入,SAFE如何评估目标的价值?安全的做法是什么?它知道如何删除无穷大的值?
撇开梯度下降不谈,这个安全函数是否适用于在很多地方都没有定义的疯狂函数?
如果我们逐步替换变量名,可能有助于您理解:
1 | target_fn = safe(target_fn) |
指
1 2 3 4 5 6 7 | def safe(target_fn): def safe_f(*args, **kwargs): try: return target_fn(*args, **kwargs) except: return float('inf') return safe_f |
还有:
1 | target_fn = safe_f |
也就是说,我们将最初绑定到
所以这些参数是通过
1 | next_value = target_fn(next_theta) |
决定:
1 2 3 4 5 | def safe_f(next_theta): try: return target_fn(next_theta) except: return float('inf') |
也就是说,用参数
would this
safe function work on a crazy functions that was undefined at uncountably many places?
因为它使用