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

Python报错:Object arrays are not currently supported 问题求助

解决TypeError: Object arrays are not currently supported问题

这个错误的核心原因很明确:你创建的三个数组长度不匹配,导致numpy无法生成统一的数值型二维数组,只能创建object类型的数组,而矩阵乘法运算符@不支持这种类型的数组。

咱们拆解下你的代码问题:

  • h_column1_formula = np.repeat(1, 10) 生成了一个长度为10的数组
  • 但for maturity in range(1,10)只循环了9次(maturity取值1到9),所以h_column2_formula_array和h_column3_formula_array的长度都是9

当你尝试把这三个数组转置拼接成h_matrix时,numpy因为子数组长度不一致,只能生成一个元素为小数组的object数组——这种数组没法进行矩阵乘法操作,自然就抛出了那个错误。

修复方案

有两种直接的修复思路,选哪种取决于你实际需要的样本数量:

方案1:让所有数组长度统一为10

把循环的范围改成range(1,11),这样h_column2和h_column3也会生成10个元素,和h_column1匹配:

import numpy as np
import math

time_decay_parameter = 0.055

h_column1_formula = np.repeat(1, 10)
h_column2_formula = []
h_column3_formula = []

# 调整循环范围为1到11,生成10个元素
for maturity in range(1,11):
    term = (1 - math.exp(-time_decay_parameter * maturity)) / (time_decay_parameter * maturity)
    h_column2_formula.append(term)
    h_column3_formula.append(term - math.exp(-time_decay_parameter * maturity))

h_column2_formula_array = np.asarray(h_column2_formula)
h_column3_formula_array = np.asarray(h_column3_formula)

h_matrix = np.array([h_column1_formula, h_column2_formula_array, h_column3_formula_array]).T
print(h_matrix)
ht_h = h_matrix.T @ h_matrix
print(ht_h)

方案2:让所有数组长度统一为9

如果你确实只需要9个样本,那就调整h_column1的长度:

# 把原来的10改成9
h_column1_formula = np.repeat(1, 9)

进阶优化:用numpy向量化替代循环

numpy的优势就是向量化操作,完全可以去掉循环,让代码更高效简洁,同时还能从根源上避免长度不匹配的问题:

import numpy as np

time_decay_parameter = 0.055
# 生成1到10的数组(根据需要调整长度)
maturities = np.arange(1, 11)

h_column1_formula = np.ones_like(maturities)
exp_term = np.exp(-time_decay_parameter * maturities)
h_column2_formula_array = (1 - exp_term) / (time_decay_parameter * maturities)
h_column3_formula_array = h_column2_formula_array - exp_term

# 用column_stack更直观地拼接列
h_matrix = np.column_stack([h_column1_formula, h_column2_formula_array, h_column3_formula_array])
print(h_matrix)
ht_h = h_matrix.T @ h_matrix
print(ht_h)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:54:31