forked from SciSharp/NumSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNdArray.Std.cs
More file actions
81 lines (70 loc) · 2.85 KB
/
NdArray.Std.cs
File metadata and controls
81 lines (70 loc) · 2.85 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NumSharp.Core.Extensions;
namespace NumSharp.Core
{
public partial class NDArray
{
public NDArray std(int axis = -1, Type dtype = null)
{
dtype = (dtype == null) ? typeof(double) : dtype;
// in case have 1D array but user still using axis 0 ... can be used like -1
axis = (axis == 0 && this.ndim == 1) ? -1 : axis;
Array data = this.Storage.GetData();
NDArray stdArr = new NDArray(dtype);
if (axis == -1)
{
double mean = this.mean(axis).MakeGeneric<double>()[0];
double sum = 0;
for(int idx = 0; idx < data.Length;idx++)
sum += Math.Pow(Convert.ToDouble(data.GetValue(idx)) - mean,2);
double stdValue = Math.Sqrt(sum / this.size);
stdArr.Storage.Allocate(dtype,new Shape(1),1);
var puffer = Array.CreateInstance(dtype,1);
puffer.SetValue(stdValue,0);
stdArr.Storage.SetData(puffer);
}
else
{
double[] stdValue = null;
if (axis == 0)
{
double[] sum = new double[this.shape[1]];
stdValue = new double[sum.Length];
double[] mean = this.mean(axis).Storage.GetData<double>();
for (int idx = 0; idx < sum.Length;idx++)
{
for(int jdx =0; jdx < this.shape[0];jdx++)
{
sum[idx] += Math.Pow(Convert.ToDouble(this[jdx,idx]) - mean[idx],2);
}
stdValue[idx] = Math.Sqrt(sum[idx] / this.shape[0]);
}
}
else if (axis == 1)
{
double[] sum = new double[this.shape[0]];
stdValue = new double[sum.Length];
double[] mean = this.mean(axis).Storage.GetData<double>();
for (int idx = 0; idx < sum.Length;idx++)
{
for(int jdx =0; jdx < this.shape[1];jdx++)
{
sum[idx] += Math.Pow(Convert.ToDouble(this[idx,jdx]) - mean[idx],2);
}
stdValue[idx] = Math.Sqrt(sum[idx] / this.shape[1]);
}
}
else
{
throw new NotImplementedException();
}
stdArr.Storage.Allocate(dtype,new Shape(stdValue.Length),1);
stdArr.Storage.SetData(stdValue);
}
return stdArr;
}
}
}