python - 如何在没有for循环的情况下进行元素比较和
问题描述
for 循环使我的程序非常慢。我会使用 np.sum(target==output) 但我需要输出中每一行的 argmax 值。我怎样才能加快速度?输出是张量数据类型
for i, x in enumerate(target):
if target[i] == torch.argmax(output[i]):
correct_class += 1
解决方案
np.argmax
您可以使用'参数对上述内容进行矢量化axis
,以获得跨行的最大值的索引:
(target==np.argmax(output, axis=1)).sum()
例如:
output = np.random.choice([0,1],(4,2))
print(output)
array([[1, 1],
[0, 1],
[0, 1],
[0, 1]])
target = np.array([[0,1,0,1]])
(target==np.argmax(output, axis=1)).sum()
# 3
推荐阅读
- android - 制作导航视图覆盖工具栏
- javascript - 使用html中的提交按钮重定向到基于单选按钮的网页
- orientdb - 无法在 Windows 中将 Orientdb 作为服务启动
- python - 尝试使用 Selenium-Python 选择菜单时出错
- json - 如何在 Flutter 中使用 http.post 并作为 String Json 对象发送
- python - 从网络驱动器复制所有文件
- linux - 我将如何在 Windows CMD 上执行此操作?
- powerbi - 我如何计算前一天的平均价格,按组过滤?
- r - 不带前导零的日期格式 - R
- mysql - 如何一次性将 40 亿条记录从 MySQL 加载到 SQL Server