好友
阅读权限10
听众
最后登录1970-1-1
|
jtwc
发表于 2022-5-20 16:51
本帖最后由 jtwc 于 2022-5-20 17:31 编辑
各位老师,C++源码依次输入能正常显示,把所有的手动输入改为数组咋运行出错呢?
[C++] 纯文本查看 复制代码 #include<iostream>
using namespace std;
#define T 5
#define M 3
#define N 2
float mp[M][M];
float w2a[M][N];
int O[T];
int bestPath[T][M];
float pi[M];
void initHMM()
{
int i, j, k;
// float mp[3][3] = { { 0.33333, 0.33333, 0.33333 }, { 0.33333, 0.33333, 0.33333 }, { 0.33333, 0.33333, 0.33333 } };
// float w2a[3][2] = { { 0.75, 0.25 }, { 0.4, 0.6 }, { 0.25, 0.75 } };
// float pi[3] = { 0.5, 0.3, 0.2 };
// int O[5] = { 0, 0, 1, 0, 1 };
for (i = 0; i<M; i++)
{
for (j = 0; j<M; j++)
{
cin >> mp[i][j];
}
}
for (i = 0; i<M; i++)
{
for (j = 0; j<N; j++)
{
cin >> w2a[i][j];
}
}
for (i = 0; i<M; i++)
{
cin >> pi[i];
}
for (i = 0; i<T; i++)
{
cin >> O[i];
}
}
float viterbi()
{
float maxP[T][M];
int i, j, t;
float maxpp = 0;
int maxPre = 0;
for (i = 0; i<M; i++)
{
maxP[0][i] = pi[i] * w2a[i][O[0]];
if (maxP[0][i]>maxpp)
{
bestPath[0][i] = -1;
maxpp = maxP[0][i];
}
}
for (t = 1; t<T; t++)
{
for (i = 0; i<M; i++)
{
maxpp = 0;
maxPre = 0;
for (j = 0; j<M; j++)
{
float temp = maxP[t - 1][j] * mp[j][i] * w2a[i][O[t]];
if (temp > maxpp)
{
maxpp = temp;
maxPre = j;
}
}
maxP[t][i] = maxpp;
bestPath[t][i] = maxPre;
}
}
float maxEndP = 0;
int lastChoice;
for (i = 0; i<M; i++)
{
if (maxP[T - 1][i] > maxEndP)
{
maxEndP = maxP[T - 1][i];
lastChoice = i;
}
}
cout << "最大:" << maxEndP << endl;
cout << "路径(逆序)为:" << endl;
cout << lastChoice << " ";
for (t = T - 1; t>0; t--)
{
cout << bestPath[t][lastChoice] << " ";
lastChoice = bestPath[t][lastChoice];
}
cout << endl;
return maxEndP;
}
void forward()
{
float sumP[T][M];
int t, i, j, k;
for (i = 0; i<M; i++)
{
sumP[0][i] = pi[i] * w2a[i][O[0]];
}
for (t = 1; t<T; t++)
{
for (i = 0; i<M; i++)
{
sumP[t][i] = 0;
for (j = 0; j<M; j++)
{
sumP[t][i] += sumP[t - 1][j] * mp[j][i] * w2a[i][O[t]];
}
}
}
float sumPP = 0;
for (i = 1; i<M; i++)
{
sumPP += sumP[T - 1][i];
}
cout << "序列为" << sumPP << endl;
}
int main()
{
initHMM();
viterbi();
forward();
system("pause");
}
for (i = 0; i<M; i++)
{
for (j = 0; j<M; j++)
{
cin >> mp[j];
}
}
for (i = 0; i<M; i++)
{
for (j = 0; j<N; j++)
{
cin >> w2a[j];
}
}
for (i = 0; i<M; i++)
{
cin >> pi;
}
for (i = 0; i<T; i++)
{
cin >> O;
}
以上源码改为如下:
float mp[3][3] = { { 0.33333, 0.33333, 0.33333 }, { 0.33333, 0.33333, 0.33333 }, { 0.33333, 0.33333, 0.33333 } };
float w2a[3][2] = { { 0.75, 0.25 }, { 0.4, 0.6 }, { 0.25, 0.75 } };
float pi[3] = { 0.5, 0.3, 0.2 };
int O[5] = { 0, 0, 1, 0, 1 };
|
|