Repository navigation
Expand file tree
/
Copy pathProjNN-Ref.cpp
More file actions
85 lines (75 loc) · 2.51 KB
/
Copy pathProjNN-Ref.cpp
File metadata and controls
85 lines (75 loc) · 2.51 KB
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
/**
* @file ProjNN-ref.cpp
* @brief Main application for data (spam) classification system
*
* Implements complete machine learning pipeline:
* 1. Data loading and preprocessing
* 2. Neural network training
* 3. Interactive prediction interface
*/
#include <iostream>
#include "Matrix.h"
#include "NeuralNetwork.h"
#include "Processing.h"
#include "IDataset.h"
#include "Dataset.h"
int main() {
// Polymorphic dataset
IDataset* data = new Dataset();
std::cout << "Set path to dataset: ";
std::string path; std::cin >> path;
data->load(path);
// Build input matrix
Processing preprocessor;
Matrix<double> inputs = preprocessor.textToMatrix(data->getMessages());
// Build targets matrix
std::vector<std::vector<double>> targetRows;
for (int i = 0; i < data->getSize(); i++) {
double label = data->getLabel(i) ? 1.0 : 0.0;
targetRows.push_back({ label });
}
Matrix<double> targets(targetRows);
// Create and train network
std::cout << "\033[33mTraining Neural Network.\033[0m" << std::endl;
NeuralNetwork nn(inputs.getCols(), 16, 1, 0.01);
nn.train(inputs, targets, 1000);
std::cout << "\033[32mTraining Ended.\033[0m" << std::endl;
// Prediction logic
std::cout << "\033[33mSet Neural Network prediction mode:\033[0m" << std::endl;
std::cout << "\033[34m1)\033[0m Single Input" << std::endl;
std::cout << "\033[34m2)\033[0m Multiple from file" << std::endl;
int mode; std::cout << "Mode: "; std::cin >> mode;
while (mode < 1 || mode > 2) {
std::cout << "\033[31mInvalid mode. \033[0m \nSet mode: "; std::cin >> mode;
}
if (mode == 1) {
std::string input_text;
std::cout << "Enter a message: ";
std::cin.ignore();
std::getline(std::cin, input_text);
Matrix<double> test_input = preprocessor.textToMatrix(input_text);
Matrix<double> prediction = nn.forward(test_input);
std::cout << "Spam probability: \033[33m"
<< prediction.getValues()[0][0] << "\033[0m\n";
}
else if (mode == 2) {
std::string input_path;
std::cout << "Set path to dataset: ";
std::cin >> input_path;
Dataset prediction_data;
prediction_data.load(input_path);
for (int i = 0; i < prediction_data.getSize(); i++) {
Matrix<double> test_input = preprocessor.textToMatrix(
prediction_data.getMessage(i)
);
Matrix<double> prediction = nn.forward(test_input);
prediction_data.setLabel(i, prediction.getValues()[0][0] > 0.5);
}
prediction_data.save(input_path + ".out.csv");
std::cout << "\033[32mPredictions saved to: "
<< input_path << ".out.txt\033[0m" << std::endl;
}
// Cleanup
delete data;
return 0;
}