fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. // Tu wklejam klasę Perceptron z poprzedniego przykładu
  5.  
  6. class Perceptron {
  7. private:
  8. std::vector<double> weights;
  9. double bias;
  10. double learning_rate;
  11.  
  12. public:
  13. Perceptron(int input_size, double learning_rate)
  14. : weights(input_size, 0.0), bias(0.0), learning_rate(learning_rate) {}
  15.  
  16. int predict(const std::vector<double>& inputs) {
  17. double suma = bias;
  18. for (size_t i = 0; i < weights.size(); ++i) {
  19. suma += weights[i] * inputs[i];
  20. }
  21. return (suma >= 0) ? 1 : 0;
  22. }
  23.  
  24. void train(const std::vector<std::vector<double>>& inputs,
  25. const std::vector<int>& labels,
  26. int epochs) {
  27. for (int epoch = 0; epoch < epochs; ++epoch) {
  28. for (size_t i = 0; i < inputs.size(); ++i) {
  29. int prediction = predict(inputs[i]);
  30. int error = labels[i] - prediction;
  31.  
  32. for (size_t j = 0; j < weights.size(); ++j) {
  33. weights[j] += learning_rate * error * inputs[i][j];
  34. }
  35. bias += learning_rate * error;
  36. }
  37. }
  38. }
  39.  
  40. void printWeightsAndBias() const {
  41. std::cout << "Wagi: ";
  42. for (double w : weights) {
  43. std::cout << w << " ";
  44. }
  45. std::cout << "\nBias: " << bias << std::endl;
  46. }
  47. };
  48.  
  49. int main() {
  50. // Tworzymy perceptron z 2 wejściami i współczynnikiem uczenia 0.1
  51. Perceptron p(2, 0.1);
  52.  
  53. // Dane treningowe (wejścia)
  54. std::vector<std::vector<double>> training_inputs = {
  55. {0, 0},
  56. {0, 1},
  57. {1, 0},
  58. {1, 1}
  59. };
  60.  
  61. // Etykiety zgodne z funkcją AND, ale wyjścia to 0 lub 2 (zgodnie z Twoim kodem)
  62. std::vector<int> training_labels = {0, 0, 0, 1};
  63.  
  64. // Trenujemy perceptron przez 10 epok
  65. p.train(training_inputs, training_labels, 10);
  66.  
  67. // Wypisujemy wagi i bias po treningu
  68. p.printWeightsAndBias();
  69.  
  70. // Testujemy perceptron na danych treningowych
  71. std::cout << "Test predykcji:" << std::endl;
  72. for (const auto& input : training_inputs) {
  73. int result = p.predict(input);
  74. std::cout << "(" << input[0] << ", " << input[1] << ") -> " << result << std::endl;
  75. }
  76.  
  77. return 0;
  78. }
  79.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Wagi: 0.2 0.1 
Bias: -0.2
Test predykcji:
(0, 0) -> 0
(0, 1) -> 0
(1, 0) -> 0
(1, 1) -> 1