deep-learning - ```predictions[a > 0.5] = 1``` 和 ```acc = np.mean(predictions == y)``` 是什么意思?
问题描述
我是 python 编程的新手。我正在研究深度学习算法。我从未在 c 或 c++ 程序中见过这种类型的行。
线条predictions[a > 0.5] = 1
和acc = 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}%')
谢谢你
解决方案
一般来说,不知道更多是不可能说的,因为[]
只是调用一个方法,可以在任何类上定义:
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]
where b
is 相同大小的布尔数组将生成一个数组,该数组仅包含其中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.5
为1
.
至于你想知道的另一行,逻辑==
类似于>
上面的:predictions == y
将给出一个布尔数组,告诉哪里predictions
和y
重合。
然后将该数组传递给np.mean
,计算其参数的算术平均值。你怎么得到平均值[True, False, False, False, True]
呢?通过强迫他们浮动!float(True)
是1.0
;float(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
是黄金数据)。
推荐阅读
- python - Protobuf 定义一个可以是 int 或 float 的字段
- angular - 选择动画不适用于 Angular (7) 材质选项卡
- mongo-cxx-driver - 如何通过mongocxx比较mongodb中的“_id”?
- java - 如何使用opencv在代理后面捕获视频
- android - Kivy:在android上播放声音,没有延迟
- java - 在 SOAPUI 工具的密钥库中找不到私钥
- highcharts - highchart tooltip hover - 在繁忙的图表上,工具提示在点之间跳转
- c# - 为单个控件定制 Mahapps.Metro CustomValidationPopup 的样式(不适用于整个应用程序/窗口)
- php - 自定义 ocmod 修改在 opencart 版本 3.0.2.0 中不起作用
- java - Apache Nifi 属性描述符的动态修改类路径()的 Hello World 程序不起作用