如何在Jupyter中使用bfloat16(bf16)?numpy及Python版本已更新
在Jupyter中使用bfloat16(bf16)的方法
最新版NumPy已经原生支持bfloat16类型,无需额外安装第三方库,直接在Jupyter中按以下方式操作即可:
1. 确认NumPy版本
先在Jupyter单元格中执行代码,确保使用的是支持bf16的NumPy版本(需1.20及以上,你提到的最新版肯定满足):
import numpy as np print(np.__version__)
2. 创建与使用bfloat16数组
直接创建bf16数组
# 直接指定dtype为bfloat16 bf16_array = np.array([3.14, 2.718, 1.618], dtype=np.bfloat16) print(bf16_array) print(bf16_array.dtype)
从其他数值类型转换
# 从float32转换为bf16 float32_array = np.array([10.5, -0.3], dtype=np.float32) bf16_converted = float32_array.astype(np.bfloat16) print(bf16_converted)
3. Jupyter环境注意事项
- 如果遇到
np.bfloat16未定义的情况,大概率是Jupyter内核未关联到安装了最新NumPy的Python环境。此时可以在Jupyter单元格中执行:
!pip install numpy --upgrade
然后重启Jupyter内核即可。
- bf16的精度仅为float32的一半(8位有效数字 vs 23位),运算时注意精度损失问题,适合对精度要求不高但追求性能/内存节省的场景。
4. 与深度学习框架配合(可选)
如果需要和PyTorch、TensorFlow等框架配合使用bf16,可直接进行类型转换:
PyTorch示例
import torch # 从NumPy bf16数组转换为PyTorch bf16张量 torch_bf16 = torch.tensor(bf16_array, dtype=torch.bfloat16)
TensorFlow示例
import tensorflow as tf # 创建TensorFlow bf16张量 tf_bf16 = tf.constant([1.0, 2.0], dtype=tf.bfloat16)
内容的提问来源于stack exchange,提问作者Nimasha Pilippange
相关产品推荐
相关产品推荐

