def number_of_nonzero_coef(X, model):
    """
    Calculates the number of non-zero coefficients in a model. Useful for
    evaluating models with an L1 penalty.

    Parameters
    ----------
    X : numpy array or pandas dataframe
        The design or feature matrix.
    model : sklearn object, or similar
        The model, which needs to have a coef_ attribute.

    Returns
    -------
    num_coef : int
        Number of non-zero coefficients.

    """
    num_coef = None
    try:
        num_coef = sum((True if c != 0 else False for c in model.coef_.reshape(-1,)))
    except:
        num_coef = X.shape[1]
    return num_coef