You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决NumPy v1.24中broadcast_arrays的FutureWarning警告?

缓解NumPy v1.24中broadcast_arrays的FutureWarning方法

问题场景

运行以下代码时,NumPy v1.24会抛出FutureWarning:

import numpy as np
x = np.array(0)
y = np.array([1, 2, 3])
x_, y_ = np.broadcast_arrays(x, y)

print(x_.flags.writeable)
# 触发警告:FutureWarning: future versions will not create a writeable array from broadcast_array. Set the writable flag explicitly to avoid this warning.

警告原因

从NumPy v1.24开始,np.broadcast_arrays()默认生成的广播数组是否可写的行为会在后续版本中改变——未来版本默认不会创建可写的广播数组,因此需要显式指定writable参数来明确需求。

解决方法

根据实际需求选择对应方式:

  • 如果需要可写的广播数组:调用broadcast_arrays时显式设置writable=True

    import numpy as np
    x = np.array(0)
    y = np.array([1, 2, 3])
    # 显式指定可写
    x_, y_ = np.broadcast_arrays(x, y, writable=True)
    
    print(x_.flags.writeable)  # 输出True,无警告
    
  • 如果不需要可写的广播数组:显式设置writable=False,符合未来版本的默认行为

    import numpy as np
    x = np.array(0)
    y = np.array([1, 2, 3])
    # 显式指定不可写
    x_, y_ = np.broadcast_arrays(x, y, writable=False)
    
    print(x_.flags.writeable)  # 输出False,无警告
    

若只是临时屏蔽该警告(不推荐,建议优先显式指定参数),可使用np.warnings.filterwarnings:

import numpy as np
# 针对具体警告信息屏蔽
np.warnings.filterwarnings("ignore", message="future versions will not create a writeable array from broadcast_array")

x = np.array(0)
y = np.array([1, 2, 3])
x_, y_ = np.broadcast_arrays(x, y)

print(x_.flags.writeable)

内容的提问来源于stack exchange,提问作者ndou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:47:07