-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVector.cs
More file actions
133 lines (111 loc) · 2.85 KB
/
Vector.cs
File metadata and controls
133 lines (111 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
using System;
using System.Diagnostics;
namespace FastText
{
public class Vector
{
protected float[] data_;
public float[] Data => data_;
public float this[long key]
{
get
{
return data_[key];
}
set
{
data_[key] = value;
}
}
public Vector(long m)
{
data_ = new float[m];
}
public long Size()
{
return data_.Length;
}
public void Zero()
{
Array.Clear(data_, 0, data_.Length);
}
public float Norm()
{
var sum = 0f;
for (long i = 0; i < Size(); i++)
{
sum += data_[i] * data_[i];
}
return (float)Math.Sqrt(sum);
}
public void mul(float a)
{
for (long i = 0; i < Size(); i++)
{
data_[i] *= a;
}
}
public void AddVector(Vector source)
{
Debug.Assert(Size() == source.Size());
for (long i = 0; i < Size(); i++)
{
data_[i] += source.data_[i];
}
}
public void AddVector(Vector source, float s)
{
Debug.Assert(Size() == source.Size());
for (long i = 0; i < Size(); i++)
{
data_[i] += s * source.data_[i];
}
}
public void AddRow(Matrix A, long i, float a)
{
Debug.Assert(i >= 0);
Debug.Assert(i < A.Size(0));
Debug.Assert(Size() == A.Size(1));
A.AddRowToVector(data_, (int)i, a);
}
public void AddRow(Matrix A, long i)
{
Debug.Assert(i >= 0);
Debug.Assert(i < A.Size(0));
Debug.Assert(Size() == A.Size(1));
A.AddRowToVector(data_, (int)i);
}
public void Mul(Matrix A, Vector vec)
{
Debug.Assert(A.Size(0) == Size());
Debug.Assert(A.Size(1) == vec.Size());
for (long i = 0; i < Size(); i++)
{
data_[i] = A.DotRow(vec.data_, i);
}
}
public long ArgMax()
{
var max = data_[0];
long argmax = 0;
for (long i = 1; i < Size(); i++)
{
if (data_[i] > max)
{
max = data_[i];
argmax = i;
}
}
return argmax;
}
public override string ToString()
{
var result = string.Empty;
for (long j = 0; j < data_.Length; j++)
{
result += $"{data_[j]:0.#####} ";
}
return result;
}
}
}