Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <ctime>
- #include <cstdlib>
- const int rows = 4, cols = 3;
- double sigmoid(double x, double w)
- {
- if (x == 0) x -= w;
- //if (x > -1 && x<1) x -= w;
- return 1 / (1 + exp(-(x)));
- }
- double fRand()
- {
- double fMin = -1;
- double fMax = 1;
- double f = (double)rand() / RAND_MAX;
- return fMin + f * (fMax - fMin);
- }
- template <int Size1, int Size2>
- double newDot(int(&input)[Size1][Size2], double other[], int k)
- {
- double d = 0;
- for (int j = 0; j < Size2; j++)
- {
- d += input[k][j] * other[j];
- }
- return d;
- }
- void transpose(int T[cols][rows], int input_layers[rows][cols])
- {
- for (int i = 0; i < rows; i++)
- for (int j = 0; j < cols; j++)
- T[j][i] = input_layers[i][j];
- }
- void findRfromO(double errors[rows], double outputs[rows], double right[rows])
- {
- for (int i = 0; i < rows; i++)
- {
- right[i] = errors[i] * (outputs[i] * (1 - outputs[i]));
- }
- }
- int main()
- {
- double B = 8;
- srand(time(0));
- int training_inputs[rows][cols] =
- { {0,1,0},
- {0,1,1},
- {0,0,1},
- {1,0,1} };
- int training_outputs[rows] = { 0,0,0,1 };
- double synaptic_weights[cols];
- for (int i = 0; i < cols; i++)
- synaptic_weights[i] = fRand();
- std::cout << "Starting weights: " << std::endl;
- for (int i = 0; i < cols; i++)
- std::cout << synaptic_weights[i] << std::endl;
- //Метод обратного распространения
- int input_layers[rows][cols];
- for (int i = 0; i < rows; i++)
- for (int j = 0; j < cols; j++)
- input_layers[i][j] = training_inputs[i][j];
- double outputs[rows];
- double errors[rows];
- double adjustments[cols];
- double right[rows];
- int T_input_layers[cols][rows];
- for (int g = 0; g < 20000; g++)
- {
- for (int i = 0; i < rows; i++)
- outputs[i] = sigmoid(newDot(input_layers, synaptic_weights, i), B);
- for (int i = 0; i < rows; i++)
- errors[i] = training_outputs[i] - outputs[i];
- transpose(T_input_layers, input_layers);
- findRfromO(errors, outputs, right);
- for (int j = 0; j < cols; j++)
- adjustments[j] = newDot(T_input_layers, right, j);
- for (int j = 0; j < cols; j++)
- synaptic_weights[j] += adjustments[j];
- }
- std::cout << "\nWeights after learning: " << std::endl;
- for (int j = 0; j < cols; j++)
- std::cout << synaptic_weights[j] << std::endl;
- std::cout << "\nResult for starting inputs: " << std::endl;
- for (int i = 0; i < rows; i++)
- std::cout << outputs[i] << std::endl;
- //Тест
- const int new_rows = 2;
- int new_in[new_rows][cols];
- int x;
- for (int i = 0; i < new_rows; i++)
- {
- for (int j = 0; j < cols; j++)
- {
- std::cin >> x;
- new_in[i][j] = x;
- }
- }
- double new_out[new_rows];
- std::cout << "\n\nTest Results: " << std::endl;
- for (int i = 0; i < new_rows; i++)
- {
- new_out[i] = sigmoid(newDot(new_in, synaptic_weights, i), B);
- std::cout << std::endl << new_out[i];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement