【问题标题】:Comparing floating point numbers in python比较python中的浮点数
【发布时间】:2022-01-14 17:22:13
【问题描述】:

我一直在尝试用 python 编写一个神经网络,但我已经在这部分卡住了一段时间。我有这个代码:

import numpy as np

np.random.seed(0)

X = [[1.0, 2.0, 3.0, 2.5],
          [2.0, 5.0, -1.0, 2.0],
          [-1.5, 2.7, 3.3, -0.8]]

class Layer:
    def __init__ (self, inputCount, neronCount):
        self.weights = 0.10 * np.random.randn(inputCount, neronCount)
        self.biases = np.zeros((1, neronCount))
    def forward(self, inputs):
        self.output = np.dot(inputs, self.weights) + self.biases


layer1 = Layer(4, 5)
layer2 = Layer(5, 2)

layer1.forward(X)
layer2.forward(layer1.output)

print(layer2.output)

这个输出:

[[ 0.148296   -0.08397602]
 [ 0.14100315 -0.01340469]
 [ 0.20124979 -0.07290616]]

所以我创建了一个数组Y,将其用作预期输出,以便比较它们。对于测试建议,我将预期输出设置为实际输出,以便我知道它有效。

Y = np.array([[0.148296,   -0.08397602],
 [0.14100315, -0.01340469],
 [0.20124979, -0.07290616]])

我还想比较每个变量,这样我就可以知道他们错了多少 但是当我比较它们时

for i in range (0, 3):
    for j in range(0, 2):
        if np.asarray(layer2.output[i, j], dtype=np.float32) == Y[i, j]:
            print("TEST")

当它应该输出TEST 3 次时,它什么也不输出。 有什么建议吗?

整个脚本:

import numpy as np

np.random.seed(0)

X = [[1.0, 2.0, 3.0, 2.5],
          [2.0, 5.0, -1.0, 2.0],
          [-1.5, 2.7, 3.3, -0.8]]

Y = np.array([[0.148296,   -0.08397602],
 [0.14100315, -0.01340469],
 [0.20124979, -0.07290616]])

class Layer:
    def __init__ (self, inputCount, neronCount):
        self.weights = 0.10 * np.random.randn(inputCount, neronCount)
        self.biases = np.zeros((1, neronCount))
    def forward(self, inputs):
        self.output = np.dot(inputs, self.weights) + self.biases


layer1 = Layer(4, 5)
layer2 = Layer(5, 2)

layer1.forward(X)
layer2.forward(layer1.output)

print(layer2.output)

for i in range (0, 3):
    for j in range(0, 2):
        if np.asarray(layer2.output[i, j], dtype=np.float32) == Y[i, j]:
            print("TEST")

【问题讨论】:

标签: python arrays numpy neural-network


【解决方案1】:
for i in range(0, 3):
    for j in range(0, 2):
        if layer2.output[i][j] - Y[i][j] <= 1e-13:
            print("TEST")

您应该允许像 1e-13 这样的相对错误值,因为它们是浮点数,无法通过 == 运算符进行精确比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多