File: featureSet.cc

package info (click to toggle)
gpsshogi 0.7.0-3.3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 111,280 kB
  • sloc: cpp: 80,962; perl: 12,610; ruby: 3,929; javascript: 1,631; makefile: 1,202; sh: 473; tcl: 166; ansic: 67
file content (401 lines) | stat: -rw-r--r-- 11,012 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/* featureSet.cc
 */
#include "featureSet.h"
#include "feature.h"
#include "osl/csa.h"
#include "osl/eval/see.h"
#include "osl/eval/pieceEval.h"
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/format.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <cstdio>

gpsshogi::
FeatureSet::FeatureSet()
{
}

gpsshogi::
FeatureSet::~FeatureSet()
{
}

void gpsshogi::
FeatureSet::pushBack(Feature *f, bool light)
{
  features.push_back(f);
  if (light)
    light_features.push_back(features.size()-1);
}

void gpsshogi::
FeatureSet::addFinished()
{
  offsets.resize(features.size()+1);
  offsets[0] = 0;
  for (size_t i=0; i<features.size(); ++i)
    offsets[i+1] = offsets[i] + features[i].dimension();
}

gpsshogi::weight_t gpsshogi::FeatureSet::
match(const StateInfo& state, Move move, index_list_t& out,
      const valarray_t& weights) const
{
  MoveInfo info(state, move);
  assert(offsets.size() == features.size()+1);
  out.clear();
#ifndef NDEBUG
  size_t prev = 0;
#endif
  for (size_t i=0; i<features.size(); ++i) {
    features[i].match(state, info, offsets[i], out);
#ifndef NDEBUG
    for (size_t j=prev; j<out.size(); ++j) {
      assert(offsets[i] <= out[j].first);
      assert(out[j].first < offsets[i+1]);
    }
    prev = out.size();
#endif
  }
  return accumulate(out, weights);
}

gpsshogi::weight_t gpsshogi::FeatureSet::
matchExp(const StateInfo& state, Move move, index_list_t& out,
      const valarray_t& weights) const
{
  return exp(match(state, move, out, weights));
}

gpsshogi::weight_t gpsshogi::FeatureSet::
matchLight(const StateInfo& state, Move move, index_list_t& out,
	   const valarray_t& weights) const
{
  MoveInfo info(state, move);
  assert(offsets.size() == features.size()+1);
  out.clear();
  for (size_t i: light_features) {
    features[i].match(state, info, offsets[i], out);
  }
  return accumulate(out, weights);
}


void gpsshogi::FeatureSet::
analyze(const StateInfo& state, Move move, const valarray_t& weights) const
{
  MoveInfo info(state, move);
  index_list_t matched;
  std::cerr << csa::show(move) << "\n";
  std::vector<std::pair<double, std::string> > out;
  for (size_t i=0; i<features.size(); ++i) {
    matched.clear();
    features[i].match(state, info, offsets[i], matched);
    if (! matched.empty())
      out.push_back(make_pair(accumulateExp(matched, weights),
			      features[i].name()));
  }
  std::sort(out.begin(), out.end());
  std::reverse(out.begin(), out.end());
  for (size_t i=0; i<out.size(); ++i) {
    std::cerr << boost::format("%16s %6.2f ") % out[i].second % out[i].first;
    if (i % 3 == 2)
      std::cerr << "\n";
  }
  if (out.size() % 3 != 0)
    std::cerr << "\n";
}

gpsshogi::weight_t gpsshogi::FeatureSet::
accumulate(const index_list_t& features, const valarray_t& weights)
{
  weight_t sum = 0.0;
  for (const index_list_t::value_type& p: features) {
    assert(p.first < weights.size());
    sum += weights[p.first] * p.second;
  }
  assert(sum == 0.0 || std::isnormal(sum));
  return sum;
}

gpsshogi::weight_t gpsshogi::FeatureSet::
accumulateExp(const index_list_t& features, const valarray_t& weights)
{
  return exp(accumulate(features, weights));
}

gpsshogi::weight_t gpsshogi::FeatureSet::
generateRating(const StateInfo& state, WeightedMoveVector& out,
	       const valarray_t& weights) const
{
  MoveVector moves;
  state.state.generateLegal(moves);
  weight_t sum = 0.0;
  for (Move move: moves) {
    index_list_t dummy;
    weight_t score = match(state, move, dummy, weights);
    out.push_back(WeightedMove(score, move));
    sum += exp(score);
  }
  return sum;
}

void gpsshogi::FeatureSet::
ratingToLogProb(const WeightedMoveVector& rating,
		weight_t sum,
		MoveLogProbVector& out)
{
  static const double scale = 100.0 / log(0.5);
  for (WeightedMove move: rating) {
    weight_t p = exp(move.first)/sum;
    if (std::isnan(p) || p <= 1.0/(1<<12)) 
      p = 1.0/(1<<12);
    const int logp = std::max(50, static_cast<int>(log(p)*scale));
    out.push_back(MoveLogProb(move.second, logp));
  }
  out.sortByProbability();
}

void gpsshogi::FeatureSet::
generateLogProb(const StateInfo& state, MoveLogProbVector& out,
		const valarray_t& weights) const
{
  WeightedMoveVector moves;
  weight_t sum = generateRating(state, moves, weights);
  ratingToLogProb(moves, sum, out);
}

int gpsshogi::FeatureSet::
logLikelihood(const StateInfo& state,
	      Move move, const valarray_t& weights) const
{
  MoveLogProbVector moves;
  generateLogProb(state, moves, weights);
  const MoveLogProb *p = moves.find(move);
  if (!p)
    return 1200;
  return p->logProb();
}

void gpsshogi::FeatureSet::
save(const char *base_filename, const valarray_t& weights) const
{
  assert(weights.size() == dimension());
  std::string info_filename = std::string(base_filename) + "-info.txt";
  {
    std::ofstream os(info_filename.c_str());
    os << "#* all\n";
    for (const Feature& f: features)
      os << f.name() << ' ' << f.dimension() << "\n";
  }
  std::string filename = std::string(base_filename) + ".txt";
  {
    FILE *fp = fopen(filename.c_str(), "w");
    if (! fp)
      return;
    for (size_t i=0; i<weights.size(); ++i)
      fprintf(fp, "%.8f\n", weights[i]);
    fclose(fp);
  }
}

bool gpsshogi::FeatureSet::
load(const char *base_filename, valarray_t& weights) const
{
  std::string filename = std::string(base_filename) + ".txt";
  weights.resize(dimension());
  weights = 0.0;
  std::ifstream is(filename.c_str());
  for (size_t i=0; i<dimension(); ++i) {
    is >> weights[i];
    if (! is) {
      std::cerr << "load failed at " << i << " in " << dimension() << "\n";
      break;
    }
  }
  return static_cast<bool>(is);
}

void gpsshogi::FeatureSet::
showSummary(const valarray_t& weights) const
{
  assert(weights.size() == dimension());
  for (size_t i=0; i<features.size(); ++i) {
    const Feature& f = features[i];
    using namespace boost::accumulators;
    accumulator_set<weight_t, stats<tag::mean, tag::min, tag::max> > acc;
    int zero = 0;
    for (size_t j=offsets[i]; j<offsets[i+1]; ++j)
      if (weights[j])
	acc(weights[j]);
      else 
	++zero;
    std::cerr << std::setw(16) << f.name() 
	      << " dim " << std::setw(5) << f.dimension() - zero
	      << "/" << std::setw(5) << f.dimension()
	      << " min " << std::setw(6) << min(acc)
	      << " max " << std::setw(6) << max(acc)
	      << " mean " << std::setw(6) << mean(acc)
	      << "\n";
  }
}


gpsshogi::StandardFeatureSet::
StandardFeatureSet()
{
  pushBack(new TakeBackFeature, 1);
  pushBack(new CheckFeature, 1);
  pushBack(new SeeFeature, 1);
  pushBack(new ContinueCapture, 1);
  pushBack(new DropCaptured);
  pushBack(new SquareY, 1);
  pushBack(new SquareX, 1);
  pushBack(new KingRelativeY, 1);
  pushBack(new KingRelativeX, 1);
  pushBack(new FromEffect, 1);
  pushBack(new ToEffect, 1);
  pushBack(new FromEffectLong, 1);
  pushBack(new ToEffectLong, 1);
  pushBack(new Pattern(0,-1));	// U
  pushBack(new Pattern(1,-1));	// UL
  pushBack(new Pattern(1,0));	// L
  pushBack(new Pattern(0,1));	// D
  pushBack(new Pattern(1,1));	// DL
  pushBack(new Pattern(1,-2));	// UUL
  pushBack(new Pattern(0,-2));	// UU
  pushBack(new Pattern(0,2));	// DD
  pushBack(new Pattern(2,0));	// LL
  pushBack(new Pattern(1,2));	// DDL
  pushBack(new MoveFromOpposingSliders);
  pushBack(new AttackToOpposingSliders);
  pushBack(new PawnAttack);
  pushBack(new CapturePtype, 1);
  pushBack(new BlockLong);
  pushBack(new BlockLongFrom);
  pushBack(new LanceAttack);
  pushBack(new BishopAttack);
  pushBack(new RookAttack);
  pushBack(new BreakThreatmate);
  pushBack(new SendOff);
  pushBack(new CheckmateIfCapture);
  pushBack(new OpposingPawn);
  pushBack(new DropAfterOpposingPawn);
  pushBack(new LongRecapture);
  pushBack(new SacrificeAttack);
  pushBack(new AddEffectLong);
  pushBack(new King5x5Ptype);
  pushBack(new KingBlockade);
  pushBack(new CoverFork);
  pushBack(new ThreatmateByCapture);
  pushBack(new LureDefender);
  pushBack(new CoverPawn);
  pushBack(new PromotionBySacrifice);
  pushBack(new EscapeThreatened);
  pushBack(new BookMove);
  addFinished();
}



void gpsshogi::PredictionModelLight::
save(const char *filename, const valarray_t& weights)
{
  assert(weights.size() == dimension());
  FILE *fp = fopen(filename, "w");
  if (! fp)
    return;
  for (size_t i=0; i<weights.size(); ++i)
    fprintf(fp, "%.8f\n", weights[i]);
  fclose(fp);
}

bool gpsshogi::PredictionModelLight::
load(const char *filename, valarray_t& weights)
{
  weights.resize(dimension());
  weights = 0.0;
  std::ifstream is(filename);
  for (size_t i=0; i<dimension(); ++i) {
    is >> weights[i];
    if (! is) {
      std::cerr << "load failed at " << i << " in " << dimension() << "\n";
      break;
    }
  }
  return static_cast<bool>(is);
}

gpsshogi::weight_t gpsshogi::PredictionModelLight::
addGradientTakeBack(int progress8, Move next, Move target, double sum, const valarray_t& weights,
		    valarray_t& partial)
{
  return addGradient(next, target, sum, weights, partial, progress8*4 + 0);
}

gpsshogi::weight_t gpsshogi::PredictionModelLight::
addGradientSeePlus(const StateInfo& info, Move next, Move target, double sum, const valarray_t& weights,
		   valarray_t& partial)
{
  const int progress8 = info.progress8();
  return addGradient(next, target, sum, weights, partial, progress8*4 + 2);
}

gpsshogi::weight_t gpsshogi::PredictionModelLight::
addGradient(Move next, Move target, double sum, const valarray_t& weights,
	    valarray_t& partial, int offset)
{
  // p = a * r + b
  assert(partial.size() == dimension());
  assert(weights.size() == dimension());
  valarray_t x(dimension());
  x = 0.0;
  x[0+offset] = sum;
  x[1+offset] = 1.0;
  weight_t f = (x*weights).sum();
  weight_t p = 1/(1.0+exp(-f));
  if (target == next) {
    for (size_t j=0; j<x.size(); ++j) {
      assert(j < partial.size());
      partial[j] += x[j]*p*(1-p);
      assert(! isnan(partial[j]));
    }
  } else {
    for (size_t j=0; j<x.size(); ++j) {
      assert(j < partial.size());
      partial[j] -= x[j]*p*(1-p);
      assert(! isnan(partial[j]));
    }
  }
  return std::max(p, 1.0/(1<<12));
}

int gpsshogi::PredictionModelLight::
logProbTakeBack(const StateInfo& info, double sum, const valarray_t& w)
{
  return predict(info.progress8()*4 + 0, sum, w);
}
int gpsshogi::PredictionModelLight::
logProbSeePlus(const StateInfo& info, double sum, const valarray_t& w)
{
  return predict(info.progress8()*4 + 2, sum, w);
}
int gpsshogi::PredictionModelLight::
predict(int offset, double sum, const valarray_t& w)
{
  static const double scale = 100.0 / log(0.5);
  double x = w[offset] * sum + w[offset+1], p = 1/(1.0+exp(-x));
  return std::max(50, static_cast<int>(log(p)*scale));
}

// ;;; Local Variables:
// ;;; mode:c++
// ;;; c-basic-offset:2
// ;;; End: