-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_usage.py
More file actions
341 lines (255 loc) · 8.95 KB
/
example_usage.py
File metadata and controls
341 lines (255 loc) · 8.95 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
"""
Example Usage Script for ML Agent
This script demonstrates how to use the ML Agent and includes
sample dataset generators for testing.
"""
import argparse
import pandas as pd
import numpy as np
from pathlib import Path
from ml_agent import MLAgent
def generate_classification_dataset(n_samples=1000, n_features=10):
"""
Generate a sample classification dataset
Args:
n_samples: Number of samples
n_features: Number of features
Returns:
DataFrame with features and binary target
"""
print(f"Generating classification dataset: {n_samples} samples, {n_features} features")
np.random.seed(42)
# Generate features
data = {}
# Numerical features
for i in range(n_features // 2):
data[f'num_feature_{i + 1}'] = np.random.randn(n_samples)
# Categorical features
categories = ['A', 'B', 'C', 'D']
for i in range(n_features // 2):
data[f'cat_feature_{i + 1}'] = np.random.choice(categories, n_samples)
# Create target with some correlation to features
# Target is based on first numerical feature + some noise
target_prob = 1 / (1 + np.exp(-data['num_feature_1']))
data['target'] = (np.random.random(n_samples) < target_prob).astype(int)
df = pd.DataFrame(data)
# Add some missing values (10% randomly)
for col in df.columns[:-1]: # Don't add missing to target
mask = np.random.random(len(df)) < 0.1
df.loc[mask, col] = np.nan
return df
def generate_regression_dataset(n_samples=1000, n_features=10):
"""
Generate a sample regression dataset
Args:
n_samples: Number of samples
n_features: Number of features
Returns:
DataFrame with features and continuous target
"""
print(f"Generating regression dataset: {n_samples} samples, {n_features} features")
np.random.seed(42)
# Generate features
data = {}
# Numerical features
for i in range(n_features):
data[f'feature_{i + 1}'] = np.random.randn(n_samples)
# Create target as linear combination + noise
target = sum(data[f'feature_{i + 1}'] * (i + 1) for i in range(3))
target += np.random.randn(n_samples) * 2 # Add noise
data['target'] = target
df = pd.DataFrame(data)
# Add some missing values (5% randomly)
for col in df.columns[:-1]:
mask = np.random.random(len(df)) < 0.05
df.loc[mask, col] = np.nan
return df
def generate_iris_dataset():
"""
Generate the classic Iris dataset for classification
Returns:
DataFrame with iris features and species target
"""
print("Generating Iris dataset (classic multiclass classification)")
try:
from sklearn.datasets import load_iris
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = iris.target
return df
except ImportError:
print("⚠️ sklearn.datasets not available, using dummy data")
return generate_classification_dataset(n_samples=150, n_features=4)
def generate_boston_dataset():
"""
Generate a housing price regression dataset
Returns:
DataFrame with housing features and price target
"""
print("Generating housing price dataset (regression)")
np.random.seed(42)
n_samples = 500
data = {
'rooms': np.random.randint(3, 10, n_samples),
'age': np.random.randint(5, 100, n_samples),
'distance_to_city': np.random.uniform(1, 20, n_samples),
'crime_rate': np.random.uniform(0, 10, n_samples),
'tax_rate': np.random.uniform(200, 700, n_samples),
'student_teacher_ratio': np.random.uniform(12, 22, n_samples),
}
# Price based on features with some noise
price = (
data['rooms'] * 30000 +
-data['age'] * 500 +
-data['distance_to_city'] * 5000 +
-data['crime_rate'] * 10000 +
-data['tax_rate'] * 100 +
-data['student_teacher_ratio'] * 2000 +
200000 # Base price
)
# Add noise
price += np.random.randn(n_samples) * 20000
data['price'] = price
return pd.DataFrame(data)
def run_example_classification():
"""Run example with classification dataset"""
print("\n" + "=" * 60)
print("EXAMPLE 1: Classification")
print("=" * 60)
# Generate data
df = generate_classification_dataset(n_samples=1000, n_features=8)
# Save to file
data_dir = Path("sample_data")
data_dir.mkdir(exist_ok=True)
data_path = data_dir / "classification_example.csv"
df.to_csv(data_path, index=False)
print(f"✅ Data saved to: {data_path}")
# Run agent
agent = MLAgent(
data_path=str(data_path),
output_dir="outputs/classification_example",
target_col="target",
problem_type="classification"
)
agent.run()
def run_example_regression():
"""Run example with regression dataset"""
print("\n" + "=" * 60)
print("EXAMPLE 2: Regression")
print("=" * 60)
# Generate data
df = generate_regression_dataset(n_samples=800, n_features=10)
# Save to file
data_dir = Path("sample_data")
data_dir.mkdir(exist_ok=True)
data_path = data_dir / "regression_example.csv"
df.to_csv(data_path, index=False)
print(f"✅ Data saved to: {data_path}")
# Run agent
agent = MLAgent(
data_path=str(data_path),
output_dir="outputs/regression_example",
target_col="target",
problem_type="regression"
)
agent.run()
def run_example_iris():
"""Run example with Iris dataset"""
print("\n" + "=" * 60)
print("EXAMPLE 3: Iris Dataset (Multiclass Classification)")
print("=" * 60)
# Generate data
df = generate_iris_dataset()
# Save to file
data_dir = Path("sample_data")
data_dir.mkdir(exist_ok=True)
data_path = data_dir / "iris.csv"
df.to_csv(data_path, index=False)
print(f"✅ Data saved to: {data_path}")
# Run agent (auto-detect everything)
agent = MLAgent(
data_path=str(data_path),
output_dir="outputs/iris_example"
)
agent.run()
def run_example_housing():
"""Run example with housing price dataset"""
print("\n" + "=" * 60)
print("EXAMPLE 4: Housing Prices (Regression)")
print("=" * 60)
# Generate data
df = generate_boston_dataset()
# Save to file
data_dir = Path("sample_data")
data_dir.mkdir(exist_ok=True)
data_path = data_dir / "housing.csv"
df.to_csv(data_path, index=False)
print(f"✅ Data saved to: {data_path}")
# Run agent
agent = MLAgent(
data_path=str(data_path),
output_dir="outputs/housing_example"
)
agent.run()
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="ML Agent Examples - Generate and run sample datasets"
)
parser.add_argument(
'--example',
type=str,
choices=['classification', 'regression', 'iris', 'housing', 'all'],
default='iris',
help='Which example to run'
)
parser.add_argument(
'--generate-data',
action='store_true',
help='Only generate data, do not run agent'
)
args = parser.parse_args()
# Create sample data directory
Path("sample_data").mkdir(exist_ok=True)
if args.generate_data:
print("Generating sample datasets...")
# Generate all datasets
df_class = generate_classification_dataset()
df_class.to_csv("sample_data/classification_example.csv", index=False)
print("✅ classification_example.csv")
df_reg = generate_regression_dataset()
df_reg.to_csv("sample_data/regression_example.csv", index=False)
print("✅ regression_example.csv")
df_iris = generate_iris_dataset()
df_iris.to_csv("sample_data/iris.csv", index=False)
print("✅ iris.csv")
df_housing = generate_boston_dataset()
df_housing.to_csv("sample_data/housing.csv", index=False)
print("✅ housing.csv")
print("\n✅ All sample datasets generated in 'sample_data/' directory")
print("\nRun examples with:")
print(" python example_usage.py --example iris")
print(" python example_usage.py --example classification")
print(" python example_usage.py --example regression")
print(" python example_usage.py --example housing")
return
# Run examples
if args.example == 'classification':
run_example_classification()
elif args.example == 'regression':
run_example_regression()
elif args.example == 'iris':
run_example_iris()
elif args.example == 'housing':
run_example_housing()
elif args.example == 'all':
run_example_classification()
run_example_regression()
run_example_iris()
run_example_housing()
print("\n" + "=" * 60)
print("✅ ALL EXAMPLES COMPLETE")
print("=" * 60)
print("\nCheck the outputs/ directory for results!")
if __name__ == "__main__":
main()