行“预测[a> 0.5] = 1”和“ acc = np.mean(预测== y)”是什么意思?

时间:2019-09-18 08:59:12

标签: deep-learning

我是python编程的新手。我正在研究深度学习算法。我从未在c或c ++程序中见过这些类型的行。 predictions[a > 0.5] = 1acc = np.mean(predictions == y)行是什么意思?

def predict(x, w, b):
    a = sigmoid( w.T @ x + b)
    predictions =  np.zeros_like(a) 
    predictions[a > 0.5] = 1
    return predictions

def test_model(x, y, w, b):
    predictions = predict(x, w, b)
    acc = np.mean(predictions == y)
    acc = np.asscalar(acc)
    return acc

def main():
    x, y = load_train_data()
    x = flatten(x)
    x = x/255. # normalize the data to [0, 1]

    print(f'train accuracy: {test_model(x, y, w, b) * 100:.2f}%')

    x, y = load_test_data()
    x = flatten(x)
    x = x/255. # normalize the data to [0, 1]

    print(f'test accuracy: {test_model(x, y, w, b) * 100:.2f}%')

谢谢

1 个答案:

答案 0 :(得分:0)

通常来说,不了解更多信息就很难说了,因为[]只是在调用一个方法,该方法可以在任何类上定义:

class Indexable:
    def __getitem__(self, index):
        if index:
            return "Truly indexed!"
        else:
            return "Falsely indexed!"

predictions = Indexable()
a = 0.7
predictions[a > 0.5]
# => 'Truly indexed!'

运算符>也是如此。


但是,从上下文来看,predictionsa可能都是相同大小的numpy数组,并且a包含数字。

a > .5将产生另一个与a相同大小的数组,其中元素为False或更小,元素为.5的{​​{1}}比True

.5,其中predictions[b]是相同大小的布尔数组,将产生一个仅包含b为True的元素的数组:

b

索引分配相似,仅在索引数组中的对应元素为predictions = np.array([1, 2, 3, 4, 5]) b = [True, False, False, False, True] predictions[b] # => array([1, 5]) 的情况下设置值:

True

因此,您想知道的那一行是将所有predictions[b] = 17 predictions # => array([17, 2, 3, 4, 17]) (对应的predictions位于a上方的0.5设置为1


对于您想知道的另一行,==的逻辑类似于上面的>的逻辑:predictions == y将给出一个布尔数组,告诉{{1} }和predictions重合。

此数组然后传递到y,后者计算其参数的算术平均值。不过,您如何平均获得np.mean?通过强迫他们漂浮! [True, False, False, False, True]float(True)1.0float(False)。因此,布尔列表的平均值基本上可以告诉您正确元素的比例:0.0np.mean([True, False, False, True])相同,得出np.mean([1.0, 0.0, 0.0, 0.0, 1.0])的结果(或40%的元素为{ {1}}。

因此,您的行计算出0.4的哪个比例与True相同(换句话说,假设predictions是黄金数据,则预测的准确性)。