知识卡片
张量转数组需兼顾梯度设备形状
detach用于切断自动求导关联,转NumPy还须处理所在设备;squeeze不指定轴时可能把单样本批次压成标量。指标函数应检查预测与标签形状一致,避免广播把逐样本比较变成二维交叉比较。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 神经网络基础
原书出处 · 1 处
- · 查看原书依据
>>> def make_array(x): ... if hasattr(x, 'detach'): ... return torch.squeeze(x).detach().numpy() ... return x You use this utility function to measure the accuracy of each iteration on the tensors for your outputs (predictions): >>> def measure_binary_accuracy(y_pred, y): ... y_pred = make_array(y_pred).round() ... y = make_array(y).round() ... num_correct = (y_pred == y).sum() ... return num_correct / len(y) Now, you can rerun your training using this utility function
参考来源
- 位置:《Natural Language Processing in Action, Second Edition》第05章《神经网络基础》(来源项目:a19c7933-4eda-4176-aebd-30fe7e1ad292;源文件:extracted/Natural Language Processing in Action, Second Edition/_epub-src/OEBPS/Text/chapter-5.html)
- 结论依据:摘录中关于张量转数组需兼顾梯度设备形状的定义、比较或条件支撑卡片;原书表述不严谨的范围已在覆盖记录逐项限定,不把案例结果外推为普遍结论。
- 原始内容:>>> def make_array(x): ... if hasattr(x, 'detach'): ... return torch.squeeze(x).detach().numpy() ... return x You use this utility function to measure the accuracy of each iteration on the tensors for your outputs (predictions): >>> def measure_binary_accuracy(y_pred, y): ... y_pred = make_array(y_pred).round() ... y = make_array(y).round() ... num_correct = (y_pred == y).sum() ... return num_correct / len(y) Now, you can rerun your training using this utility function