-
Notifications
You must be signed in to change notification settings - Fork 0
/
logistic_regression.cpp
537 lines (451 loc) · 13.6 KB
/
logistic_regression.cpp
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
#include <iostream>
#include <iomanip>
#include <fstream>
#include <unistd.h>
#include <cmath>
#include <vector>
#include <string.h>
using namespace std;
// Dot Product
float vector_dot_product(vector<float> vec_A, vector<float> vec_B)
{
if (vec_A.size() != vec_B.size())
{
cerr << "Vector size mismatch" << endl;
exit(1);
}
float result = 0;
for (unsigned int i = 0; i < vec_A.size(); i++)
{
result += vec_A[i] * vec_B[i];
}
return result;
}
// Matrix Transpose
vector<vector<float>> transpose_matrix(vector<vector<float>> input_matrix)
{
int rowSize = input_matrix.size();
int colSize = input_matrix[0].size();
vector<vector<float>> transposed(colSize, vector<float>(rowSize));
for (int i = 0; i < rowSize; i++)
{
for (int j = 0; j < colSize; j++)
{
transposed[j][i] = input_matrix[i][j];
}
}
return transposed;
}
// Linear Transformation (or Matrix * Vector)
vector<float> linear_transformation(vector<vector<float>> input_matrix, vector<float> input_vec)
{
int rowSize = input_matrix.size();
int colSize = input_matrix[0].size();
if (colSize != input_vec.size())
{
cerr << "Matrix Vector sizes error" << endl;
exit(EXIT_FAILURE);
}
vector<float> result_vec(rowSize);
for (int i = 0; i < input_matrix.size(); i++)
{
result_vec[i] = vector_dot_product(input_matrix[i], input_vec);
}
return result_vec;
}
// Sigmoid
float sigmoid(float z)
{
return 1 / (1 + exp(-z));
}
// Predict
vector<float> predict(vector<vector<float>> features, vector<float> weights)
{
vector<float> lintransf_vec = linear_transformation(features, weights);
vector<float> result_sigmoid_vec(features.size());
for (int i = 0; i < result_sigmoid_vec.size(); i++)
{
result_sigmoid_vec[i] = sigmoid(lintransf_vec[i]);
// DEBUG
// cout << "lintransf_vec[i] = " << lintransf_vec[i] << endl;
// cout << "result_sigmoid_vec[i] = " << result_sigmoid_vec[i] << endl;
// if (i == 10)
// {
// exit(0);
// }
}
return result_sigmoid_vec;
}
// Cost Function
float cost_function(vector<vector<float>> features, vector<float> labels, vector<float> weights)
{
int observations = labels.size();
vector<float> predictions = predict(features, weights);
vector<float> cost_result_vec(observations);
float cost_sum = 0;
for (int i = 0; i < observations; i++)
{
// Handle Prediction = 1 issue: Epsilon subtraction
float epsilon = 0.0001;
if (predictions[i] == 1)
{
predictions[i] -= epsilon;
}
// Calculate Cost 0 and 1
float cost0 = (1.0 - labels[i]) * log(1.0 - predictions[i]);
float cost1 = (-labels[i]) * log(predictions[i]);
cost_result_vec[i] = cost1 - cost0;
cost_sum += cost_result_vec[i];
// Log Progress
if (i % 2000 == 0)
{
cout << "i = " << i << "\t\t";
cout << "labels[i] = " << labels[i] << "\t\t";
cout << "predictions[i] = " << predictions[i] << "\t\t";
cout << "cost 0 = " << cost0 << "\t\t";
cout << "cost 1 = " << cost1 << "\t\t";
cout << "cost sum = " << cost_sum << endl;
}
// // DEBUG
// if (i == 100)
// {
// exit(0);
// }
}
float cost_result = cost_sum / observations;
return cost_result;
}
// Gradient Descent (or Update Weights)
vector<float> update_weights(vector<vector<float>> features, vector<float> labels, vector<float> weights, float learning_rate)
{
vector<float> new_weights(weights.size());
int N = features.size();
// Get predictions
vector<float> predictions = predict(features, weights);
// Tranpose features matrix
vector<vector<float>> features_T = transpose_matrix(features);
// Calculate Predictions - Labels vector
vector<float> pred_labels(labels.size());
for (int i = 0; i < labels.size(); i++)
{
pred_labels[i] = predictions[i] - labels[i];
}
// Calculate Gradient vector
vector<float> gradient = linear_transformation(features_T, pred_labels);
for (int i = 0; i < gradient.size(); i++)
{
// Divide by N to get average
gradient[i] /= N;
// Multiply by learning rate
gradient[i] *= learning_rate;
// Subtract from weights to minimize cost
new_weights[i] = weights[i] - gradient[i];
}
return new_weights;
}
// Training
tuple<vector<float>, vector<float>> train(vector<vector<float>> features, vector<float> labels, vector<float> weights, float learning_rate, int iters)
{
int colSize = weights.size();
vector<float> new_weights(colSize);
vector<float> cost_history(iters);
// Set temp weights
vector<float> temp_weights(colSize);
for (int i = 0; i < colSize; i++)
{
temp_weights[i] = weights[i];
}
for (int i = 0; i < iters; i++)
{
// Get new weights
new_weights = update_weights(features, labels, temp_weights, learning_rate);
// Get cost
float cost = cost_function(features, labels, new_weights);
cost_history[i] = cost;
// Log Progress
if (i % 100 == 0)
{
cout << "Iteration:\t" << i << "\t" << cost << endl;
cout << "Weights: ";
for (int i = 0; i < colSize; i++)
{
cout << new_weights[i] << ", ";
}
cout << endl;
}
// Set temp weights to new weights
for (int j = 0; j < colSize; j++)
{
temp_weights[j] = new_weights[j];
}
}
return make_tuple(new_weights, cost_history);
}
// CSV to string matrix converter
vector<vector<string>> CSVtoMatrix(string filename)
{
vector<vector<string>> result_matrix;
ifstream data(filename);
string line;
int line_count = 0;
while (getline(data, line))
{
stringstream lineStream(line);
string cell;
vector<string> parsedRow;
while (getline(lineStream, cell, ','))
{
parsedRow.push_back(cell);
}
// Skip first line since it has text instead of numbers
if (line_count != 0)
{
result_matrix.push_back(parsedRow);
}
line_count++;
}
return result_matrix;
}
// String matrix to float matrix converter
vector<vector<float>> stringToFloatMatrix(vector<vector<string>> matrix)
{
vector<vector<float>> result(matrix.size(), vector<float>(matrix[0].size()));
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[0].size(); j++)
{
result[i][j] = ::atof(matrix[i][j].c_str());
}
}
return result;
}
// Mean calculation
float getMean(vector<float> input_vec)
{
float mean = 0;
for (int i = 0; i < input_vec.size(); i++)
{
mean += input_vec[i];
}
mean /= input_vec.size();
return mean;
}
// Standard Dev calculation
float getStandardDev(vector<float> input_vec, float mean)
{
float variance = 0;
for (int i = 0; i < input_vec.size(); i++)
{
variance += pow(input_vec[i] - mean, 2);
}
variance /= input_vec.size();
float standard_dev = sqrt(variance);
return standard_dev;
}
// Standard Scaler
vector<vector<float>> standard_scaler(vector<vector<float>> input_matrix)
{
int rowSize = input_matrix.size();
int colSize = input_matrix[0].size();
vector<vector<float>> result_matrix(rowSize, vector<float>(colSize));
// Optimization: Get Means and Standard Devs first then do the scaling
// first pass: get means and standard devs
vector<float> means_vec(colSize);
vector<float> stdev_vec(colSize);
for (int i = 0; i < colSize; i++)
{
vector<float> column(rowSize);
for (int j = 0; j < rowSize; j++)
{
// cout << input_matrix[j][i] << ", ";
column[j] = input_matrix[j][i];
// cout << column[j] << ", ";
}
means_vec[i] = getMean(column);
stdev_vec[i] = getStandardDev(column, means_vec[i]);
// cout << "MEAN at i = " << i << ":\t" << means_vec[i] << endl;
// cout << "STDV at i = " << i << ":\t" << stdev_vec[i] << endl;
}
// second pass: scale
for (int i = 0; i < rowSize; i++)
{
for (int j = 0; j < colSize; j++)
{
result_matrix[i][j] = (input_matrix[i][j] - means_vec[j]) / stdev_vec[j];
// cout << "RESULT at i = " << i << ":\t" << result_matrix[i][j] << endl;
}
}
return result_matrix;
}
float accuracy(vector<float> predicted_labels, vector<float> actual_labels)
{
// handle error
if (predicted_labels.size() != actual_labels.size())
{
cerr << "Vector size mismatch" << endl;
exit(EXIT_FAILURE);
}
int size = predicted_labels.size();
vector<float> diff(size);
int nnz = 0;
for (int i = 0; i < size; i++)
{
diff[i] = predicted_labels[i] - actual_labels[i];
// count non zero in diff
if (diff[i] != 0)
{
nnz++;
}
}
float result = 1.0 - (nnz / size);
return result;
}
float RandomFloat(float a, float b)
{
float random = ((float)rand()) / (float)RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
int main()
{
// Read File
string filename = "pulsar_stars.csv";
vector<vector<string>> s_matrix = CSVtoMatrix(filename);
vector<vector<float>> f_matrix = stringToFloatMatrix(s_matrix);
// Test print first 10 rows
cout << "First 10 rows of CSV file --------\n"
<< endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < f_matrix[0].size(); j++)
{
cout << f_matrix[i][j] << ", ";
}
cout << endl;
}
cout << "...........\nLast 10 rows of CSV file ----------\n"
<< endl;
// Test print last 10 rows
for (int i = f_matrix.size() - 10; i < f_matrix.size(); i++)
{
for (int j = 0; j < f_matrix[0].size(); j++)
{
cout << f_matrix[i][j] << ", ";
}
cout << endl;
}
// Init features, labels and weights
// Init features (rows of f_matrix , cols of f_matrix - 1)
int rows = f_matrix.size();
cout << "\nNumber of rows = " << rows << endl;
int cols = f_matrix[0].size() - 1;
cout << "\nNumber of cols = " << cols << endl;
vector<vector<float>> features(rows, vector<float>(cols));
// Init labels (rows of f_matrix)
vector<float> labels(rows);
// Init weight vector with zeros (cols of features)
vector<float> weights(cols);
// Fill the features matrix and labels vector
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
features[i][j] = f_matrix[i][j];
}
labels[i] = f_matrix[i][cols];
}
// Fill the weights with random numbers (from 1 - 2)
for (int i = 0; i < cols; i++)
{
weights[i] = RandomFloat(-2, 2);
cout << "weights[i] = " << weights[i] << endl;
}
// Test print the features and labels
cout << "\nTesting features\n--------------\n"
<< endl;
// Features Print test
cout << "Features row size = " << features.size() << endl;
cout << "Features col size = " << features[0].size() << endl;
cout << "Labels row size = " << labels.size() << endl;
cout << "Weights row size = " << weights.size() << endl;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < features[0].size(); j++)
{
cout << features[i][j] << ", ";
}
cout << endl;
}
// Standardize the features
cout << "\nSTANDARDIZE TEST---------\n"
<< endl;
vector<vector<float>> standard_features = standard_scaler(features);
// Test print first 10 rows
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < cols; j++)
{
cout << standard_features[i][j] << ", ";
}
cout << endl;
}
cout << "..........." << endl;
// Test print last 10 rows
for (int i = rows - 10; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
cout << standard_features[i][j] << ", ";
}
cout << endl;
}
cout << "\nTesting labels\n--------------\n"
<< endl;
// Labels Print Test
for (int i = 0; i < 10; i++)
{
cout << labels[i] << ", ";
}
cout << endl;
// TRAIN
cout << "\nTraining--------------\n"
<< endl;
tuple<vector<float>, vector<float>> training_tuple = train(standard_features, labels, weights, 0.1, 100);
vector<float> new_weights = get<0>(training_tuple);
vector<float> cost_history = get<1>(training_tuple);
// Print old weights
cout << "\nOLD WEIGHTS\n------------------"
<< endl;
for (int i = 0; i < weights.size(); i++)
{
cout << weights[i] << ", ";
}
cout << endl;
// Print mew weights
cout << "\nNEW WEIGHTS\n------------------"
<< endl;
for (int i = 0; i < new_weights.size(); i++)
{
cout << new_weights[i] << ", ";
}
cout << endl;
// Print Cost history
cout << "\nCOST HISTORY\n------------------"
<< endl;
for (int i = 0; i < cost_history.size(); i++)
{
cout << cost_history[i] << ", ";
if (i % 10 == 0 && i > 0)
{
cout << "\n";
}
}
cout << endl;
// Print Accuracy
cout << "\nACCURACY\n-------------------" << endl;
vector<float> predictions = predict(features, new_weights);
double acc = accuracy(predictions, labels);
cout << acc << endl;
return 0;
}