-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathProgram.cs
175 lines (148 loc) · 6.06 KB
/
Program.cs
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
// Решение классификационной задачи, описанной тут: https://github.com/Koziev/WordRepresentations
// Файлы с датасетами в формате csv с табуляцией в качестве разделителя полей должны быть
// заранее подготовлены скриптом store_dataset_file.py
// Используется моя простая реализация vanilla MLP с одним скрытым слоем и sigmoida активациями.
// Достигаемая точность - примерно 0.64
using System;
using System.Linq;
namespace WithMyMLP
{
class Program
{
// В этой папке должны лежать файлы, сгенерированные скриптом store_dataset_file.py (см. https://github.com/Koziev/WordRepresentations/blob/master/PyModels/store_dataset_file.py).
static string data_folder = "../../../../data";
static float[][] LoadXData(string filename)
{
string path = System.IO.Path.Combine(data_folder, filename);
int nb_cols = -1;
int nb_rows = -1;
using (System.IO.StreamReader rdr = new System.IO.StreamReader(path))
{
nb_cols = rdr.ReadLine().Split('\t').Length;
nb_rows = 1;
while (!rdr.EndOfStream)
{
string line = rdr.ReadLine();
if (line == null)
{
break;
}
nb_rows++;
}
}
Console.WriteLine($"Load matrix {nb_rows}x{nb_cols} from {path}");
float[][] data = new float[nb_rows][];
for (int i = 0; i < nb_rows; ++i)
{
data[i] = new float[nb_cols];
}
using (System.IO.StreamReader rdr = new System.IO.StreamReader(path))
{
int irow = 0;
while (!rdr.EndOfStream)
{
string line = rdr.ReadLine();
if (line == null)
{
break;
}
var x = line.Split('\t');
for (int icol = 0; icol < x.Length; ++icol)
{
data[irow][icol] = float.Parse(x[icol], System.Globalization.CultureInfo.InvariantCulture);
}
irow++;
}
}
return data;
}
static float[][] LoadYData(string filename)
{
string path = System.IO.Path.Combine(data_folder, filename);
int nb_rows = -1;
using (System.IO.StreamReader rdr = new System.IO.StreamReader(path))
{
nb_rows = 1;
while (!rdr.EndOfStream)
{
string line = rdr.ReadLine();
if (line == null)
{
break;
}
nb_rows++;
}
}
Console.WriteLine($"Load matrix {nb_rows}x{1} from {path}");
float[][] data = new float[nb_rows][];
for( int i=0; i<nb_rows; ++i)
{
data[i] = new float[1];
}
using (System.IO.StreamReader rdr = new System.IO.StreamReader(path))
{
int irow = 0;
while (!rdr.EndOfStream)
{
string line = rdr.ReadLine();
if (line == null)
{
break;
}
data[irow][0] = float.Parse(line.Trim(), System.Globalization.CultureInfo.InvariantCulture);
irow++;
}
}
return data;
}
static void Main(string[] args)
{
var X_train = LoadXData("X_train.csv");
var y_train = LoadYData("y_train.csv");
var X_val = LoadXData("X_val.csv");
var y_val = LoadYData("y_val.csv");
var X_holdout = LoadXData("X_holdout.csv");
var y_holdout = LoadYData("y_holdout.csv");
int nb_samples = X_train.Length;
int input_size = X_train[0].Length;
FeedForwardNetworks.FeedForwardNetwork2 mlp = new FeedForwardNetworks.FeedForwardNetwork2(false, input_size, input_size, 1);
mlp.LearningRate = 0.01f;
mlp.BatchSize = 20;
Random rnd = new Random();
for (int iter = 0; iter < 100; ++iter)
{
Console.Write($"Epoch {iter}");
int nb_batches = nb_samples / mlp.BatchSize;
int[] indeces = Enumerable.Range(0, nb_samples).OrderBy(z => rnd.Next()).ToArray();
for( int ibatch=0, ii=0; ibatch<nb_batches; ++ibatch)
{
mlp.BeginBatch();
for( int idata=0; idata< mlp.BatchSize; ++idata, ++ii)
{
int irow = indeces[ii];
mlp.ForwardPropagation(X_train[irow]);
mlp.BackwardPropagation(X_train[irow], y_train[irow]);
}
mlp.EndBatch();
}
float loss = 0;
int hits = 0;
for( int irow=0; irow<X_val.Length; ++irow)
{
mlp.ForwardPropagation(X_val[irow]);
float delta = y_val[irow][0] - mlp.GetOutput(0);
loss += delta * delta;
float z = mlp.GetOutput(0) > 0.5f ? 1 : 0;
if( z==y_val[irow][0] )
{
hits++;
}
}
loss /= X_val.Length;
float acc = hits / (float)X_val.Length;
Console.WriteLine($" val_loss={loss} val_accuracy={acc}");
}
return;
}
}
}