首页 > 解决方案 > ```predictions[a > 0.5] = 1``` 和 ```acc = np.mean(predictions == y)``` 是什么意思?

问题描述

我是 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}%')

谢谢你

标签: deep-learning

解决方案


一般来说,不知道更多是不可能说的,因为[]只是调用一个方法,可以在任何类上定义:

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!'

运算符也是如此>


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

a > .5将生成另一个a与元素相同或更小的数组,False其中元素大于..5True.5

predictions[b]where bis 相同大小的布尔数组将生成一个数组,该数组仅包含其中b为 True 的元素:

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.51.


至于你想知道的另一行,逻辑==类似于>上面的:predictions == y将给出一个布尔数组,告诉哪里predictionsy重合。

然后将该数组传递给np.mean,计算其参数的算术平均值。你怎么得到平均值[True, False, False, False, True]呢?通过强迫他们浮动!float(True)1.0float(False)0.0。因此,布尔列表的平均值基本上告诉您为真元素的比例:np.mean([True, False, False, True])与 相同np.mean([1.0, 0.0, 0.0, 0.0, 1.0]),给出0.4(或 40% 的元素为True)的结果。

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


推荐阅读