File size: 2,019 Bytes
ff1c689
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from codecarbon import EmissionsTracker

# Import necessary libraries
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score
import pandas as pd
import numpy as np

# Let's create a sample dataset (you can replace this with your own data)
def create_sample_data():
    np.random.seed(42)
    n_samples = 10000
    
    # Create features (X)
    X = np.random.randn(n_samples, 4)  # 4 features
    
    # Create target (y) - binary classification
    y = (X[:, 0] + X[:, 1] + X[:, 2] > 0).astype(int)
    
    return X, y

# Get data (replace this with your data loading code)
X, y = create_sample_data()
tracker = EmissionsTracker()

def submit(username):

    tracker.start()

    tracker.start_task("train_model")
    # Split the data into training and testing sets
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.2, random_state=42
    )
        
    # Initialize the model
    rf_model = RandomForestClassifier(
        n_estimators=1000,
        max_depth=5,
        random_state=42
    )

    # Train the model
    print("Training the model...")
    rf_model.fit(X_train, y_train)

    training_emissions = tracker.stop_task()

    tracker.start_task("inference")
    rf_model.predict(X_test)
    inference_emissions = tracker.stop_task()

    emissions = inference_emissions.emissions
    energy = inference_emissions.energy_consumed

    return [emissions, energy]

# Update the interface configuration
demo = gr.Interface(
    fn=submit,
    inputs=gr.Textbox(label="Username"),
    outputs=[
        gr.Number(label="Emissions (kgCO2eq)", precision=6),
        gr.Number(label="Energy Consumed (kWh)", precision=6)
    ],
    title="Carbon Emissions Tracker",
    description="Track the carbon emissions and energy consumption of model training and inference."
)

# Launch the Gradio interface
if __name__ == "__main__":
    demo.launch()