この記事の冒頭で説明したアルゴリズムを複製しようとするプログラムを作成しています。
http://www-stat.stanford.edu/~cgates/PERSI/papers/MCMCRev.pdf
F は char から char への関数です。Pl(f) がその関数の「妥当性」尺度であると仮定します。アルゴリズムは次のとおりです。
関数の予備的な推測から始めて、たとえば f と、新しい関数 f* を作成します。
- Pl(f) を計算します。
- f が 2 つのシンボルに割り当てる値をランダムに転置して、f* に変更します。
- Pl(f*) を計算します。これが Pl(f) より大きい場合は、f* を受け入れます。
- そうでない場合は、Pl(f)/Pl(f*) コインを 1 枚投げます。表が出たら、f* を受け入れます。
- コイントスで裏が出た場合は、f にとどまります。
次のコードを使用してこれを実装しています。私はc#を使用していますが、誰にとってもやや単純化しようとしました。これに関するより良いフォーラムがあれば、私に知らせてください。
var current_f = Initial(); // current accepted function f
var current_Pl_f = InitialPl(); // current plausibility of accepted function f
for (int i = 0; i < 10000; i++)
{
var candidate_f = Transpose(current_f); // create a candidate function
var candidate_Pl_f = ComputePl(candidate_f); // compute its plausibility
if (candidate_Pl_f > current_Pl_f) // candidate Pl has improved
{
current_f = candidate_f; // accept the candidate
current_Pl_f = candidate_Pl_f;
}
else // otherwise flip a coin
{
int flip = Flip();
if (flip == 1) // heads
{
current_f = candidate_f; // accept it anyway
current_Pl_f = candidate_Pl_f;
}
else if (flip == 0) // tails
{
// what to do here ?
}
}
}
私の質問は基本的に、これがそのアルゴリズムを実装するための最適なアプローチのように見えるかどうかです。この方法を実装しているにもかかわらず、極大値/極小値で動けなくなっているようです。
編集- これは基本的に Transpose() メソッドの背後にあるものです。候補関数が特定の char -> char 変換を調べるために使用する << char, char >> 型の辞書/ハッシュ テーブルを使用します。そのため、転置メソッドは、関数の動作を指示するディクショナリ内の 2 つの値を単純に交換します。
private Dictionary<char, char> Transpose(Dictionary<char, char> map, params int[] indices)
{
foreach (var index in indices)
{
char target_val = map.ElementAt(index).Value; // get the value at the index
char target_key = map.ElementAt(index).Key; // get the key at the index
int _rand = _random.Next(map.Count); // get a random key (char) to swap with
char rand_key = map.ElementAt(_rand).Key;
char source_val = map[rand_key]; // the value that currently is used by the source of the swap
map[target_key] = source_val; // make the swap
map[rand_key] = target_val;
}
return map;
}
基になる辞書を使用する候補関数は、基本的に次のとおりであることに注意してください。
public char GetChar(char in, Dictionary<char, char> theMap)
{
return theMap[char];
}
そして、これは Pl(f) を計算する関数です:
public decimal ComputePl(Func<char, char> candidate, string encrypted, decimal[][] _matrix)
{
decimal product = default(decimal);
for (int i = 0; i < encrypted.Length; i++)
{
int j = i + 1;
if (j >= encrypted.Length)
{
break;
}
char a = candidate(encrypted[i]);
char b = candidate(encrypted[j]);
int _a = GetIndex(_alphabet, a); // _alphabet is just a string/char[] of all avl chars
int _b = GetIndex(_alphabet, b);
decimal _freq = _matrix[_a][_b];
if (product == default(decimal))
{
product = _freq;
}
else
{
product = product * _freq;
}
}
return product;
}