我正在尝试修改example from Infer.NET以使其更灵活。我希望能够发送任意数量的指标来进行预测。
我创建了以下包装类(非常接近原始示例):
class Inference
{
private readonly List<List<double>> _pastMetrics = new List<List<double>>();
public void AddPastMetrics(List<double> pastMetrics)
{
_pastMetrics.Add(pastMetrics);
}
private readonly List<Boolean> _pastResults = new List<Boolean>();
public void AddPastResults(Boolean pastResults)
{
_pastResults.Add(pastResults);
}
private readonly List<List<double>> _testMetrics = new List<List<double>>();
public void AddTestMetrics(List<double> dayMetrics)
{
_testMetrics.Add(dayMetrics);
}
public Object GetInfer()
{
// Create x vector, augmented by 1
Vector[] xdata = new Vector[_pastMetrics.Count];
for (int i = 0; i < xdata.Length; i++)
xdata[i] = Vector.FromList(_pastMetrics[i]);
VariableArray<Vector> x = Variable.Observed(xdata);
// Create target y
VariableArray<bool> y = Variable.Observed(_pastResults.ToArray(), x.Range);
var count = _pastMetrics.First().Count;
Variable<Vector> w = Variable.Random(new VectorGaussian(Vector.Zero(count), PositiveDefiniteMatrix.Identity(count)));
Range j = y.Range;
double noise = 0.1;
y[j] = Variable.GaussianFromMeanAndVariance(Variable.InnerProduct(w, x[j]), noise) > 0;
InferenceEngine engine = new InferenceEngine(new ExpectationPropagation());
VectorGaussian wPosterior = engine.Infer<VectorGaussian>(w);
VariableArray<bool> ytest = Variable.Array<bool>(new Range(_pastMetrics.Count));
BayesPointMachine(Variable.Random(wPosterior), ytest);
return engine.Infer(ytest);
}
void BayesPointMachine(Variable<Vector> w, VariableArray<bool> y)
{
// Create x vector, augmented by 1
Range j = y.Range;
Vector[] xdata = new Vector[_testMetrics.Count];
for (int i = 0; i < xdata.Length; i++)
xdata[i] = Vector.FromList(_testMetrics[i]);
VariableArray<Vector> x = Variable.Observed(xdata, j);
// Bayes Point Machine
double noise = 0.1;
y[j] = Variable.GaussianFromMeanAndVariance(Variable.InnerProduct(w, x[j]), noise) > 0;
}
}
这是主程序:
static void Main()
{
var inf = new Inference();
double[] incomes = { 63, 16, 28, 55, 22, 20 };
double[] ages = { 38, 23, 40, 27, 18, 40 };
for (int i = 0; i < incomes.Length; i++)
inf.AddPastMetrics(new List<double> {incomes[i], ages[i]});
double[] incomesTest = { 58, 18, 22 };
double[] agesTest = { 36, 24, 37 };
for (int i = 0; i < incomesTest.Length; i++)
inf.AddTestMetrics(new List<double> { incomesTest[i], agesTest[i] });
bool[] willBuy = { true, false, true, true, false, false };
for (int i = 0; i < willBuy.Length; i++)
inf.AddPastResults(willBuy[i]);
Console.WriteLine("output=\n" + inf.GetInfer());
}
当我调用推断方法时,我收到以下错误:
当变量的长度为6时,提供长度为3的数组 'vVector__1'
知道为什么吗?
答案 0 :(得分:0)
我忘了给数组添加1。从示例页面:
我们将使用这些数据来训练我们的贝叶斯点机器。要做到这一点,我们 需要创建两个观察数组,一个名为x组成 输入要素的向量(通过附加1增加)和一个 叫做y,它只包装willBuy。