python - 如何解决 ValueError: Expected 2D array, got scalar array instead of error in python?
问题描述
我有一个 nX2 维数组,并且定义了一些 HMM 模型。现在,对于存在的每个 HMM 模型,我正在尝试计算 nx2 数组中存在的每个值的对数似然值。为此,我使用 hmmlearn 包中的 score 函数
链接:https ://hmmlearn.readthedocs.io/en/latest/api.html#hmmlearn.base._BaseHMM.score
作为参考,这些是我编写的代码:
定义 HMM 模型之一:
HMMmodel = hmm.GaussianHMM(n_components=3, covariance_type="full", n_iter=10)
HMMmodel.fit(Sdata2)
HMMpredict = HMMmodel.predict(Sdata2)
HMMmodel.transmat_
然后,与 Score 函数一起使用的数据集:
[[-1.72914138 -1.63633714]
[-1.72914138 -1.63633714]
[-1.69620469 -1.63633714]
...
[-1.72226929 -1.63633714]
[-1.71539655 -1.63633714]
[-1.72914138 -1.63633714]]
查找分数的代码:
score1 = list()
score2 = list()
score3 = list()
score4 = list()
for x in np.nditer(Sdata3):
score1.append(HMMmodel.score(x))
score2.append(HMMmodel2.score(x))
score3.append(HMMmodel3.score(x))
score4.append(HMMmodel4.score(x))
正是在这一点上遇到了错误:
ValueError: Expected 2D array, got scalar array instead:
array=-1.7291413774395343.
我在这个网站上阅读了一些类似的问题,并尝试使用 (-1,1) 和 (1,-1) 重塑我的数组,但它会产生相同的错误。
任何解决错误的技术将不胜感激。谢谢!
解决方案
好的,我想我已经解决了这个问题。
我所做的是从数据集中取出一个 [1x2] 序列,然后使用 reshape 函数将其转换为 [2x1] 序列。转换后,score 函数接受了它,程序运行顺利。
这是修改后的代码:
score1 = list()
score2 = list()
score3 = list()
score4 = list()
for x in Sdata3:
y = np.reshape(x, (2,1))
score1.append(HMMmodel.score(y))
score2.append(HMMmodel2.score(y))
score3.append(HMMmodel3.score(y))
score4.append(HMMmodel4.score(y))
我希望这可以帮助任何面临类似问题的人。
推荐阅读
- php - 如何单击提交按钮立即更新 MySQL 并重新加载 php 中的表格内容?
- c# - WPF Wrap ListView 或 Grid DataTable
- reactjs - 从同级 React 组件中的表单提交刷新一个子 React 组件
- javascript - 如何让标题在网页上只淡出一次(添加 java 脚本类)
- spring-boot - Spring Cloud Consul 和 Consul Clients dockerized
- nested - 如何根据分组值嵌套 kusto 查询
- nativescript - 如何在 nativescript 中使用 css 关键帧添加波纹效果
- php - 不包括周末的小时数
- jquery - 使用对象操作将多条记录合并为一条
- python - 到同一 DF 中最近点的距离