Advertisement
Guest User

Untitled

a guest
Dec 7th, 2021
12
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1.  
  2. /**
  3. * Predicts passed attributes using the sigmoid function and returns its chance to fit to the certain label.
  4. * @param data
  5. * @return
  6. */
  7. float predict(MatrixXf &data){ // Data is basically a vector here, just rows no columns
  8.  
  9. // LogisticRegression network graph like calculation
  10. auto sum = 0.0f;
  11. for (auto index = 0; index < data.rows(); index++) {
  12.  
  13. auto weight = weights(index); // Weights is also a vector
  14. auto attribute = data(index);
  15.  
  16. auto result = weight * attribute;
  17. sum += result;
  18. }
  19.  
  20. // Sigmoid
  21. return 1.0f / (1.0f + exp(-sum));
  22. }
  23.  
  24.  
  25. /**
  26. * Learns by a given set of dataSet and trains the perceptron.
  27. * @param dataSet
  28. */
  29. void learn(int iterations, MatrixXf &dataSet, MatrixXf &labelSet){ // Data is
  30.  
  31. auto difference = MatrixXf(labelSet.rows(), 1); // The vector being used as ( a - y ) ^ T from the formula
  32. for (auto index = 0; index < iterations; ++index) {
  33.  
  34. // Update differences... basically ( prediction - label ) -> ( a - y )^T from the formula
  35. for (auto col = 0; col < dataSet.cols(); ++col) {
  36.  
  37. auto data = dataSet.col(col); // The first data vector
  38. auto predicted = predict(data.nestedExpression()); // Predicted value
  39. difference(col) = predicted - labelSet(col); // Insert into ( a - y ) ^ T vector
  40. }
  41.  
  42. auto gradient = ( 1.0f/(float)dataSet.cols() * ( dataSet * difference)); // 1/m * X * ( A - Y ) ^ T
  43. weights -= step * gradient; // Update gradients
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement