-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathperceptron.rs
More file actions
231 lines (185 loc) · 6.07 KB
/
perceptron.rs
File metadata and controls
231 lines (185 loc) · 6.07 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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/// Returns the weights and bias after performing Perceptron algorithm on the input data points.
/// The Perceptron is a binary classification algorithm that learns a linear separator.
/// Labels should be either -1.0 or 1.0 for the two classes.
pub fn perceptron(
data_points: Vec<(Vec<f64>, f64)>,
max_iterations: usize,
learning_rate: f64,
) -> Option<(Vec<f64>, f64)> {
if data_points.is_empty() {
return None;
}
let num_features = data_points[0].0.len();
if num_features == 0 {
return None;
}
let mut weights = vec![0.0; num_features];
let mut bias = 0.0;
for _ in 0..max_iterations {
let mut misclassified = 0;
for (features, label) in &data_points {
let prediction = predict(&weights, bias, features);
if prediction != *label {
misclassified += 1;
for (weight, feature) in weights.iter_mut().zip(features.iter()) {
*weight += learning_rate * label * feature;
}
bias += learning_rate * label;
}
}
if misclassified == 0 {
break;
}
}
Some((weights, bias))
}
/// Make a prediction using the given weights and bias.
fn predict(weights: &[f64], bias: f64, features: &[f64]) -> f64 {
let sum = weights
.iter()
.zip(features.iter())
.map(|(w, x)| w * x)
.sum::<f64>()
+ bias;
if sum >= 0.0 {
1.0
} else {
-1.0
}
}
/// Classify a new data point using the learned weights and bias.
pub fn classify(weights: &[f64], bias: f64, features: &[f64]) -> Option<f64> {
if weights.is_empty() || features.is_empty() {
return None;
}
if weights.len() != features.len() {
return None;
}
Some(predict(weights, bias, features))
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_perceptron_linearly_separable() {
let data = vec![
(vec![1.0, 1.0], 1.0),
(vec![2.0, 2.0], 1.0),
(vec![3.0, 3.0], 1.0),
(vec![-1.0, -1.0], -1.0),
(vec![-2.0, -2.0], -1.0),
(vec![-3.0, -3.0], -1.0),
];
let result = perceptron(data, 100, 0.1);
assert!(result.is_some());
let (weights, bias) = result.unwrap();
let prediction1 = classify(&weights, bias, &[2.5, 2.5]);
assert_eq!(prediction1, Some(1.0));
let prediction2 = classify(&weights, bias, &[-2.5, -2.5]);
assert_eq!(prediction2, Some(-1.0));
}
#[test]
fn test_perceptron_xor_like() {
let data = vec![
(vec![0.0, 0.0], -1.0),
(vec![1.0, 1.0], 1.0),
(vec![0.0, 1.0], -1.0),
(vec![1.0, 0.0], -1.0),
];
let result = perceptron(data, 100, 0.1);
assert!(result.is_some());
let (weights, _bias) = result.unwrap();
assert_eq!(weights.len(), 2);
}
#[test]
fn test_perceptron_single_feature() {
let data = vec![
(vec![1.0], 1.0),
(vec![2.0], 1.0),
(vec![3.0], 1.0),
(vec![-1.0], -1.0),
(vec![-2.0], -1.0),
(vec![-3.0], -1.0),
];
let result = perceptron(data, 100, 0.1);
assert!(result.is_some());
let (weights, bias) = result.unwrap();
assert_eq!(weights.len(), 1);
let prediction1 = classify(&weights, bias, &[5.0]);
assert_eq!(prediction1, Some(1.0));
let prediction2 = classify(&weights, bias, &[-5.0]);
assert_eq!(prediction2, Some(-1.0));
}
#[test]
fn test_perceptron_empty_data() {
let result = perceptron(vec![], 100, 0.1);
assert_eq!(result, None);
}
#[test]
fn test_perceptron_empty_features() {
let data = vec![(vec![], 1.0), (vec![], -1.0)];
let result = perceptron(data, 100, 0.1);
assert_eq!(result, None);
}
#[test]
fn test_perceptron_zero_iterations() {
let data = vec![(vec![1.0, 1.0], 1.0), (vec![-1.0, -1.0], -1.0)];
let result = perceptron(data, 0, 0.1);
assert!(result.is_some());
let (weights, bias) = result.unwrap();
assert_eq!(weights, vec![0.0, 0.0]);
assert_eq!(bias, 0.0);
}
#[test]
fn test_classify_empty_weights() {
let result = classify(&[], 0.0, &[1.0, 2.0]);
assert_eq!(result, None);
}
#[test]
fn test_classify_empty_features() {
let result = classify(&[1.0, 2.0], 0.0, &[]);
assert_eq!(result, None);
}
#[test]
fn test_classify_mismatched_dimensions() {
let result = classify(&[1.0, 2.0], 0.0, &[1.0]);
assert_eq!(result, None);
}
#[test]
fn test_perceptron_different_learning_rates() {
let data = vec![
(vec![1.0, 1.0], 1.0),
(vec![2.0, 2.0], 1.0),
(vec![-1.0, -1.0], -1.0),
(vec![-2.0, -2.0], -1.0),
];
let result1 = perceptron(data.clone(), 100, 0.01);
let result2 = perceptron(data, 100, 1.0);
assert!(result1.is_some());
assert!(result2.is_some());
let (weights1, bias1) = result1.unwrap();
let (weights2, bias2) = result2.unwrap();
let prediction1 = classify(&weights1, bias1, &[3.0, 3.0]);
let prediction2 = classify(&weights2, bias2, &[3.0, 3.0]);
assert_eq!(prediction1, Some(1.0));
assert_eq!(prediction2, Some(1.0));
}
#[test]
fn test_perceptron_with_bias() {
let data = vec![
(vec![1.0], 1.0),
(vec![2.0], 1.0),
(vec![10.0], 1.0),
(vec![0.0], -1.0),
(vec![-1.0], -1.0),
(vec![-10.0], -1.0),
];
let result = perceptron(data, 100, 0.1);
assert!(result.is_some());
let (weights, bias) = result.unwrap();
let prediction_positive = classify(&weights, bias, &[5.0]);
let prediction_negative = classify(&weights, bias, &[-5.0]);
assert_eq!(prediction_positive, Some(1.0));
assert_eq!(prediction_negative, Some(-1.0));
}
}