Skip to content

Commit 356dcff

Browse files
committed
add gradient multiple input
1 parent 8ccf060 commit 356dcff

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

MLTests/GradientMulInOneOutTests.cs

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
using FluentAssertions;
2+
using NUnit.Framework;
3+
4+
namespace MLTests
5+
{
6+
public class GradientMulInOneOutTests
7+
{
8+
private double WeightsSum(double[] vecA, double[] vecB)
9+
{
10+
double result = 0;
11+
for (int i = 0; i < vecA.Length; i++)
12+
{
13+
result = result + vecA[i] * vecB[i];
14+
}
15+
return result;
16+
}
17+
18+
private double[] WeightsSub(double[] vecA, double sub)
19+
{
20+
var result = new double[vecA.Length];
21+
for (int i = 0; i < vecA.Length; i++)
22+
{
23+
result[i] = vecA[i] - sub;
24+
}
25+
return result;
26+
27+
}
28+
29+
private double[] WeightsMul(double[] vecA, double[] vecB)
30+
{
31+
var result = new double[vecA.Length];
32+
for (int i = 0; i < vecA.Length; i++)
33+
{
34+
result[i] = vecA[i] * vecB[i];
35+
}
36+
return result;
37+
}
38+
39+
private double[] GetLearnByGradientMul(double[] weights, double[] input, double predictionGoal, double alpha, double iterations)
40+
{
41+
var result = weights.ToArray();
42+
for(int iteration = 0; iteration < iterations; ++iteration)
43+
{
44+
var prediction = WeightsSum(input, result);
45+
var error = Math.Pow(prediction - predictionGoal, 2);
46+
var delta = prediction - predictionGoal;
47+
var deltaWeight = delta * prediction;
48+
result = WeightsSub(result, alpha * deltaWeight);
49+
}
50+
return result;
51+
}
52+
53+
[Test]
54+
public void ShouldGradientLearnByMultipleInputOneOutput()
55+
{
56+
var weights = new double[] { 0.1, 0.2, -0.1 };
57+
var alpha = 0.01;
58+
var iterations = 1;
59+
60+
var toes = new double[] { 8.5, 9.5, 9.9, 9.0 };
61+
var wlrec = new double[] { 0.65, 0.8, 0.8, 0.9 };
62+
var nfans = new double[] { 1.2, 1.3, 0.5, 1.0 };
63+
64+
var winOrLoseData = new double[] {1, 1, 0, -1};
65+
66+
var predictionGoal = winOrLoseData[0];
67+
var input = new double[] { toes[0], wlrec[0], nfans[0] };
68+
69+
var result = GetLearnByGradientMul(weights, input, predictionGoal, alpha, iterations);
70+
71+
result.SequenceEqual(new double[] { 0.101204, 0.20120400000000002, -0.098796000000000009 }).Should().Be(true);
72+
73+
//var learnWeights =
74+
}
75+
}
76+
}

0 commit comments

Comments
 (0)