Skip to content

Simple Halo-MNL Model

Open In Colab

# Install necessary requirements

# If you run this notebook on Google Colab, or in standalone mode, you need to install the required packages.
# Uncomment the following lines:

# !pip install choice-learn

# If you run the notebook within the GitHub repository, you need to run the following lines, that can skipped otherwise:
import os
import sys

sys.path.append("../../")
import os
# Remove GPU use
os.environ["CUDA_VISIBLE_DEVICES"] = ""

import numpy as np

from choice_learn.models.halo_mnl import LowRankHaloMNL, HaloMNL
from choice_learn.data import ChoiceDataset
from choice_learn.datasets.base import load_heating
heating_df = load_heating(as_frame=True)

shared_features_by_choice = ["income", "agehed", "rooms"]
choice = ["depvar"]
items_features_by_choice = ["ic.", "oc."]
items = ["hp", "gc", "gr", "ec", "er"]

choices = np.array([items.index(val) for val in heating_df[choice].to_numpy().ravel()])
shared_features_by_choice = heating_df[shared_features_by_choice].to_numpy().astype("float32")
items_features_by_choice = np.stack([heating_df[[feat + item for feat in items_features_by_choice]].to_numpy() for item in items], axis=1)
dataset = ChoiceDataset(items_features_by_choice=items_features_by_choice,
                        choices=choices)
model = LowRankHaloMNL(halo_latent_dim=2, intercept=None)
history = model.fit(dataset, verbose=2, get_report=True)
model = HaloMNL(intercept="item", optimizer="lbfgs")
history = model.fit(dataset, verbose=0, get_report=True)
import matplotlib.pyplot as plt
import tensorflow as tf

plt.imshow(tf.linalg.set_diag(model.trainable_weights[-1], model.zero_diag))
plt.title("Estimated Halo Matrix")
plt.xticks([0., 1., 2., 3., 4.], ["hp", "gc", "gr", "ec", "er"])
plt.yticks([0., 1., 2., 3., 4.], ["hp", "gc", "gr", "ec", "er"])

plt.show()