-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_model.py
More file actions
285 lines (225 loc) · 9.14 KB
/
train_model.py
File metadata and controls
285 lines (225 loc) · 9.14 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""
TinyML Training Pipeline for Slip Detection
Uses Decision Tree classifier optimized for Arduino Uno deployment
"""
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import joblib
import json
import os
class SlipDetectionTrainer:
def __init__(self, max_depth=5, min_samples_split=10, min_samples_leaf=5):
"""
Initialize trainer with parameters optimized for Arduino Uno
Args:
max_depth: Maximum depth of tree (lower = smaller model)
min_samples_split: Minimum samples to split a node
min_samples_leaf: Minimum samples in a leaf node
"""
self.max_depth = max_depth
self.min_samples_split = min_samples_split
self.min_samples_leaf = min_samples_leaf
self.model = None
self.feature_names = None
def load_data(self, data_path):
"""
Load training data from CSV file
Expected CSV format:
- Columns: feature1, feature2, ..., featureN, label
- Label: 0 = no slip, 1 = slip
"""
df = pd.read_csv(data_path)
# Separate features and labels
self.feature_names = [col for col in df.columns if col != 'label']
X = df[self.feature_names].values
y = df['label'].values
# Convert labels to integers (handle float labels like 0.0, 1.0)
y = y.astype(int)
print(f"Loaded {len(X)} samples with {len(self.feature_names)} features")
print(f"Features: {self.feature_names}")
print(f"Class distribution: {np.bincount(y)}")
return X, y
def train(self, X, y, test_size=0.2, random_state=42):
"""
Train decision tree model
"""
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=test_size, random_state=random_state, stratify=y
)
print(f"\nTraining set: {len(X_train)} samples")
print(f"Test set: {len(X_test)} samples")
# Create and train model
self.model = DecisionTreeClassifier(
max_depth=self.max_depth,
min_samples_split=self.min_samples_split,
min_samples_leaf=self.min_samples_leaf,
random_state=random_state,
criterion='gini'
)
print("\nTraining model...")
self.model.fit(X_train, y_train)
# Evaluate
train_acc = accuracy_score(y_train, self.model.predict(X_train))
test_acc = accuracy_score(y_test, self.model.predict(X_test))
print(f"\nTraining Accuracy: {train_acc:.4f}")
print(f"Test Accuracy: {test_acc:.4f}")
print("\nClassification Report:")
print(classification_report(y_test, self.model.predict(X_test)))
print("\nConfusion Matrix:")
print(confusion_matrix(y_test, self.model.predict(X_test)))
# Print tree structure
print("\nDecision Tree Structure:")
print(export_text(self.model, feature_names=self.feature_names, max_depth=10))
return X_test, y_test
def save_model(self, model_path='model.pkl'):
"""Save trained model"""
if self.model is None:
raise ValueError("Model not trained yet")
joblib.dump(self.model, model_path)
print(f"\nModel saved to {model_path}")
def export_for_arduino(self, output_path='arduino_model.h'):
"""
Export decision tree as Arduino C++ code
"""
if self.model is None:
raise ValueError("Model not trained yet")
tree = self.model.tree_
# Generate Arduino header file
code = self._generate_arduino_code(tree)
with open(output_path, 'w') as f:
f.write(code)
print(f"\nArduino model exported to {output_path}")
# Also save metadata
metadata = {
'n_features': int(len(self.feature_names)),
'feature_names': self.feature_names,
'n_nodes': int(tree.node_count),
'max_depth': int(self.max_depth),
'n_classes': int(tree.n_classes[0])
}
with open('model_metadata.json', 'w') as f:
json.dump(metadata, f, indent=2)
print(f"Model metadata saved to model_metadata.json")
def _generate_arduino_code(self, tree):
"""Generate Arduino C++ code for decision tree inference"""
# Get tree structure
children_left = tree.children_left.tolist()
children_right = tree.children_right.tolist()
feature = tree.feature.tolist()
threshold = tree.threshold.tolist()
value = tree.value.tolist()
# Count nodes
n_nodes = tree.node_count
code = f"""/*
* Auto-generated Decision Tree Model for Slip Detection
* Generated from scikit-learn DecisionTreeClassifier
*
* Model Statistics:
* - Nodes: {n_nodes}
* - Features: {len(self.feature_names)}
* - Max Depth: {self.max_depth}
*/
#ifndef SLIP_DETECTION_MODEL_H
#define SLIP_DETECTION_MODEL_H
#include <Arduino.h>
// Model configuration
#define N_NODES {n_nodes}
#define N_FEATURES {len(self.feature_names)}
// Decision tree structure
static const int children_left[N_NODES] = {{ {', '.join(map(str, children_left))} }};
static const int children_right[N_NODES] = {{ {', '.join(map(str, children_right))} }};
static const int feature[N_NODES] = {{ {', '.join(map(str, feature))} }};
static const float threshold[N_NODES] = {{ {', '.join([f'{t:.6f}f' for t in threshold])} }};
// Leaf node predictions (value[node][class])
static const float value[N_NODES][2] = {{
"""
# Add value array
for i, val in enumerate(value):
# Normalize probabilities
total = val[0][0] + val[0][1] if len(val[0]) > 1 else val[0][0]
prob_0 = val[0][0] / total if total > 0 else 0.0
prob_1 = val[0][1] / total if len(val[0]) > 1 else 0.0
code += f" {{ {prob_0:.6f}f, {prob_1:.6f}f }}, // Node {i}\n"
code += """};
/**
* Predict slip detection from sensor features
*
* @param features Array of N_FEATURES sensor readings
* @return 0 = no slip, 1 = slip detected
*/
int predict_slip(float features[N_FEATURES]) {
int node = 0;
while (children_left[node] != children_right[node]) {
// Not a leaf node, traverse tree
if (features[feature[node]] <= threshold[node]) {
node = children_left[node];
} else {
node = children_right[node];
}
}
// Leaf node reached, return prediction
return (value[node][1] > value[node][0]) ? 1 : 0;
}
/**
* Get prediction probability
*
* @param features Array of N_FEATURES sensor readings
* @return Probability of slip (0.0 to 1.0)
*/
float predict_slip_probability(float features[N_FEATURES]) {
int node = 0;
while (children_left[node] != children_right[node]) {
if (features[feature[node]] <= threshold[node]) {
node = children_left[node];
} else {
node = children_right[node];
}
}
return value[node][1];
}
#endif // SLIP_DETECTION_MODEL_H
"""
return code
def main():
"""Main training pipeline"""
import argparse
parser = argparse.ArgumentParser(description='Train slip detection model')
parser.add_argument('--data', type=str, default='data/training_data.csv',
help='Path to training data CSV')
parser.add_argument('--max-depth', type=int, default=5,
help='Maximum tree depth')
parser.add_argument('--min-samples-split', type=int, default=10,
help='Minimum samples to split')
parser.add_argument('--min-samples-leaf', type=int, default=5,
help='Minimum samples in leaf')
parser.add_argument('--output-model', type=str, default='model.pkl',
help='Output path for saved model')
parser.add_argument('--output-arduino', type=str, default='arduino_model.h',
help='Output path for Arduino header')
args = parser.parse_args()
# Create trainer
trainer = SlipDetectionTrainer(
max_depth=args.max_depth,
min_samples_split=args.min_samples_split,
min_samples_leaf=args.min_samples_leaf
)
# Load and train
if not os.path.exists(args.data):
print(f"Error: Data file {args.data} not found!")
print("Please create training data or use generate_sample_data.py")
return
X, y = trainer.load_data(args.data)
trainer.train(X, y)
# Save model
trainer.save_model(args.output_model)
# Export for Arduino
trainer.export_for_arduino(args.output_arduino)
print("\n✓ Training pipeline completed successfully!")
print(f"✓ Model saved: {args.output_model}")
print(f"✓ Arduino code: {args.output_arduino}")
if __name__ == '__main__':
main()