你的实际值有界[-0.05, 0.05)
吗?
当我最初构建一个示例数据集来查看您的问题时,我在[0,1]
. (a,b,c)
当我这样做时,我也得到了与您观察到的相同的结果——对于每个序列,对于第六个条目,总是最大值,并且总是相同的预测类。但是考虑到我的数据分布(均匀分布在0
和之间)比第六个条目(在和之间)1
的网格搜索值具有更大的集中趋势,因此 HMM 总是选择最高值三元组是有道理的,因为那是最接近它训练过的分布的主要密度。-.05
.05
(.04,.04,.04)
[-0.05,0.05)
当我重新构建数据集时,在我们允许第六个条目O_t+1
(从您的示例数据来看,您似乎确实至少有正值和负值,但您可以尝试绘制每个特征的分布,看看您可能的第六项值范围是否都合理。
这是一些示例数据和评估代码。每当有一个新的最佳(a,b,c)
序列时,或者当第 6 次观察的预测发生变化时,它都会打印出一条消息(只是为了表明它们并不完全相同)。每个 6 元素序列的最高可能性以及预测和最佳第 6 个数据点存储在best_per_span
.
首先,构建一个样本数据集:
import numpy as np
import pandas as pd
dates = pd.date_range(start="01-01-2001", end="31-12-2001", freq='D')
n_obs = len(dates)
n_feat = 3
values = np.random.uniform(-.05, .05, size=n_obs*n_feat).reshape((n_obs,n_feat))
df = pd.DataFrame(values, index=dates)
df.head()
0 1 2
2001-01-01 0.020891 -0.048750 -0.027131
2001-01-02 0.013571 -0.011283 0.041322
2001-01-03 -0.008102 0.034088 -0.029202
2001-01-04 -0.019666 -0.005705 -0.003531
2001-01-05 -0.000238 -0.039251 0.029307
现在分成训练集和测试集:
train_pct = 0.7
train_size = round(train_pct*n_obs)
train_ix = np.random.choice(range(n_obs), size=train_size, replace=False)
train_dates = df.index[train_ix]
train = df.loc[train_dates]
test = df.loc[~df.index.isin(train_dates)]
train.shape # (255, 3)
test.shape # (110, 3)
在训练数据上拟合三态 HMM:
# hmm throws a lot of deprecation warnings, we'll suppress them.
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=DeprecationWarning)
# in the most recent hmmlearn we can't import GaussianHMM directly anymore.
from hmmlearn import hmm
mdl = hmm.GaussianHMM(n_components=3, covariance_type='diag', n_iter=1000)
mdl.fit(train)
现在网格搜索最佳第 6 个 ( t+1
) 观察:
# length of O_t
span = 5
# final store of optimal configurations per O_t+1 sequence
best_per_span = []
# update these to demonstrate heterogenous outcomes
current_abc = None
current_pred = None
for start in range(len(test)-span):
flag = False
end = start + span
first_five = test.iloc[start:end].values
output = []
for a in np.arange(-0.05,0.05,.01):
for b in np.arange(-0.05,0.05,.01):
for c in np.arange(-0.05,0.05,.01):
sixth = np.array([a, b, c])[:, np.newaxis].T
all_six = np.append(first_five, sixth, axis=0)
output.append((mdl.decode(all_six), (a,b,c)))
best = max(output, key=lambda x: x[0][0])
best_dict = {"start":start,
"end":end,
"sixth":best[1],
"preds":best[0][1],
"lik":best[0][0]}
best_per_span.append(best_dict)
# below here is all reporting
if best_dict["sixth"] != current_abc:
current_abc = best_dict["sixth"]
flag = True
print("New abc for range {}:{} = {}".format(start, end, current_abc))
if best_dict["preds"][-1] != current_pred:
current_pred = best_dict["preds"][-1]
flag = True
print("New pred for 6th position: {}".format(current_pred))
if flag:
print("Test sequence StartIx: {}, EndIx: {}".format(start, end))
print("Best 6th value: {}".format(best_dict["sixth"]))
print("Predicted hidden state sequence: {}".format(best_dict["preds"]))
print("Likelihood: {}\n".format(best_dict["nLL"]))
循环运行时报告输出示例:
New abc for range 3:8 = [-0.01, 0.01, 0.0]
New pred for 6th position: 1
Test sequence StartIx: 3, EndIx: 8
Best 6th value: [-0.01, 0.01, 0.0]
Predicted hidden state sequence: [0 2 2 1 0 1]
Likelihood: 35.30144407374163
New abc for range 18:23 = [-0.01, -0.01, -0.01]
New pred for 6th position: 2
Test sequence StartIx: 18, EndIx: 23
Best 6th value: [-0.01, -0.01, -0.01]
Predicted hidden state sequence: [0 0 0 1 2 2]
Likelihood: 34.31813078939214
示例输出best_per_span
:
[{'end': 5,
'lik': 33.791537281734904,
'preds': array([0, 2, 0, 1, 2, 2]),
'sixth': [-0.01, -0.01, -0.01],
'start': 0},
{'end': 6,
'lik': 33.28967307589143,
'preds': array([0, 0, 1, 2, 2, 2]),
'sixth': [-0.01, -0.01, -0.01],
'start': 1},
{'end': 7,
'lik': 34.446813870838156,
'preds': array([0, 1, 2, 2, 2, 2]),
'sixth': [-0.01, -0.01, -0.01],
'start': 2}]
除了报告元素之外,这对您的初始方法没有重大改变,但它似乎确实按预期工作,而不会每次都达到最大值。