Python中 assert断言声明,遇到错误则立即返回

版权声明:转载请说明链接~~~ https://blog.csdn.net/weixin_40546602/article/details/89407713

在使用python语言开发深度学习模型时,经常会遇到模型运行结束时才会发现的崩溃状态,或者得到的结果不是预想的那样。这就需要在模型中善于使用assert语句,来判断某些变量的类型或者shape等是否满足要求。

用法为 :

assert expression(你想判断的内容)

# 等价于
if not expression:
    raise AssertionError

例如:在逻辑回归中,z = W的转置*X,样本X含有五个特征,则我们在设置W时。要一直保证其shape为[5,1]


>>> import numpy as np
>>> w = np.zeros((5,1))
>>> w
array([[0.],
       [0.],
       [0.],
       [0.],
       [0.]])
>>> assert(w.shape == (5,1))
>>> assert(w.shape == (2,1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

猜你喜欢

转载自blog.csdn.net/weixin_40546602/article/details/89407713
今日推荐