-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathtest_nmist_01.php
98 lines (91 loc) · 2.47 KB
/
test_nmist_01.php
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
<?php
/*
* Handwritten digits recognation using pre-traind saved model
*
* See: http://yann.lecun.com/exdb/mnist/
*
*/
require_once("TensorFlow.php");
require_once("PrintGraph.php");
const MODEL = './models/mnist_500_500_softmax_linear';
const TEST_IMAGES = './datasets/mnist/t10k-images-idx3-ubyte.gz';
const TEST_LABELS = './datasets/mnist/t10k-labels-idx1-ubyte.gz';
function main() {
$tf = new TensorFlow();
/* Load Session */
$sess = $tf->loadSavedModel(MODEL);
/* Output of the loaded Neural Networ */
$out = $tf->graph->operation('softmax_linear/add')->output(0);
/* Index of the top value */
$out_label =
$tf->op('Reshape', [
$tf->op('TopKV2', [$out, $tf->constant(1, \TF\INT32)], [], [], null, 1),
$tf->constant([-1])]);
//print_graph($tf->graph);
/* Recognation */
$ret = $sess->run($out_label, ['Placeholder' => get_images($tf)]);
/* Verification */
$labels = $ret->value();
$right = verify_labels($labels);
printf("Num examples: %d Num correct: %d Precision: %g\n",
count($labels), $right, $right / count($labels));
}
function get_images($tf) {
$f = gzopen(TEST_IMAGES, 'r');
$magic = read32($f);
if ($magic != 2051) {
throw new Exception("Invalid magic number '$magic' in MNIST image file");
}
$num_images = read32($f);
$rows = read32($f);
$cols = read32($f);
$s = gzread($f, $rows * $cols * $num_images);
gzclose($f);
$pixels = $rows * $cols;
$n = 0;
$ret = $tf->tensor(null, \TF\FLOAT, [$num_images, $pixels]);
$data = $ret->data();
for ($i = 0; $i < $num_images; $i++) {
for ($j = 0; $j < $pixels; $j++) {
$data[$i * $pixels + $j] = ord($s[$n++]) / 255.0;
}
}
return $ret;
}
function read32($f) {
return unpack("N", gzread($f, 4))[1];
}
function get_labels($tf) {
$f = gzopen(TEST_LABELS, 'r');
$magic = read32($f);
if ($magic != 2049) {
throw new Exception("Invalid magic number '$magic' in MNIST label file");
}
$num_items = read32($f);
$s = gzread($f, $num_items);
gzclose($f);
$ret = $tf->tensor(null, \TF\INT32, [$num_items]);
$data = $ret->data();
for ($i = 0; $i < $num_items; $i++) {
$data[$i] = ord($s[$i]);
}
return $ret;
}
function verify_labels($labels) {
$right = 0;
$f = gzopen(TEST_LABELS, 'r');
$magic = read32($f);
if ($magic != 2049) {
throw new Exception("Invalid magic number '$magic' in MNIST label file");
}
$num_items = read32($f);
$s = gzread($f, $num_items);
gzclose($f);
for ($i = 0; $i < $num_items; $i++) {
if (ord($s[$i]) == $labels[$i]) {
$right++;
}
}
return $right;
}
main();