我正在尝试使用贝叶斯方法解决分类模型。特别是我使用以下工作作为参考:Modeling Analysts’ Recommendations via Bayesian Machine Learning
监督学习问题包括分析师在给定时间段内对大量股票的推荐数据集。每一行代表给定日期的给定股票,而每一列(我们称之为特征)代表给定的经纪人。该表填充了给定日期内给定股票的经纪人推荐,分为 4 个类别:
<块引用>数据集还包含一个由 3 个类组成的标签向量:
<块引用>由于数据集的大部分 99% 由缺失数据(零)组成,因此该分类问题适用于贝叶斯方法。
让我们重现数据的简化版本:
import pandas as pd
import numpy as np
index = pd.Index(range(100))
columns = ['B1', 'B2', 'B3', 'B4', 'B5']
recommendations = pd.DataFrame(np.random.randint(0, 4, size=(len(index), len(columns))), index=index,
columns=columns)
label = pd.DataFrame(np.random.randint(0,3, size=(len(index), 1)), index=index, columns=['label'])
df = recommendations.join(label)
df
B1 B2 B3 B4 B5 label
0 0 0 2 1 3 0
1 3 2 0 2 2 2
2 1 3 3 3 3 2
3 0 1 3 3 2 1
4 1 1 1 0 0 0
.. .. .. .. .. .. ...
95 3 2 0 2 3 1
96 2 0 2 0 1 2
97 3 0 3 1 0 0
98 1 2 3 0 3 0
99 3 2 1 0 0 1
我们假设行和列之间都是独立的。概率设置如下:我们假设标签概率为 k={k0, k1, k2} 并且具有参数 V=( v0、v1、v2)。对于每个经纪人,我们有 4 个不同的概率以 3 个标签类别为条件:Bk|T=t, t=0,1,2, Pr(Bk|T=t)=Pi_tk(对于每个经纪人,以我们拥有的每个事实为条件4 个概率)并假设每个 Bk 是一个四维狄利克雷分布,参数为 {a0, a1, a2, a3}。在我们的简化框架中,我们有 5(broker)x4(classes Recommendation)x3(classes label)=60 个参数。我们将模型的所有参数设置为 1。
现在,我想将数据库分成一个训练集,我观察特征和标签,以及一个测试集,我观察经纪人推荐,我想对标签类别进行预测。
train = df[df.index < 70]
test = df[df.index >=70]
我正在努力执行的任务是使用库 bayespy
为该框架构建合适的模型。我们可以将问题表示如下:
其中 A0 包含经纪人预测的狄利克雷分布的所有 3x5 四维超参数,V 是标签类别的狄利克雷分布的三维超参数,Pi 是经纪人推荐的 3x5 4D-狄利克雷随机变量, K 是标签类别的 3D-Dirichlet 随机变量,T=t_j 是在 Trining 期间观察到的分类标签类别,但必须在测试期间推断出来,B_kj 是在 Trining 和测试期间观察到的分类经纪人推荐。
我构建了以下模型:
import numpy as np
from bayespy import nodes
from bayespy.nodes import Mixture, Categorical
K = nodes.Dirichlet(np.ones(3), name='K')
T = nodes.Categorical(K, plates=(len(train),))
Pi = nodes.Dirichlet(np.ones(4), plates=(3,5), name='Pi') # four classes, one rv for each of the 3 truth, 5 brokers
B = Mixture(T, Categorical, Pi)
但在这里我得到了错误:
<块引用>不会自动从 CategoricalMoments 转换为具有不同类别数量的 CategoricalMoments
我会继续如下:
from bayespy.inference import VB
Q = VB(T, K, B, Pi)
Pi.initialize_from_prior()
K.initialize_from_prior()
B.observe(train[train.columns[:-1]])
T.observe(train.label)
Q.update(repeat=1000)
我知道我在构建模型时做错了,但经过多次试验后,我无法达到合适的设置。而且,我在网上搜索了一些关于分类混合模型构建的例子,但我没有找到类似的东西。
任何帮助将不胜感激。