Python isinstance() 的 float 失败断言测试

标签 python python-3.x numpy precision isinstance

背景:
我已经完成了机器学习和神经网络的类(class),在接下来我遇到的问题中,我们需要计算成本函数。有两种方法可以实现此目的:应用 np.multiply 和 np.sum 或 np.dot。我在示例中分别将它们称为 cost1 和 cost2。它们产生相同的结果。

问题:
我的问题是该函数(已经为我完成)断言成本是使用 isinstance() 的 float 。第一种方法产生的值可以通过此测试,而第二种方法则不能。但是,当我打印这两个值及其关联的数据类型时,它们似乎都是 float ,尽管 cost2 具有更高的精度。为什么cost2断言测试失败?

代码:

def compute_cost(A2, Y, parameters):
    """ 
    Computes the cross-entropy cost given in equation (13)

    Arguments:
    A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)
    parameters -- python dictionary containing your parameters W1, b1, W2 and b2

    Returns:
    cost -- cross-entropy cost given equation (13)
    """

    m = Y.shape[1] # number of example

    # Compute the cross-entropy cost
    ### START CODE HERE ### (≈ 2 lines of code)
    logprobs = np.multiply(np.log(A2), Y)
    cost1 = -np.sum(logprobs)
    cost2 = -np.dot(np.log(A2), Y.T)
    ### END CODE HERE ###

    cost1 = np.squeeze(cost1)     # makes sure cost is the dimension we expect. 
    cost2 = np.squeeze(cost2)     # E.g., turns [[17]] into 17 


    # Troubleshooting
    print(cost1.dtype,cost2.dtype)
    print(cost1,cost2)

    assert(isinstance(cost1, float))
    assert(isinstance(cost2, float))

    return cost1


A2, Y_assess, parameters = compute_cost_test_case()
print("cost = " + str(compute_cost(A2, Y_assess, parameters)))

输出:

float64 float64
0.692685886972 0.6926858869721941
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-84-92a25de13cb3> in <module>()
  1 A2, Y_assess, parameters = compute_cost_test_case()
  2 
----> 3 print("cost = " + str(compute_cost(A2, Y_assess, parameters)))

<ipython-input-83-411aa6cb57b7> in compute_cost(A2, Y, parameters)
 30 
 31     assert(isinstance(cost1, float))
---> 32     assert(isinstance(cost2, float))
 33 
 34     return cost1

AssertionError: 

最佳答案

好吧,让我从头开始。

首先,这不是你问的问题,而是科学秘书处的问题。 np.dot()并不总是等于np.sum和np.multiply,理论上它们是相等的,但是就成本函数计算而言,它们不会相同,因为 np.dot 的计算因矩阵和向量而异,更不用说它会因为尺寸不匹配而给您带来错误。因此,为了安全起见,请使用乘法然后求和函数,您可以查看这篇文章以获取有关此事的更多信息。 Python implementation of the cost function in logistic regression: why dot multiplication in one expression but element-wise multiplication in another

第二,这是你原来的问题,要解决这个问题,你应该打印有关cost1和cost2的所有信息。
例如,使用 keepdims = True 计算成本方程后,您会发现 cost.shape = (), cost.dtype = float64type(cost) = numpy.ndarray 这是一个标量这就是你的问题
函数 squeeze 可以成功地进行降维,例如 [[.364]] 将是 .364。但是,.364 将是 numpy.ndarray 类型。

因此,要从标量转换为 float ,您可以这样做

解决方案:

cost = np.asscalar(cost)    # make sure to convert scalar with shape () to normal float

因此,你的断言肯定会正常工作

您可以查看这个问题How to convert singleton array to a scalar value in Python?还有这个What is a ndarray of shape () returned after np.squeeze from shape (1,1)?

关于Python isinstance() 的 float 失败断言测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49392396/

相关文章:

python - Python 会停止无限循环 "for"吗?

python - 不能继承timedelta

python-3.x - 返回表情符号名称而不是表情符号

python-3.x - 在 Windows 上的 python 3 上安装斜纹布的问题。

python - 整行 Numpy 数组索引操作可以被 cythonized 吗?

python - 使用 python 向 aspx 页面提交查询并抓取结果?

python - 在 Ubuntu 上的 Python 3 中使用 Pip 并导入包

python - 计算 TSV 文件中所有其他点之间的距离?

python - 如何循环和访问 OpenERP 中字段的值?

Python:循环遍历两个向量的值