Quickstart
1
Initialize the Client
from viewai_client import ViewAIClient
# Initialize with API key
client = ViewAIClient(api_key="your-api-key-here")
# Or use environment variable
import os
client = ViewAIClient(api_key=os.getenv("VIEWAI_API_KEY"))# Check if the API is reachable
health = client.health.check_connection()
if health.healthy:
print(f"✓ Connected successfully ({health.response_time_ms:.0f}ms)")
else:
print(f"✗ Connection failed: {health.message}")2
Prepare Your Data
import pandas as pd
import numpy as np
# Create sample customer churn dataset
np.random.seed(42)
n_samples = 1000
data = {
'age': np.random.randint(18, 70, n_samples),
'income': np.random.randint(30000, 150000, n_samples),
'tenure_months': np.random.randint(1, 60, n_samples),
'monthly_charges': np.random.uniform(20, 200, n_samples),
'total_purchases': np.random.randint(0, 50, n_samples),
'support_calls': np.random.randint(0, 10, n_samples),
'contract_type': np.random.choice(['monthly', 'annual', 'biannual'], n_samples),
'payment_method': np.random.choice(['credit', 'debit', 'paypal'], n_samples),
# Target variable
'churn': np.random.choice([0, 1], n_samples, p=[0.7, 0.3])
}
df = pd.DataFrame(data)
print(f"Dataset shape: {df.shape}")
print(f"Churn rate: {df['churn'].mean():.2%}")3
Set Up Workspace
# Get default workspace
workspace = client.retrieve_default_workspace()
print(f"Using workspace: {workspace.workspace_name}")
# Or list all accessible workspaces
workspaces = client.list_accessible_workspaces()
for ws in workspaces:
print(f" - {ws.workspace_name} (ID: {ws.workspace_id})")
# Set current workspace
client.set_current_workspace(workspace)4
Train a Model
# Initiate training job
print("Starting model training...")
training_job = client.training_service.initiate_training_job(
dataset=df,
target_column='churn',
workspace=workspace,
model_name='Customer Churn Predictor',
description='Predicts customer churn based on usage patterns',
wait_for_completion=True # Wait for training to complete
)
if training_job and 'completed' in training_job.status:
print(f"✓ Training completed!")
print(f" Model ID: {training_job.job_id}")
print(f" Dashboard: {training_job.dashboard_url}")
model_id = training_job.job_id
else:
print("✗ Training failed")Training Progress: 100%|██████████| 30/30 [02:15<00:00]
✓ Training completed! View model at: https://app.viewai.ca/dashboard/model-1235
Make Predictions
# Prepare test data (single customer)
customer_data = {
'age': 35,
'income': 75000,
'tenure_months': 24,
'monthly_charges': 85.50,
'total_purchases': 15,
'support_calls': 2,
'contract_type': 'monthly',
'payment_method': 'credit'
}
# Make prediction
prediction = client.prediction_service.execute_single_point_prediction(
data=customer_data,
model_id=model_id
)
if prediction:
print("Prediction results:")
print(f" Raw prediction: {prediction.get_raw_prediction()}")
print(f" Probabilities: {prediction.get_probabilities()}")Prediction results:
Raw prediction: {'predicted_churn': 1, 'probability_0': 0.32, 'probability_1': 0.68}
Probabilities: {'probability_0': 0.32, 'probability_1': 0.68}# Prepare batch data (multiple customers)
batch_customers = [
{'age': 25, 'income': 45000, 'tenure_months': 6, ...},
{'age': 50, 'income': 95000, 'tenure_months': 48, ...},
{'age': 33, 'income': 67000, 'tenure_months': 18, ...}
]
# Or use a DataFrame
batch_df = df.drop('churn', axis=1).head(10)
# Make batch prediction
batch_job = client.prediction_service.execute_batch_prediction(
data=batch_df,
model_id=model_id,
wait_for_completion=True
)
if batch_job and batch_job.status == 'completed':
print(f"✓ Batch prediction completed!")
print(f" Job ID: {batch_job.job_id}")
print(f" View results: {batch_job.dashboard_url}")6
Monitor Your Model
# Get model from registry
models = client.registry.list_models()
our_model = next((m for m in models if m.get('dashboard_id') == model_id), None)
if our_model:
print(f"Model: {our_model.get('dashboard_name')}")
print(f" Type: {our_model.get('type')}")
print(f" Status: {our_model.get('status')}")
print(f" Created: {our_model.get('created_at')}")
# Run diagnostics
diagnostics = client.health.run_diagnostics()
for check_name, result in diagnostics.items():
status = '✓' if result.healthy else '✗'
print(f"{status} {check_name}: {result.message}")Complete Example
from viewai_client import ViewAIClient
import pandas as pd
import numpy as np
import os
# Initialize client
client = ViewAIClient(api_key=os.getenv("VIEWAI_API_KEY"))
# Verify connection
health = client.health.check_connection()
if not health.healthy:
print("Failed to connect to ViewAI API")
exit(1)
# Create sample data
np.random.seed(42)
df = pd.DataFrame({
'age': np.random.randint(18, 70, 1000),
'income': np.random.randint(30000, 150000, 1000),
'tenure_months': np.random.randint(1, 60, 1000),
'churn': np.random.choice([0, 1], 1000, p=[0.7, 0.3])
})
# Get workspace
workspace = client.retrieve_default_workspace()
client.set_current_workspace(workspace)
# Train model
print("Training model...")
training_job = client.training_service.initiate_training_job(
dataset=df,
target_column='churn',
workspace=workspace,
model_name='Quick Start Model',
wait_for_completion=True
)
if not training_job or 'completed' not in training_job.status:
print("Training failed!")
exit(1)
model_id = training_job.job_id
print(f"Model trained successfully: {model_id}")
# Make prediction
test_data = {
'age': 35,
'income': 75000,
'tenure_months': 24
}
prediction = client.prediction_service.execute_single_point_prediction(
data=test_data,
model_id=model_id
)
print(f"Prediction: {prediction.get_raw_prediction()}")
print("✓ Quick start completed successfully!")Common Patterns
Train and Deploy
Using Context Manager
Configuration Object
Next Steps
Troubleshooting
Best Practices
Support
Was this helpful?