What can you predict?

Six use cases with context, commented code and the result in an application.

  1. Will this customer churn?

    Identify SaaS accounts to contact before they cancel. Estimate Northwind’s churn probability from product usage and past cancellations.

    Northwind

    78%

    churn probability

    churn.ts
    import { readFile } from 'node:fs/promises';
    import { Spavik } from 'spavik';
    
    // Set SPAVIK_API_KEY in your server environment.
    const spavik = new Spavik();
    
    // Historical accounts: plan, seats, tickets_90d.
    // churn = 1 if the customer cancelled, otherwise 0.
    const history = JSON.parse(
      await readFile('accounts.json', 'utf8')
    );
    const report = await spavik.evaluate(history, {
      target: 'churn'
    });
    const { status, message } = report.assessment as {
      status: string; message: string;
    };
    if (status !== 'better_than_baseline') {
      throw new Error(message);
    }
    
    // Create once, then reuse this model for new accounts.
    const model = await spavik.train(history, {
      target: 'churn'
    });
    
    // Northwind's current data, without the churn label.
    const account = {
      plan: 'pro', seats: 12, tickets_90d: 3
    };
    const result = await model.predict(account);
    
    // proba_1 is the probability of cancellation.
    const risk = Math.round(Number(result.lignes[0].proba_1) * 100);
    console.log('Northwind churn risk:', risk + '%');
  2. Will this lead convert?

    Prioritise prospects in your CRM by their likelihood of buying. Estimate Acme’s conversion probability from trial activity, booked demos and past conversions.

    Acme

    34%

    conversion probability

    conversion.py
    from spavik import Spavik
    
    # Set SPAVIK_API_KEY in your server environment.
    spavik = Spavik()
    
    # leads.csv: visits, trial_days, demo_booked, converted.
    # converted = 1 for a paying customer, otherwise 0.
    history = "leads.csv"
    report = spavik.evaluate(history, target="converted")
    if report["assessment"]["status"] != "better_than_baseline":
        raise ValueError(report["assessment"]["message"])
    
    # Create once, then reuse for new prospects.
    model = spavik.train(history, target="converted")
    
    # Acme's current activity, before a purchase is known.
    prospect = {
        "visits": 8,
        "trial_days": 5,
        "demo_booked": 1,
    }
    result = model.predict(prospect)
    
    # Use the probability of conversion, not the 0/1 label.
    probability = result.lignes[0]["proba_1"]
    print(f"Acme conversion probability: {probability:.0%}")
  3. What will this house sell for?

    Estimate a sale price for listing #218 in San Francisco. The model uses completed sales and property details such as square footage, bedrooms and neighborhood.

    Listing #218

    $1,285,000

    estimated price

    property-price.py
    from spavik import Spavik
    
    # Set SPAVIK_API_KEY in your server environment.
    spavik = Spavik()
    
    # sf_sales.csv: sqft, bedrooms, neighborhood,
    # year_built, price (final sale price in USD).
    history = "sf_sales.csv"
    report = spavik.evaluate(history, target="price")
    if report["assessment"]["status"] != "better_than_baseline":
        raise ValueError(report["assessment"]["message"])
    
    # Create the model from known sale prices.
    model = spavik.train(history, target="price")
    
    # Listing #218: provide the same input columns.
    # The sale price is unknown, so do not include it.
    listing = {
        "sqft": 1450,
        "bedrooms": 3,
        "neighborhood": "Noe Valley",
        "year_built": 1925,
    }
    result = model.predict(listing)
    
    # Show the estimated price on the listing.
    price = result.lignes[0]["prediction"]
    print(f"Estimated price: ${price:,.0f}")
  4. How long will this delivery take?

    Give customers a delivery estimate at checkout. Predict how long parcel #A1042, shipped from San Francisco, will take from distance, carrier, weight and past delivery times.

    Parcel #A1042

    31 hours

    estimated delivery time

    delivery-time.ts
    import { Spavik } from 'spavik';
    
    // Set SPAVIK_API_KEY in your server environment.
    const spavik = new Spavik();
    
    // shipments.csv: distance_miles, carrier, weight_lb,
    // dispatch_day, hours (delivery time in hours).
    const history = 'shipments.csv';
    const report = await spavik.evaluate(history, {
      target: 'hours'
    });
    const { status, message } = report.assessment as {
      status: string; message: string;
    };
    if (status !== 'better_than_baseline') {
      throw new Error(message);
    }
    
    // Create once, then reuse for every new parcel.
    const model = await spavik.train(history, {
      target: 'hours'
    });
    
    // Parcel #A1042, as known at checkout.
    const parcel = {
      distance_miles: 400, carrier: 'ground',
      weight_lb: 5.3, dispatch_day: 'friday'
    };
    const result = await model.predict(parcel);
    
    // Show the estimate at checkout.
    const hours = Math.round(Number(result.lignes[0].prediction));
    console.log(`Parcel #A1042: about ${hours} hours`);
  5. How much electricity will San Francisco need tomorrow?

    Plan production and purchases a day ahead. Forecast tomorrow’s peak demand for San Francisco from the history of daily consumption peaks.

    San Francisco, tomorrow

    1,040 MW

    tomorrow peak demand

    electricity-demand.py
    from spavik import Spavik
    
    # Set SPAVIK_API_KEY in your server environment.
    spavik = Spavik()
    
    # sf_peaks.csv: date, peak_mw.
    # One row per day: the highest demand of that day.
    history = "sf_peaks.csv"
    
    # Check forecasts against past days before using them.
    report = spavik.backtest(
        history,
        target="peak_mw",
        horizon=1,
        timestamp="date",
    )
    print("Backtest:", report["assessment"]["message"])
    
    # A period is one day: horizon=1 forecasts tomorrow.
    forecast = spavik.forecast(
        history,
        target="peak_mw",
        horizon=1,
        timestamp="date",
    )
    
    # Show tomorrow's expected peak in the planning view.
    peak = forecast.points[0]["peak_mw_prediction"]
    print(f"San Francisco, tomorrow's peak demand: {peak:,.0f} MW")
  6. How many orders will we get tomorrow?

    Plan stock and staffing for the next day. Forecast tomorrow’s orders from your store’s daily order history.

    Tomorrow

    1,640

    orders tomorrow

    orders.py
    from spavik import Spavik
    
    # Set SPAVIK_API_KEY in your server environment.
    spavik = Spavik()
    
    # daily_orders.csv: date, orders.
    # One row per completed day, in chronological order.
    history = "daily_orders.csv"
    
    # Check forecasts against past days before using them.
    report = spavik.backtest(
        history,
        target="orders",
        horizon=1,
        timestamp="date",
    )
    print("Backtest:", report["assessment"]["message"])
    
    # A period is one day: horizon=1 forecasts tomorrow.
    forecast = spavik.forecast(
        history,
        target="orders",
        horizon=1,
        timestamp="date",
    )
    
    # Show tomorrow's forecast to the store team.
    orders = forecast.points[0]["orders_prediction"]
    print(f"Orders tomorrow: {orders:,.0f}")