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

Deep learning “预测[a>;0.5]=1”和“acc=np.mean(预测==y)”这两行的意思是什么?,deep-learning,Deep Learning,我是python编程新手。我正在研究深度学习算法。我从未见过C或C++程序中的这些类型的行。 行预测[a>0.5]=1和acc=np.平均值(预测==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,

我是python编程新手。我正在研究深度学习算法。我从未见过C或C++程序中的这些类型的行。
预测[a>0.5]=1
acc=np.平均值(预测==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}%')

谢谢你

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

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
元素小于等于
.5
,而
True
元素大于
.5

predictions[b]
其中
b
是相同大小的布尔数组,将生成一个仅包含
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])
因此,您想知道的是将所有
预测设置为
1,其中相应的
a
超过
0.5


至于你想知道的另一行,
==
的逻辑与上面的
类似:
预测==y
将给出一个布尔数组,告诉
预测和
y
在哪里重合

然后将该数组传递给
np.mean
,它计算其参数的算术平均值。但是,如何获得
[True,False,False,True]
的平均值?强迫他们上浮<代码>浮点(真)
1.0
<代码>浮点(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


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

搜索
numpy
教程并在那里花费一些时间。它将帮助您理解上述代码