Spaces:
Sleeping
Sleeping
File size: 13,351 Bytes
64b49ea |
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 |
import gradio as gr
import numpy as np
import pandas as pd
from typing import Dict
import time
from sklearn.metrics import accuracy_score, mean_squared_error, classification_report
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
# Additional ML helper functions
def evaluate_ml_solution(y_true, y_pred, task_type='classification'):
"""Evaluate ML model predictions"""
if task_type == 'classification':
accuracy = accuracy_score(y_true, y_pred)
report = classification_report(y_true, y_pred)
return f"Accuracy: {accuracy:.4f}\n\nDetailed Report:\n{report}"
else:
mse = mean_squared_error(y_true, y_pred)
rmse = np.sqrt(mse)
return f"MSE: {mse:.4f}\nRMSE: {rmse:.4f}"
# Extended problem set including ML problems
PROBLEM_DATA = {
# Original Algorithm Problems
"Valid Parentheses": {
"type": "algorithm",
"difficulty": "easy",
"description": "Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.",
"test_cases": [
{'input': "()", 'expected': True},
{'input': "()[]{}", 'expected': True},
{'input': "(]", 'expected': False}
],
"sample_input": "()",
"starter_code": """def solution(s: str) -> bool:
# Write your solution here
pass"""
},
# ML Classification Problem
"Binary Classification": {
"type": "ml_classification",
"difficulty": "medium",
"description": "Create a binary classifier for the provided dataset. Features include numerical values, target is binary (0/1).",
"test_cases": [
{
'input': pd.DataFrame({
'feature1': [1.2, 2.3, 3.4, 4.5],
'feature2': [2.1, 3.2, 4.3, 5.4]
}),
'expected': np.array([0, 1, 1, 0])
}
],
"starter_code": """class MLSolution:
def __init__(self):
self.model = None
def fit(self, X, y):
# Implement training logic
pass
def predict(self, X):
# Implement prediction logic
return np.zeros(len(X))"""
},
# Neural Network Problem
"Simple Neural Network": {
"type": "deep_learning",
"difficulty": "hard",
"description": "Implement a simple neural network for binary classification using PyTorch.",
"test_cases": [
{
'input': torch.randn(10, 5), # 10 samples, 5 features
'expected': torch.randint(0, 2, (10,))
}
],
"starter_code": """class NeuralNetwork(nn.Module):
def __init__(self, input_size):
super(NeuralNetwork, self).__init__()
self.layer1 = nn.Linear(input_size, 64)
self.layer2 = nn.Linear(64, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = torch.relu(self.layer1(x))
x = self.sigmoid(self.layer2(x))
return x"""
},
# Regression Problem
"House Price Prediction": {
"type": "ml_regression",
"difficulty": "medium",
"description": "Implement a regression model to predict house prices based on features like size, location, etc.",
"test_cases": [
{
'input': pd.DataFrame({
'size': [1500, 2000, 2500],
'rooms': [3, 4, 5],
'location_score': [8, 7, 9]
}),
'expected': np.array([250000, 300000, 400000])
}
],
"starter_code": """class RegressionSolution:
def __init__(self):
self.model = None
def fit(self, X, y):
# Implement training logic
pass
def predict(self, X):
# Implement prediction logic
return np.zeros(len(X))"""
}
}
def create_sample_data(problem_type: str) -> Dict:
"""Create sample datasets for ML problems"""
if problem_type == 'ml_classification':
X_train = pd.DataFrame(np.random.randn(100, 2), columns=['feature1', 'feature2'])
y_train = np.random.randint(0, 2, 100)
X_test = pd.DataFrame(np.random.randn(20, 2), columns=['feature1', 'feature2'])
y_test = np.random.randint(0, 2, 20)
return {'X_train': X_train, 'y_train': y_train, 'X_test': X_test, 'y_test': y_test}
elif problem_type == 'ml_regression':
X_train = pd.DataFrame(np.random.randn(100, 3),
columns=['size', 'rooms', 'location_score'])
y_train = np.random.uniform(200000, 500000, 100)
X_test = pd.DataFrame(np.random.randn(20, 3),
columns=['size', 'rooms', 'location_score'])
y_test = np.random.uniform(200000, 500000, 20)
return {'X_train': X_train, 'y_train': y_train, 'X_test': X_test, 'y_test': y_test}
elif problem_type == 'deep_learning':
# Generate sample data for neural network
X_train = torch.randn(100, 5) # 100 samples, 5 features
y_train = torch.randint(0, 2, (100,)) # Binary classification
X_test = torch.randn(20, 5) # 20 samples, 5 features
y_test = torch.randint(0, 2, (20,)) # Binary classification
return {'X_train': X_train, 'y_train': y_train, 'X_test': X_test, 'y_test': y_test}
return None
def run_tests(problem_name: str, user_code: str) -> str:
try:
problem = PROBLEM_DATA[problem_name]
if problem["type"] == "algorithm":
# Execute algorithm problems
namespace = {}
exec(user_code, namespace)
results = []
for i, test in enumerate(problem["test_cases"], 1):
try:
start_time = time.time()
output = namespace["solution"](test["input"])
execution_time = time.time() - start_time
passed = output == test["expected"]
results.append(
f"Test #{i}:\n"
f"Input: {test['input']}\n"
f"Expected: {test['expected']}\n"
f"Got: {output}\n"
f"Time: {execution_time:.6f}s\n"
f"Status: {'✓ PASSED' if passed else '✗ FAILED'}\n"
)
except Exception as e:
results.append(f"Test #{i} Error: {str(e)}\n")
return "\n".join(results)
else:
# Execute ML problems
namespace = {"np": np, "pd": pd, "nn": nn, "torch": torch}
exec(user_code, namespace)
# Create sample data
data = create_sample_data(problem["type"])
if not data:
return "Error: Invalid problem type"
try:
if problem["type"] in ["ml_classification", "ml_regression"]:
# Initialize and train model
model = namespace["MLSolution"]()
model.fit(data["X_train"], data["y_train"])
# Make predictions
predictions = model.predict(data["X_test"])
# Evaluate
eval_result = evaluate_ml_solution(
data["y_test"],
predictions,
"classification" if problem["type"] == "ml_classification" else "regression"
)
return f"Model Evaluation:\n{eval_result}"
elif problem["type"] == "deep_learning":
# Initialize neural network
model = namespace["NeuralNetwork"](data["X_train"].shape[1])
criterion = nn.BCELoss() # Binary cross-entropy loss
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# Convert data to tensors
X_train = data["X_train"].float()
y_train = data["y_train"].float().view(-1, 1)
X_test = data["X_test"].float()
y_test = data["y_test"].float().view(-1, 1)
# Train the model
for epoch in range(10): # 10 epochs
optimizer.zero_grad()
outputs = model(X_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
# Evaluate the model
with torch.no_grad():
predictions = model(X_test)
predictions = (predictions > 0.5).float() # Convert probabilities to binary predictions
accuracy = (predictions == y_test).float().mean()
return f"Neural Network Evaluation:\nAccuracy: {accuracy.item():.4f}"
except Exception as e:
return f"Error in ML execution: {str(e)}"
except Exception as e:
return f"Error in code execution: {str(e)}"
# Create Gradio interface with enhanced features
def create_interface():
with gr.Blocks(title="Advanced LeetCode & ML Testing Platform") as iface:
# All components and event handlers must be defined within this 'with' block
gr.Markdown("# Advanced LeetCode & ML Testing Platform")
with gr.Tabs():
with gr.Tab("Problem Solving"):
problem_dropdown = gr.Dropdown(
choices=list(PROBLEM_DATA.keys()),
label="Select Problem"
)
difficulty_display = gr.Textbox(label="Difficulty")
problem_type = gr.Textbox(label="Problem Type")
description_text = gr.Textbox(label="Description", lines=5)
code_input = gr.Textbox(label="Your Code", lines=10, value="")
results_output = gr.Textbox(label="Test Results", value="", lines=10)
with gr.Row():
run_button = gr.Button("Run Tests")
clear_button = gr.Button("Clear Code")
# Event handler for Run Tests button (inside Blocks context)
run_button.click(
run_tests,
inputs=[problem_dropdown, code_input],
outputs=[results_output]
)
# Event handler for Clear Code button (inside Blocks context)
clear_button.click(
lambda: "",
inputs=[],
outputs=[code_input]
)
# Event handler for problem selection (inside Blocks context)
def update_problem_info(problem_name):
problem = PROBLEM_DATA[problem_name]
return (
problem["difficulty"],
problem["type"],
problem["description"],
problem["starter_code"],
"" # Clear results
)
problem_dropdown.change(
update_problem_info,
inputs=[problem_dropdown],
outputs=[
difficulty_display,
problem_type,
description_text,
code_input,
results_output
]
)
with gr.Tab("Visualization"):
with gr.Row():
plot_type = gr.Dropdown(
choices=["Learning Curve", "Confusion Matrix", "Feature Importance"],
label="Select Plot Type"
)
visualize_button = gr.Button("Generate Visualization")
plot_output = gr.Plot(label="Visualization")
# Event handler for visualization
def generate_visualization(plot_type):
if plot_type == "Learning Curve":
# Example learning curve
plt.figure()
plt.plot([0, 1, 2, 3, 4], [0.8, 0.7, 0.6, 0.5, 0.4], label="Training Loss")
plt.plot([0, 1, 2, 3, 4], [0.9, 0.8, 0.7, 0.6, 0.5], label="Validation Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.title("Learning Curve")
plt.legend()
return plt
else:
return None
visualize_button.click(
generate_visualization,
inputs=[plot_type],
outputs=[plot_output]
)
return iface
if __name__ == "__main__":
iface = create_interface()
iface.launch() |