Hi
Traceback (most recent calllast): File"/Users/chennan/pythonproject/dataanalysis/e.py", line 10, in <module> foo(5) # fails File"/Users/chennan/Desktop/2019/env/lib/python3.6/site-packages/enforce/decorators.py", line 104, in universal _args, _kwargs, _ = enforcer.validate_inputs(parameters) File"/Users/chennan/Desktop/2019/env/lib/python3.6/site-packages/enforce/enforcers.py", line 86, in validate_inputs raise RuntimeTypeError(exception_text) enforce.exceptions.RuntimeTypeError: The following runtime typeerrors were encountered: Argument 'text' was notoftype <class'str'>. Actual type was int.
使用@表示矩阵的乘法
下面我们实现一个最简单的ML模型——l2正则化线性回归(又称岭回归)
# l2-regularized linear regression: || AX - y ||^2 + alpha * ||x||^2 -> min
# Python 2 X = np.linalg.inv(np.dot(A.T, A) + alpha * np.eye(A.shape[1])).dot(A.T.dot(y)) # Python 3 X = np.linalg.inv(A.T @ A + alpha * np.eye(A.shape[1])) @ (A.T @ y)
@contextlib.contextmanager defreplace_print(): import builtins _print = print# saving old print function # or use some other function here builtins.print = lambda *args, **kwargs: _print('new printing', *args, **kwargs) yield builtins.print = _print
with replace_print(): print function>
虽然上面这段代码也能达到重写 print 函数的目的,但是不推荐使用。
print 可以参与列表理解和其他语言构造
# Python 3 result = process(x) if is_valid(x) elseprint('invalid item: ', x)
n_gifts = money // gift_price # correct for int and float arguments
nutshell
>>> from operator import truediv, floordiv >>> truediv.__doc__, floordiv.__doc__ ('truediv(a, b) -- Same as a / b.', 'floordiv(a, b) -- Same as a // b.') >>> (3 / 2), (3 // 2), (3.0 // 2.0) (1.5, 1, 1.0)
# Python 3.6+, how it *can* be done, not supported rightnowin pytorch model = nn.Sequential( conv1=nn.Conv2d(1,20,5), relu1=nn.ReLU(), conv2=nn.Conv2d(20,64,5), relu2=nn.ReLU()) )
可迭代对象拆包
类似于元组和列表的拆包,具体看下面的代码例子。
# handy when amount of additional stored info may vary between experiments, but the same code can be used in all cases model_paramteres, optimizer_parameters, *other_params = load(checkpoint_name)
# picking two last values from a sequence *prev, next_to_last, last = values_history
# This also works with any iterables, so if you have a function that yields e.g. qualities, # below is a simple way to take only last two values from a list *prev, next_to_last, last = iter_train(args)
x = dict(a=1, b=2) y = dict(b=3, d=4) # Python 3.5+ z = {**x, **y} # z = {'a': 1, 'b': 3, 'd': 4}, note that value for `b` is taken from the latter dict.