Skip to content

API Reference

from_df

from_df(df, dtype: DTypeLike = np.float64, sparse_threshold: float = 0.1, cat_threshold: int = 4, object_as_cat: bool = False, cat_position: str = 'expand', drop_first: bool = False, categorical_format: str = '{name}[{category}]', cat_missing_method: str = 'fail', cat_missing_name: str = '(MISSING)') -> MatrixBase

Transform a DataFrame into an efficient SplitMatrix.

Parameters:

Name Type Description Default
df DataFrame

This can be any dataframes supported by narwhals (pandas, polars, etc.).

required
dtype dtype

dtype of all sub-matrices of the resulting SplitMatrix.

np.float64
sparse_threshold float

Density threshold at or below which numerical columns that are not already sparse will be stored in a sparse format. This threshold is not used to densify columns that are already sparse.

0.1
cat_threshold int

Number of levels of a categorical column under which the column will be stored as sparse one-hot-encoded columns instead of CategoricalMatrix

4
object_as_cat bool

If True, DataFrame columns stored as python objects will be treated as categorical columns.

False
cat_position str {'end'|'expand'}

Position of the categorical variable in the index. If "last", all the categoricals (including the ones that did not satisfy cat_threshold) will be placed at the end of the index list. If "expand", all the variables will remain in the same order.

'expand'
drop_first bool

If true, categoricals variables will have their first category dropped. This allows multiple categorical variables to be included in an unregularized model. If False, all categories are included.

False
cat_missing_method str

How to handle missing values in categorical columns:

  • if 'fail', raise an error if there are missing values.
  • if 'zero', missing values will represent all-zero indicator columns.
  • if 'convert', missing values will be converted to the '(MISSING)' category.
'fail'
cat_missing_name str

Name of the category to which missing values will be converted if cat_missing_method='convert'.

'(MISSING)'

Returns:

Type Description
SplitMatrix
Source code in src/tabmat/constructor.py
 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
@nw.narwhalify(eager_only=True)
def from_df(
    df,
    dtype: numpy.typing.DTypeLike = np.float64,
    sparse_threshold: float = 0.1,
    cat_threshold: int = 4,
    object_as_cat: bool = False,
    cat_position: str = "expand",
    drop_first: bool = False,
    categorical_format: str = "{name}[{category}]",
    cat_missing_method: str = "fail",
    cat_missing_name: str = "(MISSING)",
) -> MatrixBase:
    """
    Transform a DataFrame into an efficient SplitMatrix.

    Parameters
    ----------
    df : DataFrame
        This can be any dataframes supported by narwhals (pandas, polars, etc.).
    dtype : np.dtype, default np.float64
        dtype of all sub-matrices of the resulting SplitMatrix.
    sparse_threshold : float, default 0.1
        Density threshold at or below which numerical columns that are not already
        sparse will be stored in a sparse format. This threshold is not used to
        densify columns that are already sparse.
    cat_threshold : int, default 4
        Number of levels of a categorical column under which the column will be stored
        as sparse one-hot-encoded columns instead of CategoricalMatrix
    object_as_cat : bool, default False
        If True, DataFrame columns stored as python objects will be treated as
        categorical columns.
    cat_position : str {'end'|'expand'}, default 'expand'
        Position of the categorical variable in the index. If "last", all the
        categoricals (including the ones that did not satisfy cat_threshold)
        will be placed at the end of the index list. If "expand", all the variables
        will remain in the same order.
    drop_first : bool, default False
        If true, categoricals variables will have their first category dropped.
        This allows multiple categorical variables to be included in an
        unregularized model. If False, all categories are included.
    cat_missing_method: str {'fail'|'zero'|'convert'}, default 'fail'
        How to handle missing values in categorical columns:

        - if 'fail', raise an error if there are missing values.
        - if 'zero', missing values will represent all-zero indicator columns.
        - if 'convert', missing values will be converted to the '(MISSING)' category.
    cat_missing_name: str, default '(MISSING)'
        Name of the category to which missing values will be converted if
        `cat_missing_method='convert'`.

    Returns
    -------
    SplitMatrix
    """
    matrices: list[DenseMatrix | SparseMatrix | CategoricalMatrix] = []
    indices: list[np.ndarray] = []
    is_cat: list[bool] = []

    dense_dfidx = []  # column index in original DataFrame
    dense_tmidx = []  # index in the new SplitMatrix
    sparse_dfidx = []  # column index in the original DataFrame
    sparse_tmidx = []  # index in the new SplitMatrix
    pandas_sparse_dfidx = set()  # zero-fill pandas SparseDtype columns
    ignored_cols = []
    nonzero_fill_cols: list[tuple[str, object]] = []

    mxcolidx = 0

    for dfcolidx, colname in enumerate(df.columns):
        coldata = df[:, dfcolidx]
        if object_as_cat:
            if isinstance(coldata.dtype, (nw.String, nw.Object)) or (
                pd is not None  # until Narwhals handles it natively
                and isinstance(
                    nw.to_native(coldata).dtype,
                    pd.StringDtype,
                )
            ):
                coldata = coldata.cast(nw.Categorical)

        # deal with Pandas sparse dtype (not supported by narwhals)
        if pd is not None:
            native_dtype = nw.to_native(coldata).dtype
            if isinstance(native_dtype, pd.SparseDtype):
                fill = native_dtype.fill_value
                if np.isscalar(fill) and not pd.isna(fill) and fill == 0:
                    pandas_sparse_dfidx.add(dfcolidx)
                    sparse_dfidx.append(dfcolidx)
                    sparse_tmidx.append(mxcolidx)
                else:
                    # SparseMatrix only represents zero fill. A sparse array with
                    # any other fill value is logically dense, so store it that way.
                    nonzero_fill_cols.append((colname, fill))
                    dense_dfidx.append(dfcolidx)
                    dense_tmidx.append(mxcolidx)
                mxcolidx += 1
                continue

        if isinstance(coldata.dtype, (nw.Categorical, nw.Enum)):
            cat = CategoricalMatrix(
                coldata,
                drop_first=drop_first,
                dtype=dtype,
                column_name=colname,
                term_name=colname,
                column_name_format=categorical_format,
                cat_missing_method=cat_missing_method,
                cat_missing_name=cat_missing_name,
            )
            if len(cat.categories) < cat_threshold:
                (
                    X_dense_F,
                    X_sparse,
                    dense_idx,
                    sparse_idx,
                ) = _split_sparse_and_dense_parts(
                    sps.csc_matrix(cat.tocsr(), dtype=dtype),
                    threshold=sparse_threshold,
                    column_names=cat.get_names("column"),
                    term_names=cat.get_names("term"),
                )
                matrices.append(X_dense_F)
                is_cat.append(True)
                matrices.append(X_sparse)
                is_cat.append(True)
                if cat_position == "expand":
                    indices.append(mxcolidx + dense_idx)
                    indices.append(mxcolidx + sparse_idx)
                    mxcolidx += len(dense_idx) + len(sparse_idx)
                elif cat_position == "end":
                    indices.append(dense_idx)
                    indices.append(sparse_idx)

            else:
                matrices.append(cat)
                is_cat.append(True)
                if cat_position == "expand":
                    indices.append(mxcolidx + np.arange(cat.shape[1]))
                    mxcolidx += cat.shape[1]
                elif cat_position == "end":
                    indices.append(np.arange(cat.shape[1]))
        elif isinstance(coldata.dtype, nw.Boolean):
            if (coldata != False).mean() <= sparse_threshold:  # noqa E712
                sparse_dfidx.append(dfcolidx)
                sparse_tmidx.append(mxcolidx)
                mxcolidx += 1
            else:
                dense_dfidx.append(dfcolidx)
                dense_tmidx.append(mxcolidx)
                mxcolidx += 1
        elif coldata.dtype.is_numeric():
            if (coldata != 0).mean() <= sparse_threshold:
                sparse_dfidx.append(dfcolidx)
                sparse_tmidx.append(mxcolidx)
                mxcolidx += 1
            else:
                dense_dfidx.append(dfcolidx)
                dense_tmidx.append(mxcolidx)
                mxcolidx += 1
        else:
            ignored_cols.append(colname)

    if len(ignored_cols) > 0:
        warnings.warn(
            f"Columns {ignored_cols} were ignored. Make sure they have a valid dtype."
        )
    if len(nonzero_fill_cols) > 0:
        listed = ", ".join(
            f"{colname!r} (fill_value={fill!r})" for colname, fill in nonzero_fill_cols
        )
        warnings.warn(
            f"Columns {listed} have a sparse dtype with a fill value other than 0."
            " tabmat only supports a fill value of 0 for sparse storage, so these"
            " columns are stored as dense. Use fill_value=0 to keep them sparse."
        )
    if dense_dfidx:
        matrices.append(
            DenseMatrix(
                df[:, dense_dfidx].to_numpy().astype(dtype, copy=False),
                column_names=np.asarray(df.columns)[dense_dfidx],
                term_names=np.asarray(df.columns)[dense_dfidx],
            )
        )
        indices.append(np.asarray(dense_tmidx))
        is_cat.append(False)
    if sparse_dfidx:
        # Assemble the CSC column by column. Going through
        # `sps.coo_matrix(df[:, sparse_dfidx])` would materialize the whole block
        # densely first, which for pandas sparse columns is O(n * k) work and memory
        # on data that is O(nnz).
        data_parts: list[np.ndarray] = []
        index_parts: list[np.ndarray] = []
        indptr = [0]
        for dfcolidx in sparse_dfidx:
            if dfcolidx in pandas_sparse_dfidx:
                sparse_array = nw.to_native(df[:, dfcolidx]).array
                col_indices = sparse_array.sp_index.to_int_index().indices
                col_values = sparse_array.sp_values
            else:
                col = df[:, [dfcolidx]].to_numpy()[:, 0]
                col_indices = np.flatnonzero(col)
                col_values = col[col_indices]
            index_parts.append(np.asarray(col_indices))
            data_parts.append(np.asarray(col_values))
            indptr.append(indptr[-1] + len(col_indices))
        sparse_block = sps.csc_matrix(
            (
                np.concatenate(data_parts).astype(dtype, copy=False),
                np.concatenate(index_parts),
                np.asarray(indptr),
            ),
            shape=(df.shape[0], len(sparse_dfidx)),
        )
        # pandas sparse arrays may hold explicitly stored zeros
        sparse_block.eliminate_zeros()
        matrices.append(
            SparseMatrix(
                sparse_block,
                dtype=dtype,
                column_names=np.asarray(df.columns)[sparse_dfidx],
                term_names=np.asarray(df.columns)[sparse_dfidx],
            )
        )
        indices.append(np.asarray(sparse_tmidx))
        is_cat.append(False)

    if cat_position == "end":
        indices = _reindex_cat(indices, is_cat, mxcolidx)

    if len(matrices) > 1:
        return SplitMatrix(matrices, indices)
    elif len(matrices) == 0:
        raise ValueError("DataFrame contained no valid column")
    else:
        return matrices[0]

from_pandas

from_pandas(df, dtype: DTypeLike = np.float64, sparse_threshold: float = 0.1, cat_threshold: int = 4, object_as_cat: bool = False, cat_position: str = 'expand', drop_first: bool = False, categorical_format: str = '{name}[{category}]', cat_missing_method: str = 'fail', cat_missing_name: str = '(MISSING)') -> MatrixBase

Deprecated. Please use from_df instead.

Transform a pandas.DataFrame into an efficient SplitMatrix.

Parameters:

Name Type Description Default
df DataFrame

pandas DataFrame to convert.

required
dtype dtype

dtype of all sub-matrices of the resulting SplitMatrix.

np.float64
sparse_threshold float

Density threshold at or below which numerical columns that are not already sparse will be stored in a sparse format. This threshold is not used to densify columns that are already sparse.

0.1
cat_threshold int

Number of levels of a categorical column under which the column will be stored as sparse one-hot-encoded columns instead of CategoricalMatrix

4
object_as_cat bool

If True, DataFrame columns stored as python objects will be treated as categorical columns.

False
cat_position str {'end'|'expand'}

Position of the categorical variable in the index. If "last", all the categoricals (including the ones that did not satisfy cat_threshold) will be placed at the end of the index list. If "expand", all the variables will remain in the same order.

'expand'
drop_first bool

If true, categoricals variables will have their first category dropped. This allows multiple categorical variables to be included in an unregularized model. If False, all categories are included.

False
cat_missing_method str

How to handle missing values in categorical columns:

  • if 'fail', raise an error if there are missing values.
  • if 'zero', missing values will represent all-zero indicator columns.
  • if 'convert', missing values will be converted to the '(MISSING)' category.
'fail'
cat_missing_name str

Name of the category to which missing values will be converted if cat_missing_method='convert'.

'(MISSING)'

Returns:

Type Description
SplitMatrix
Source code in src/tabmat/constructor.py
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
def from_pandas(
    df,
    dtype: numpy.typing.DTypeLike = np.float64,
    sparse_threshold: float = 0.1,
    cat_threshold: int = 4,
    object_as_cat: bool = False,
    cat_position: str = "expand",
    drop_first: bool = False,
    categorical_format: str = "{name}[{category}]",
    cat_missing_method: str = "fail",
    cat_missing_name: str = "(MISSING)",
) -> MatrixBase:
    """
    Deprecated. Please use `from_df` instead.

    Transform a pandas.DataFrame into an efficient SplitMatrix.

    Parameters
    ----------
    df : pd.DataFrame
        pandas DataFrame to convert.
    dtype : np.dtype, default np.float64
        dtype of all sub-matrices of the resulting SplitMatrix.
    sparse_threshold : float, default 0.1
        Density threshold at or below which numerical columns that are not already
        sparse will be stored in a sparse format. This threshold is not used to
        densify columns that are already sparse.
    cat_threshold : int, default 4
        Number of levels of a categorical column under which the column will be stored
        as sparse one-hot-encoded columns instead of CategoricalMatrix
    object_as_cat : bool, default False
        If True, DataFrame columns stored as python objects will be treated as
        categorical columns.
    cat_position : str {'end'|'expand'}, default 'expand'
        Position of the categorical variable in the index. If "last", all the
        categoricals (including the ones that did not satisfy cat_threshold)
        will be placed at the end of the index list. If "expand", all the variables
        will remain in the same order.
    drop_first : bool, default False
        If true, categoricals variables will have their first category dropped.
        This allows multiple categorical variables to be included in an
        unregularized model. If False, all categories are included.
    cat_missing_method: str {'fail'|'zero'|'convert'}, default 'fail'
        How to handle missing values in categorical columns:

        - if 'fail', raise an error if there are missing values.
        - if 'zero', missing values will represent all-zero indicator columns.
        - if 'convert', missing values will be converted to the '(MISSING)' category.
    cat_missing_name: str, default '(MISSING)'
        Name of the category to which missing values will be converted if
        `cat_missing_method='convert'`.

    Returns
    -------
    SplitMatrix
    """
    return from_df(
        df,
        dtype=dtype,
        sparse_threshold=sparse_threshold,
        cat_threshold=cat_threshold,
        object_as_cat=object_as_cat,
        cat_position=cat_position,
        drop_first=drop_first,
        categorical_format=categorical_format,
        cat_missing_method=cat_missing_method,
        cat_missing_name=cat_missing_name,
    )

from_csc

from_csc(mat: csc_matrix, threshold=0.1, column_names=None, term_names=None)

Convert a CSC-format sparse matrix into a SplitMatrix.

The threshold parameter specifies the density below which a column is treated as sparse.

Source code in src/tabmat/constructor.py
348
349
350
351
352
353
354
355
356
def from_csc(mat: sps.csc_matrix, threshold=0.1, column_names=None, term_names=None):
    """
    Convert a CSC-format sparse matrix into a `SplitMatrix`.

    The `threshold` parameter specifies the density below which a column is
    treated as sparse.
    """
    dense, sparse, dense_idx, sparse_idx = _split_sparse_and_dense_parts(mat, threshold)
    return SplitMatrix([dense, sparse], [dense_idx, sparse_idx])

from_formula

from_formula(formula: str | Formula, data, ensure_full_rank: bool = False, na_action: str | NAAction = NAAction.IGNORE, dtype: DTypeLike = np.float64, sparse_threshold: float = 0.1, cat_threshold: int = 4, interaction_separator: str = ':', categorical_format: str = '{name}[{category}]', cat_missing_method: str = 'fail', cat_missing_name: str = '(MISSING)', intercept_name: str = 'Intercept', include_intercept: bool = False, add_column_for_intercept: bool = True, context: int | Mapping[str, Any] | None = None) -> SplitMatrix

Transform a pandas data frame to a SplitMatrix using a Wilkinson formula.

Parameters:

Name Type Description Default
formula str | Formula

A formula accepted by formulaic.

required
data

pandas data frame to be converted.

required
ensure_full_rank bool

If True, ensure that the matrix has full structural rank by categories.

False
na_action str | NAAction

How to handle missing values. Can be one of "drop", "ignore", "raise".

IGNORE
dtype DTypeLike

The dtype of the resulting matrix.

float64
sparse_threshold float

The density below which a column is treated as sparse.

0.1
cat_threshold int

The number of categories below which a categorical column is one-hot encoded. This is only checked after interactions have been applied.

4
interaction_separator str

The separator between the names of interacted variables.

':'
categorical_format str

The format string used to generate the names of categorical variables. Has to include the placeholders {name} and {category}.

'{name}[{category}]'
cat_missing_method str

How to handle missing values in categorical columns:

  • if 'fail', raise an error if there are missing values.
  • if 'zero', missing values will represent all-zero indicator columns.
  • if 'convert', missing values will be converted to the '(MISSING)' category.
'fail'
cat_missing_name str

Name of the category to which missing values will be converted if cat_missing_method='convert'.

'(MISSING)'
intercept_name str

The name of the intercept column.

'Intercept'
include_intercept bool

Whether to include an intercept term if the formula does not include (+ 1) or exclude (+ 0 or - 1) it explicitly.

False
add_column_for_intercept bool

Whether to add a column of ones for the intercept, or just have a term without a corresponding column. For advanced use only.

True
context int | Mapping[str, Any] | None

The context to add to the evaluation context of the formula with, e.g., custom transforms. If an integer, the context is taken from the stack frame of the caller at the given depth. Otherwise, a mapping from variable names to values is expected. By default, no context is added. Set context=0 to make the calling scope available.

None
Source code in src/tabmat/constructor.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def from_formula(
    formula: str | Formula,
    data,
    ensure_full_rank: bool = False,
    na_action: str | NAAction = NAAction.IGNORE,
    dtype: numpy.typing.DTypeLike = np.float64,
    sparse_threshold: float = 0.1,
    cat_threshold: int = 4,
    interaction_separator: str = ":",
    categorical_format: str = "{name}[{category}]",
    cat_missing_method: str = "fail",
    cat_missing_name: str = "(MISSING)",
    intercept_name: str = "Intercept",
    include_intercept: bool = False,
    add_column_for_intercept: bool = True,
    context: int | Mapping[str, Any] | None = None,
) -> SplitMatrix:
    """
    Transform a pandas data frame to a SplitMatrix using a Wilkinson formula.

    Parameters
    ----------
    formula: str
        A formula accepted by formulaic.
    data: pd.DataFrame
        pandas data frame to be converted.
    ensure_full_rank: bool, default False
        If True, ensure that the matrix has full structural rank by categories.
    na_action: Union[str, NAAction], default NAAction.IGNORE
        How to handle missing values. Can be one of "drop", "ignore", "raise".
    dtype: np.dtype, default np.float64
        The dtype of the resulting matrix.
    sparse_threshold: float, default 0.1
        The density below which a column is treated as sparse.
    cat_threshold: int, default 4
        The number of categories below which a categorical column is one-hot
        encoded. This is only checked after interactions have been applied.
    interaction_separator: str, default ":"
        The separator between the names of interacted variables.
    categorical_format: str, default "{name}[T.{category}]"
        The format string used to generate the names of categorical variables.
        Has to include the placeholders `{name}` and `{category}`.
    cat_missing_method: str {'fail'|'zero'|'convert'}, default 'fail'
        How to handle missing values in categorical columns:

        - if 'fail', raise an error if there are missing values.
        - if 'zero', missing values will represent all-zero indicator columns.
        - if 'convert', missing values will be converted to the '(MISSING)' category.
    cat_missing_name: str, default '(MISSING)'
        Name of the category to which missing values will be converted if
        `cat_missing_method='convert'`.
    intercept_name: str, default "Intercept"
        The name of the intercept column.
    include_intercept: bool, default False
        Whether to include an intercept term if the formula does not
        include (`+ 1`) or exclude (`+ 0` or `- 1`) it explicitly.
    add_column_for_intercept: bool, default = True
        Whether to add a column of ones for the intercept, or just
        have a term without a corresponding column. For advanced use only.
    context: Optional[Union[int, Mapping[str, Any]]], default = None
        The context to add to the evaluation context of the formula with,
        e.g., custom transforms. If an integer, the context is taken from
        the stack frame of the caller at the given depth. Otherwise, a
        mapping from variable names to values is expected. By default,
        no context is added. Set `context=0` to make the calling scope
        available.
    """
    if isinstance(context, int):
        if hasattr(sys, "_getframe"):
            frame = sys._getframe(context + 1)
            context = LayeredMapping(frame.f_locals, frame.f_globals)
        else:
            context = None
    spec = ModelSpec(
        formula=Formula(
            formula, _parser=DefaultFormulaParser(include_intercept=include_intercept)
        ),
        ensure_full_rank=ensure_full_rank,
        na_action=na_action,
    )
    materializer = TabmatMaterializer(
        data,
        context=context,
        interaction_separator=interaction_separator,
        categorical_format=categorical_format,
        intercept_name=intercept_name,
        dtype=dtype,
        sparse_threshold=sparse_threshold,
        cat_threshold=cat_threshold,
        add_column_for_intercept=add_column_for_intercept,
        cat_missing_method=cat_missing_method,
        cat_missing_name=cat_missing_name,
    )
    result = materializer.get_model_matrix(spec)

    term_names: np.ndarray = np.zeros(len(result.term_names), dtype="object")
    for term, indices in result.model_spec.term_indices.items():
        term_names[indices] = str(term)
    result.term_names = term_names.tolist()

    return result

as_tabmat

as_tabmat(a: MatrixBase | StandardizedMatrix | ndarray | spmatrix)

Convert an array to a corresponding MatrixBase type.

If the input is already a MatrixBase, return untouched. If the input is sparse, return a SparseMatrix. If the input is a numpy array, return a DenseMatrix. Raise an error is input is another type.

Source code in src/tabmat/split_matrix.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def as_tabmat(a: MatrixBase | StandardizedMatrix | np.ndarray | sps.spmatrix):
    """Convert an array to a corresponding MatrixBase type.

    If the input is already a MatrixBase, return untouched.
    If the input is sparse, return a SparseMatrix.
    If the input is a numpy array, return a DenseMatrix.
    Raise an error is input is another type.
    """
    if isinstance(a, (MatrixBase, StandardizedMatrix)):
        return a
    elif sps.issparse(a):
        return SparseMatrix(a.tocsc(copy=False))  # type: ignore
    elif isinstance(a, np.ndarray):
        return DenseMatrix(a)
    else:
        raise ValueError(f"Cannot convert type {type(a)} to Matrix.")

hstack

hstack(tup: Sequence[MatrixBase | ndarray | spmatrix]) -> MatrixBase

Stack arrays in sequence horizontally (column wise).

This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.

Parameters:

Name Type Description Default
tup Sequence[MatrixBase | ndarray | spmatrix]

The arrays must have the same shape along all but the second axis.

required
Source code in src/tabmat/split_matrix.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def hstack(tup: Sequence[MatrixBase | np.ndarray | sps.spmatrix]) -> MatrixBase:
    """Stack arrays in sequence horizontally (column wise).

    This is equivalent to concatenation along the second axis,
    except for 1-D arrays where it concatenates along the first axis.

    Parameters
    ----------
    tup: sequence of arrays
        The arrays must have the same shape along all but the second axis.
    """
    matrices = [as_tabmat(a) for a in tup]

    if len(matrices) == 0:
        raise ValueError("Need at least one array to concatenate.")

    if all(isinstance(mat, SparseMatrix) for mat in matrices):
        return SparseMatrix(sps.hstack([mat._array for mat in matrices]))
    elif all(isinstance(mat, DenseMatrix) for mat in matrices):
        return DenseMatrix(np.hstack([mat._array for mat in matrices]))
    else:
        return SplitMatrix(matrices)

MatrixBase

Bases: ABC

Base class for all matrix classes. MatrixBase cannot be instantiated.

A property

A: ndarray

Convert self into an np.ndarray. Synonym for toarray().

column_names property writable

column_names

Column names of the matrix.

term_names property writable

term_names

Term names of the matrix.

For differences between column names and term names, see get_names.

matvec abstractmethod

matvec(other, cols: ndarray | None = None, out: ndarray | None = None)

Perform: self[:, cols] @ other[cols], so result[i] = sum_j self[i, j] other[j].

The 'cols' parameter allows restricting to a subset of the matrix without making a copy. If provided:

::

result[i] = sum_{j in cols} self[i, j] other[j].

If 'out' is provided, we modify 'out' in place by adding the output of this operation to it.

Source code in src/tabmat/matrix_base.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@abstractmethod
def matvec(
    self, other, cols: np.ndarray | None = None, out: np.ndarray | None = None
):
    """
    Perform: self[:, cols] @ other[cols], so result[i] = sum_j self[i, j] other[j].

    The 'cols' parameter allows restricting to a subset of the matrix without making
    a copy. If provided:

    ::

        result[i] = sum_{j in cols} self[i, j] other[j].

    If 'out' is provided, we modify 'out' in place by adding the output of this
    operation to it.
    """
    pass

transpose_matvec abstractmethod

transpose_matvec(vec: ndarray | list, rows: ndarray | None = None, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform: self[rows, cols].T @ vec[rows], so result[i] = sum_j self[j, i] vec[j].

The rows and cols parameters allow restricting to a subset of the matrix without making a copy.

If 'rows' and 'cols' are provided:

::

result[i] = sum_{j in rows} self[j, cols[i]] vec[j].

Note that the length of the output is len(cols).

If out is provided:

::

out[cols[i]] += sum_{j in rows} self[j, cols[i]] vec[j]
Source code in src/tabmat/matrix_base.py
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
@abstractmethod
def transpose_matvec(
    self,
    vec: np.ndarray | list,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """
    Perform: self[rows, cols].T @ vec[rows], so result[i] = sum_j self[j, i] vec[j].

    The rows and cols parameters allow restricting to a subset of the
    matrix without making a copy.

    If 'rows' and 'cols' are provided:

    ::

        result[i] = sum_{j in rows} self[j, cols[i]] vec[j].

    Note that the length of the output is len(cols).

    If `out` is provided:

    ::

        out[cols[i]] += sum_{j in rows} self[j, cols[i]] vec[j]

    """
    pass

sandwich abstractmethod

sandwich(d: ndarray, rows: ndarray | None = None, cols: ndarray | None = None) -> np.ndarray

Perform a sandwich product: (self[rows, cols].T * d[rows]) @ self[rows, cols].

The rows and cols parameters allow restricting to a subset of the matrix without making a copy.

Source code in src/tabmat/matrix_base.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@abstractmethod
def sandwich(
    self,
    d: np.ndarray,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
) -> np.ndarray:
    """
    Perform a sandwich product: (self[rows, cols].T * d[rows]) @ self[rows, cols].

    The rows and cols parameters allow restricting to a subset of the
    matrix without making a copy.
    """
    pass

toarray abstractmethod

toarray() -> np.ndarray

Convert self into an np.ndarray.

Source code in src/tabmat/matrix_base.py
109
110
111
112
@abstractmethod
def toarray(self) -> np.ndarray:  # noqa D102
    """Convert self into an np.ndarray."""
    pass

standardize

standardize(weights: ndarray, center_predictors: bool, scale_predictors: bool) -> tuple[Any, np.ndarray, np.ndarray | None]

Return a StandardizedMatrix along with the column means and column standard deviations.

It is often useful to modify a dataset so that each column has mean zero and standard deviation one. This function does this "standardization" without modifying the underlying dataset by storing shifting and scaling factors that are then used whenever an operation is performed with the new StandardizedMatrix.

Note: If center_predictors is False, col_means will be zeros.

Note: If scale_predictors is False, col_stds will be None.

Source code in src/tabmat/matrix_base.py
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
def standardize(
    self, weights: np.ndarray, center_predictors: bool, scale_predictors: bool
) -> tuple[Any, np.ndarray, np.ndarray | None]:
    """
    Return a StandardizedMatrix along with the column means and column standard
    deviations.

    It is often useful to modify a dataset so that each column has mean
    zero and standard deviation one. This function does this "standardization"
    without modifying the underlying dataset by storing shifting and scaling
    factors that are then used whenever an operation is performed with the new
    StandardizedMatrix.

    Note: If center_predictors is False, col_means will be zeros.

    Note: If scale_predictors is False, col_stds will be None.
    """
    from .standardized_mat import StandardizedMatrix

    weights = prepare_vector(weights)
    col_means = self._get_col_means(weights)
    if scale_predictors:
        col_stds = self._get_col_stds(weights, col_means)
        mult = _one_over_var_inf_to_val(col_stds, 1.0)
        if center_predictors:
            shifter = -col_means * mult
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
    else:
        col_stds = None
        if center_predictors:
            shifter = -col_means
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
        mult = None

    out = StandardizedMatrix(self, shifter, mult)
    # Keep the exact means, so that dense products can center the data with
    # them instead of recovering them from shifter / mult.
    out._center = np.array(out_means, copy=True)
    return out, out_means, col_stds

get_names abstractmethod

get_names(type: str = 'column', missing_prefix: str | None = None, indices: list[int] | None = None) -> list[str | None]

Get column names.

For columns that do not have a name, a default name is created using the following pattern: "{missing_prefix}{start_index + i}" where i is the index of the column.

Parameters:

Name Type Description Default
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
missing_prefix str | None

Prefix to use for columns that do not have a name. If None, then no default name is created.

None
indices list[int] | None

The indices used for columns that do not have a name. If None, then the indices are list(range(self.shape[1])).

None

Returns:

Type Description
list[Optional[str]]

Column names.

Source code in src/tabmat/matrix_base.py
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
@abstractmethod
def get_names(
    self,
    type: str = "column",
    missing_prefix: str | None = None,
    indices: list[int] | None = None,
) -> list[str | None]:
    """Get column names.

    For columns that do not have a name, a default name is created using the
    following pattern: `"{missing_prefix}{start_index + i}"` where `i` is
    the index of the column.

    Parameters
    ----------
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    missing_prefix: Optional[str], default None
        Prefix to use for columns that do not have a name. If None, then no
        default name is created.
    indices
        The indices used for columns that do not have a name. If `None`,
        then the indices are `list(range(self.shape[1]))`.

    Returns
    -------
    list[Optional[str]]
        Column names.
    """
    pass

set_names

set_names(names: str | list[str | None], type: str = 'column')

Set column names.

Parameters:

Name Type Description Default
names str | list[str | None]

Names to set.

required
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
Source code in src/tabmat/matrix_base.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def set_names(self, names: str | list[str | None], type: str = "column"):
    """Set column names.

    Parameters
    ----------
    names: list[Optional[str]]
        Names to set.
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    """
    pass

DenseMatrix

DenseMatrix(input_array, column_names=None, term_names=None)

Bases: MatrixBase

A numpy.ndarray subclass with several additional functions that allow it to share the MatrixBase API with SparseMatrix and CategoricalMatrix.

In particular, we have added:

  • The sandwich product
  • getcol to support the same interface as SparseMatrix for retrieving a single column
  • toarray
  • matvec
Source code in src/tabmat/dense_matrix.py
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
def __init__(self, input_array, column_names=None, term_names=None):
    input_array = np.asarray(input_array)

    if input_array.ndim == 1:
        input_array = input_array.reshape(-1, 1)
    elif input_array.ndim > 2:
        raise ValueError("Input array must be 1- or 2-dimensional")

    # Ensure array is contiguous (C or F order) for Cython operations
    # Only copy if necessary
    if (
        not input_array.flags["C_CONTIGUOUS"]
        and not input_array.flags["F_CONTIGUOUS"]
    ):
        warnings.warn(
            "Input array is not contiguous; making a copy.",
            UserWarning,
            stacklevel=2,
        )
        input_array = np.asfortranarray(input_array)

    self._array = input_array
    width = self._array.shape[1]

    if column_names is not None:
        if len(column_names) != width:
            raise ValueError(
                f"Expected {width} column names, got {len(column_names)}"
            )
        self._colnames = column_names
    else:
        self._colnames = [None] * width

    if term_names is not None:
        if len(term_names) != width:
            raise ValueError(f"Expected {width} term names, got {len(term_names)}")
        self._terms = term_names
    else:
        self._terms = self._colnames

A property

A: ndarray

Convert self into an np.ndarray. Synonym for toarray().

column_names property writable

column_names

Column names of the matrix.

term_names property writable

term_names

Term names of the matrix.

For differences between column names and term names, see get_names.

shape property

shape

Tuple of array dimensions.

ndim property

ndim

Number of array dimensions.

dtype property

dtype

Data type of the array's elements.

standardize

standardize(weights: ndarray, center_predictors: bool, scale_predictors: bool) -> tuple[Any, np.ndarray, np.ndarray | None]

Return a StandardizedMatrix along with the column means and column standard deviations.

It is often useful to modify a dataset so that each column has mean zero and standard deviation one. This function does this "standardization" without modifying the underlying dataset by storing shifting and scaling factors that are then used whenever an operation is performed with the new StandardizedMatrix.

Note: If center_predictors is False, col_means will be zeros.

Note: If scale_predictors is False, col_stds will be None.

Source code in src/tabmat/matrix_base.py
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
def standardize(
    self, weights: np.ndarray, center_predictors: bool, scale_predictors: bool
) -> tuple[Any, np.ndarray, np.ndarray | None]:
    """
    Return a StandardizedMatrix along with the column means and column standard
    deviations.

    It is often useful to modify a dataset so that each column has mean
    zero and standard deviation one. This function does this "standardization"
    without modifying the underlying dataset by storing shifting and scaling
    factors that are then used whenever an operation is performed with the new
    StandardizedMatrix.

    Note: If center_predictors is False, col_means will be zeros.

    Note: If scale_predictors is False, col_stds will be None.
    """
    from .standardized_mat import StandardizedMatrix

    weights = prepare_vector(weights)
    col_means = self._get_col_means(weights)
    if scale_predictors:
        col_stds = self._get_col_stds(weights, col_means)
        mult = _one_over_var_inf_to_val(col_stds, 1.0)
        if center_predictors:
            shifter = -col_means * mult
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
    else:
        col_stds = None
        if center_predictors:
            shifter = -col_means
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
        mult = None

    out = StandardizedMatrix(self, shifter, mult)
    # Keep the exact means, so that dense products can center the data with
    # them instead of recovering them from shifter / mult.
    out._center = np.array(out_means, copy=True)
    return out, out_means, col_stds

transpose

transpose()

Returns a view of the array with axes transposed.

Source code in src/tabmat/dense_matrix.py
128
129
130
def transpose(self):
    """Returns a view of the array with axes transposed."""  # noqa: D401
    return type(self)(self._array.T)

astype

astype(dtype, order='K', casting='unsafe', copy=True)

Copy of the array, cast to a specified type.

Source code in src/tabmat/dense_matrix.py
134
135
136
137
138
139
140
def astype(self, dtype, order="K", casting="unsafe", copy=True):
    """Copy of the array, cast to a specified type."""
    return type(self)(
        self._array.astype(dtype, order, casting, copy),
        column_names=self.column_names,
        term_names=self.term_names,
    )

getcol

getcol(i)

Return matrix column at specified index.

Source code in src/tabmat/dense_matrix.py
142
143
144
145
146
147
148
def getcol(self, i):
    """Return matrix column at specified index."""
    return type(self)(
        self._array[:, [i]],
        column_names=[self.column_names[i]],
        term_names=[self.term_names[i]],
    )

toarray

toarray()

Return array representation of matrix.

Source code in src/tabmat/dense_matrix.py
150
151
152
def toarray(self):
    """Return array representation of matrix."""
    return self._array

unpack

unpack()

Return the underlying numpy.ndarray.

Source code in src/tabmat/dense_matrix.py
154
155
156
def unpack(self):
    """Return the underlying numpy.ndarray."""
    return self._array

sandwich

sandwich(d: ndarray, rows: ndarray | None = None, cols: ndarray | None = None) -> np.ndarray

Perform a sandwich product: X.T @ diag(d) @ X.

Source code in src/tabmat/dense_matrix.py
158
159
160
161
162
163
164
165
def sandwich(
    self,
    d: np.ndarray,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
) -> np.ndarray:
    """Perform a sandwich product: X.T @ diag(d) @ X."""
    return self._centered_sandwich(d, None, rows, cols)

transpose_matvec

transpose_matvec(vec: ndarray | list, rows: ndarray | None = None, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform: self[rows, cols].T @ vec[rows].

Source code in src/tabmat/dense_matrix.py
318
319
320
321
322
323
324
325
326
327
def transpose_matvec(
    self,
    vec: np.ndarray | list,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """Perform: self[rows, cols].T @ vec[rows]."""
    check_transpose_matvec_out_shape(self, out)
    return self._matvec_helper(vec, rows, cols, out, True)

matvec

matvec(vec: ndarray | list, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform self[:, cols] @ other[cols].

Source code in src/tabmat/dense_matrix.py
329
330
331
332
333
334
335
336
337
def matvec(
    self,
    vec: np.ndarray | list,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """Perform self[:, cols] @ other[cols]."""
    check_matvec_out_shape(self, out)
    return self._matvec_helper(vec, None, cols, out, False)

multiply

multiply(other)

Element-wise multiplication.

This assumes that other is a vector of size self.shape[0].

Source code in src/tabmat/dense_matrix.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def multiply(self, other):
    """Element-wise multiplication.

    This assumes that `other` is a vector of size `self.shape[0]`.
    """
    if np.asanyarray(other).ndim == 1:
        return type(self)(
            self._array.__mul__(other[:, np.newaxis]),
            column_names=self.column_names,
            term_names=self.term_names,
        )
    return type(self)(
        self._array.__mul__(other),
        column_names=self.column_names,
        term_names=self.term_names,
    )

get_names

get_names(type: str = 'column', missing_prefix: str | None = None, indices: list[int] | None = None) -> list[str | None]

Get column names.

For columns that do not have a name, a default name is created using the following pattern: "{missing_prefix}{start_index + i}" where i is the index of the column.

Parameters:

Name Type Description Default
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
missing_prefix str | None

Prefix to use for columns that do not have a name. If None, then no default name is created.

None
indices list[int] | None

The indices used for columns that do not have a name. If None, then the indices are list(range(self.shape[1])).

None

Returns:

Type Description
list[Optional[str]]

Column names.

Source code in src/tabmat/dense_matrix.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def get_names(
    self,
    type: str = "column",
    missing_prefix: str | None = None,
    indices: list[int] | None = None,
) -> list[str | None]:
    """Get column names.

    For columns that do not have a name, a default name is created using the
    following pattern: `"{missing_prefix}{start_index + i}"` where `i` is
    the index of the column.

    Parameters
    ----------
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    missing_prefix: Optional[str], default None
        Prefix to use for columns that do not have a name. If None, then no
        default name is created.
    indices
        The indices used for columns that do not have a name. If `None`,
        then the indices are `list(range(self.shape[1]))`.

    Returns
    -------
    list[Optional[str]]
        Column names.
    """
    if type == "column":
        names = np.array(self._colnames)
    elif type == "term":
        names = np.array(self._terms)
    else:
        raise ValueError(f"Type must be 'column' or 'term', got {type}")

    if indices is None:
        indices = list(range(len(self._colnames)))

    if missing_prefix is not None:
        default_names = np.array([f"{missing_prefix}{i}" for i in indices])
        names[names == None] = default_names[names == None]  # noqa: E711

    return names.tolist()

set_names

set_names(names: str | list[str | None], type: str = 'column')

Set column names.

Parameters:

Name Type Description Default
names str | list[str | None]

Names to set.

required
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
Source code in src/tabmat/dense_matrix.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def set_names(self, names: str | list[str | None], type: str = "column"):
    """Set column names.

    Parameters
    ----------
    names: list[Optional[str]]
        Names to set.
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    """
    if isinstance(names, str):
        names = [names]

    if len(names) != self.shape[1]:
        raise ValueError(f"Length of names must be {self.shape[1]}")

    if type == "column":
        self._colnames = names
    elif type == "term":
        self._terms = names
    else:
        raise ValueError(f"Type must be 'column' or 'term', got {type}")

SparseMatrix

SparseMatrix(input_array, shape=None, dtype=None, copy=False, column_names=None, term_names=None)

Bases: MatrixBase

A scipy.sparse csc matrix subclass that allows such objects to conform to the MatrixBase interface.

SparseMatrix is instantiated in the same way as scipy.sparse.csc_matrix.

Source code in src/tabmat/sparse_matrix.py
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
def __init__(
    self,
    input_array,
    shape=None,
    dtype=None,
    copy=False,
    column_names=None,
    term_names=None,
):
    if isinstance(input_array, np.ndarray):
        if input_array.ndim == 1:
            input_array = input_array.reshape(-1, 1)
        elif input_array.ndim > 2:
            raise ValueError("Input array must be 1- or 2-dimensional")

    self._array = sps.csc_matrix(input_array, shape, dtype, copy)
    # The kernels read these arrays through pointers, so they must be contiguous
    # and in native byte order. scipy keeps strided or byte-swapped arrays.
    for name in ("data", "indices", "indptr"):
        arr = getattr(self._array, name)
        if not (arr.dtype.isnative and arr.flags.c_contiguous):
            setattr(
                self._array,
                name,
                np.ascontiguousarray(arr, dtype=arr.dtype.newbyteorder("=")),
            )

    self.idx_dtype = max(self._array.indices.dtype, self._array.indptr.dtype)
    if self._array.indices.dtype != self.idx_dtype:
        self._array.indices = self._array.indices.astype(self.idx_dtype)
    if self._array.indptr.dtype != self.idx_dtype:
        self._array.indptr = self._array.indptr.astype(self.idx_dtype)
    assert self.indices.dtype == self.idx_dtype

    if not self._array.has_sorted_indices:
        if not (
            self._array.data.flags.writeable and self._array.indices.flags.writeable
        ):
            # Read-only input, e.g. from a pandas DataFrame with copy-on-write.
            self._array = self._array.copy()
        self._array.sort_indices()
    self._array_csr = None

    if column_names is not None:
        if len(column_names) != self.shape[1]:
            raise ValueError(
                f"Expected {self.shape[1]} column names, got {len(column_names)}"
            )
        self._colnames = column_names
    else:
        self._colnames = [None] * self.shape[1]

    if term_names is not None:
        if len(term_names) != self.shape[1]:
            raise ValueError(
                f"Expected {self.shape[1]} term names, got {len(term_names)}"
            )
        self._terms = term_names
    else:
        self._terms = self._colnames

A property

A: ndarray

Convert self into an np.ndarray. Synonym for toarray().

column_names property writable

column_names

Column names of the matrix.

term_names property writable

term_names

Term names of the matrix.

For differences between column names and term names, see get_names.

shape property

shape

Tuple of array dimensions.

ndim property

ndim

Number of array dimensions.

dtype property

dtype

Data-type of the array’s elements.

indices property

indices

Indices of the matrix.

indptr property

indptr

Indptr of the matrix.

data property

data

Data of the matrix.

array_csc property

array_csc

Return the CSC representation of the matrix.

array_csr property

array_csr

Cache the CSR representation of the matrix.

standardize

standardize(weights: ndarray, center_predictors: bool, scale_predictors: bool) -> tuple[Any, np.ndarray, np.ndarray | None]

Return a StandardizedMatrix along with the column means and column standard deviations.

It is often useful to modify a dataset so that each column has mean zero and standard deviation one. This function does this "standardization" without modifying the underlying dataset by storing shifting and scaling factors that are then used whenever an operation is performed with the new StandardizedMatrix.

Note: If center_predictors is False, col_means will be zeros.

Note: If scale_predictors is False, col_stds will be None.

Source code in src/tabmat/matrix_base.py
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
def standardize(
    self, weights: np.ndarray, center_predictors: bool, scale_predictors: bool
) -> tuple[Any, np.ndarray, np.ndarray | None]:
    """
    Return a StandardizedMatrix along with the column means and column standard
    deviations.

    It is often useful to modify a dataset so that each column has mean
    zero and standard deviation one. This function does this "standardization"
    without modifying the underlying dataset by storing shifting and scaling
    factors that are then used whenever an operation is performed with the new
    StandardizedMatrix.

    Note: If center_predictors is False, col_means will be zeros.

    Note: If scale_predictors is False, col_stds will be None.
    """
    from .standardized_mat import StandardizedMatrix

    weights = prepare_vector(weights)
    col_means = self._get_col_means(weights)
    if scale_predictors:
        col_stds = self._get_col_stds(weights, col_means)
        mult = _one_over_var_inf_to_val(col_stds, 1.0)
        if center_predictors:
            shifter = -col_means * mult
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
    else:
        col_stds = None
        if center_predictors:
            shifter = -col_means
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
        mult = None

    out = StandardizedMatrix(self, shifter, mult)
    # Keep the exact means, so that dense products can center the data with
    # them instead of recovering them from shifter / mult.
    out._center = np.array(out_means, copy=True)
    return out, out_means, col_stds

tocsc

tocsc(copy=False)

Return the matrix in CSC format.

Source code in src/tabmat/sparse_matrix.py
159
160
161
def tocsc(self, copy=False):
    """Return the matrix in CSC format."""
    return self._array.tocsc(copy=copy)

transpose

transpose()

Returns a view of the array with axes transposed.

Source code in src/tabmat/sparse_matrix.py
163
164
165
def transpose(self):
    """Returns a view of the array with axes transposed."""  # noqa: D401
    return type(self)(self._array.T)

getcol

getcol(i)

Return matrix column at specified index.

Source code in src/tabmat/sparse_matrix.py
169
170
171
172
173
174
175
def getcol(self, i):
    """Return matrix column at specified index."""
    return type(self)(
        self._array.getcol(i),
        column_names=[self.column_names[i]],
        term_names=[self.term_names[i]],
    )

unpack

unpack()

Return the underlying scipy.sparse.csc_matrix.

Source code in src/tabmat/sparse_matrix.py
177
178
179
def unpack(self):
    """Return the underlying scipy.sparse.csc_matrix."""
    return self._array

toarray

toarray()

Return a dense ndarray representation of the matrix.

Source code in src/tabmat/sparse_matrix.py
181
182
183
def toarray(self):
    """Return a dense ndarray representation of the matrix."""
    return self._array.toarray()

dot

dot(other)

Return the dot product as a scipy sparse matrix.

Source code in src/tabmat/sparse_matrix.py
185
186
187
def dot(self, other):
    """Return the dot product as a scipy sparse matrix."""
    return self._array.dot(other)

sandwich

sandwich(d: ndarray, rows: ndarray | None = None, cols: ndarray | None = None) -> np.ndarray

Perform a sandwich product: X.T @ diag(d) @ X.

Source code in src/tabmat/sparse_matrix.py
189
190
191
192
193
194
195
196
197
198
199
def sandwich(
    self,
    d: np.ndarray,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
) -> np.ndarray:
    """Perform a sandwich product: X.T @ diag(d) @ X."""
    d = prepare_vector(d)
    check_sandwich_compatible(self, d)
    rows, cols = setup_restrictions(self.shape, rows, cols, dtype=self.idx_dtype)
    return sparse_sandwich(self, self.array_csr, d, rows, cols)

sandwich_dense

sandwich_dense(B: ndarray, d: ndarray, rows: ndarray | None, L_cols: ndarray | None, R_cols: ndarray | None, B_center: ndarray | None = None) -> np.ndarray

Perform a sandwich product: self.T @ diag(d) @ B.

If B_center (one value per column of B) is given, compute self.T @ diag(d) @ (B - B_center) instead, centering B in the kernel.

Source code in src/tabmat/sparse_matrix.py
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
def sandwich_dense(
    self,
    B: np.ndarray,
    d: np.ndarray,
    rows: np.ndarray | None,
    L_cols: np.ndarray | None,
    R_cols: np.ndarray | None,
    B_center: np.ndarray | None = None,
) -> np.ndarray:
    """Perform a sandwich product: self.T @ diag(d) @ B.

    If `B_center` (one value per column of `B`) is given, compute
    `self.T @ diag(d) @ (B - B_center)` instead, centering `B` in the kernel.
    """
    d = prepare_vector(d)

    if self.dtype != d.dtype or B.dtype != d.dtype:
        raise TypeError(
            f"""self, B and d all need to be of same dtype, either
            np.float64 or np.float32. This matrix is of type {self.dtype},
            B is of type {B.dtype}, while d is of type {d.dtype}."""
        )
    rows, L_cols = setup_restrictions(
        self.shape, rows, L_cols, dtype=self.idx_dtype
    )
    R_cols = set_up_rows_or_cols(R_cols, B.shape[1], dtype=self.idx_dtype)
    return csr_dense_sandwich(
        self.array_csr, B, d, rows, L_cols, R_cols, B_center=B_center
    )

matvec

matvec(vec, cols: ndarray | None = None, out: ndarray | None = None)

Perform self[:, cols] @ other[cols].

Source code in src/tabmat/sparse_matrix.py
303
304
305
306
307
308
def matvec(
    self, vec, cols: np.ndarray | None = None, out: np.ndarray | None = None
):
    """Perform self[:, cols] @ other[cols]."""
    check_matvec_out_shape(self, out)
    return self._matvec_helper(vec, None, cols, out, False)

transpose_matvec

transpose_matvec(vec: ndarray | list, rows: ndarray | None = None, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform: self[rows, cols].T @ vec[rows].

Source code in src/tabmat/sparse_matrix.py
310
311
312
313
314
315
316
317
318
319
def transpose_matvec(
    self,
    vec: np.ndarray | list,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """Perform: self[rows, cols].T @ vec[rows]."""
    check_transpose_matvec_out_shape(self, out)
    return self._matvec_helper(vec, rows, cols, out, True)

astype

astype(dtype, order='K', casting='unsafe', copy=True)

Return SparseMatrix cast to new type.

Source code in src/tabmat/sparse_matrix.py
339
340
341
def astype(self, dtype, order="K", casting="unsafe", copy=True):
    """Return SparseMatrix cast to new type."""
    return type(self)(self._array.astype(dtype, casting, copy))

multiply

multiply(other)

Element-wise multiplication.

See scipy.sparse.csc_matrix.multiply. The method is taken almost directly from the parent class except that other is assumed to be a vector of size self.shape[0].

Source code in src/tabmat/sparse_matrix.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def multiply(self, other):
    """Element-wise multiplication.

    See `scipy.sparse.csc_matrix.multiply`. The method is taken almost directly
    from the parent class except that `other` is assumed to be a vector of size
    `self.shape[0]`.
    """
    if np.asanyarray(other).ndim == 1:
        return type(self)(
            self._array.multiply(other[:, np.newaxis]),
            column_names=self.column_names,
            term_names=self.term_names,
        )
    return type(self)(
        self._array.multiply(other),
        column_names=self.column_names,
        term_names=self.term_names,
    )

get_names

get_names(type: str = 'column', missing_prefix: str | None = None, indices: list[int] | None = None) -> list[str | None]

Get column names.

For columns that do not have a name, a default name is created using the following pattern: "{missing_prefix}{start_index + i}" where i is the index of the column.

Parameters:

Name Type Description Default
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
missing_prefix str | None

Prefix to use for columns that do not have a name. If None, then no default name is created.

None
indices list[int] | None

The indices used for columns that do not have a name. If None, then the indices are list(range(self.shape[1])).

None

Returns:

Type Description
list[Optional[str]]

Column names.

Source code in src/tabmat/sparse_matrix.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def get_names(
    self,
    type: str = "column",
    missing_prefix: str | None = None,
    indices: list[int] | None = None,
) -> list[str | None]:
    """Get column names.

    For columns that do not have a name, a default name is created using the
    following pattern: `"{missing_prefix}{start_index + i}"` where `i` is
    the index of the column.

    Parameters
    ----------
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    missing_prefix: Optional[str], default None
        Prefix to use for columns that do not have a name. If None, then no
        default name is created.
    indices
        The indices used for columns that do not have a name. If `None`,
        then the indices are `list(range(self.shape[1]))`.

    Returns
    -------
    list[Optional[str]]
        Column names.
    """
    if type == "column":
        names = np.array(self._colnames)
    elif type == "term":
        names = np.array(self._terms)
    else:
        raise ValueError(f"Type must be 'column' or 'term', got {type}")

    if indices is None:
        indices = list(range(len(self._colnames)))

    if missing_prefix is not None:
        default_names = np.array([f"{missing_prefix}{i}" for i in indices])
        names[names == None] = default_names[names == None]  # noqa: E711

    return names.tolist()

set_names

set_names(names: str | list[str | None], type: str = 'column')

Set column names.

Parameters:

Name Type Description Default
names str | list[str | None]

Names to set.

required
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
Source code in src/tabmat/sparse_matrix.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def set_names(self, names: str | list[str | None], type: str = "column"):
    """Set column names.

    Parameters
    ----------
    names: list[Optional[str]]
        Names to set.
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    """
    if isinstance(names, str):
        names = [names]

    if len(names) != self.shape[1]:
        raise ValueError(f"Length of names must be {self.shape[1]}")

    if type == "column":
        self._colnames = names
    elif type == "term":
        self._terms = names
    else:
        raise ValueError(f"Type must be 'column' or 'term', got {type}")

CategoricalMatrix

CategoricalMatrix(cat_vec, categories: ndarray | None = None, drop_first: bool = False, dtype: DTypeLike = np.float64, column_name: str | None = None, term_name: str | None = None, column_name_format: str = '{name}[{category}]', cat_missing_method: str = 'fail', cat_missing_name: str = '(MISSING)')

Bases: MatrixBase

A faster, more memory efficient sparse matrix adapted to the specific settings of a one-hot encoded categorical variable.

Parameters:

Name Type Description Default
cat_vec

array-like vector of categorical data.

required
categories ndarray | None

If provided, cat_vec is assumed to be an array-like vector of indices.

None
drop_first bool

drop the first level of the dummy encoding. This allows a CategoricalMatrix to be used in an unregularized setting.

False
cat_missing_method str
  • if 'fail', raise an error if there are missing values.
  • if 'zero', missing values will represent all-zero indicator columns.
  • if 'convert', missing values will be converted to the cat_missing_name category.
'fail'
cat_missing_name str

Name of the category to which missing values will be converted if cat_missing_method='convert'. If this category already exists, an error will be raised.

'(MISSING)'
dtype DTypeLike

data type

float64
Source code in src/tabmat/categorical_matrix.py
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def __init__(
    self,
    cat_vec,
    categories: np.ndarray | None = None,
    drop_first: bool = False,
    dtype: numpy.typing.DTypeLike = np.float64,
    column_name: str | None = None,
    term_name: str | None = None,
    column_name_format: str = "{name}[{category}]",
    cat_missing_method: str = "fail",
    cat_missing_name: str = "(MISSING)",
):
    if cat_missing_method not in {"fail", "zero", "convert"}:
        raise ValueError(
            "cat_missing_method must be one of 'fail' 'zero' or 'convert'; "
            f" got {cat_missing_method}."
        )

    if not hasattr(cat_vec, "dtype"):
        cat_vec = np.asarray(cat_vec)  # avoid errors in pd.factorize

    self._missing_method = cat_missing_method
    self._missing_category = cat_missing_name

    if categories is not None:
        self.categories = categories
        indices = np.nan_to_num(cat_vec, nan=-1)
        if indices.max() >= len(categories):
            raise ValueError("Indices exceed length of categories.")
        if indices.min() < -1:
            raise ValueError("Indices must be non-negative (or -1 for missing).")
    else:
        indices, self.categories = _extract_codes_and_categories(cat_vec)

    if np.any(indices == -1):
        if self._missing_method == "fail":
            raise ValueError(
                "Categorical data can't have missing values "
                "if cat_missing_method='fail'."
            )

        elif self._missing_method == "convert":
            if self._missing_category in self.categories:
                raise ValueError(
                    f"Missing category {self._missing_category} already exists."
                )

            self.categories = np.hstack(
                [self.categories, self._missing_category], dtype="object"
            )

            indices = np.where(indices < 0, len(self.categories) - 1, indices)

            self._has_missings = False

        else:
            self._has_missings = True

    else:
        self._has_missings = False

    self.drop_first = drop_first
    try:
        self.indices = indices.astype(np.int32, copy=False)
    except ValueError:
        raise ValueError(
            "When creating a CategoricalMatrix with indices and categories, "
            "indices must be castable to a numpy int32 dtype."
        )
    self.shape = (len(self.indices), max(len(self.categories) - int(drop_first), 0))
    self.x_csc = None
    self.dtype = np.dtype(dtype)

    self._colname = column_name
    self._colname_format = column_name_format

    if term_name is None:
        self._term = self._colname
    else:
        self._term = term_name

A property

A: ndarray

Convert self into an np.ndarray. Synonym for toarray().

column_names property writable

column_names

Column names of the matrix.

term_names property writable

term_names

Term names of the matrix.

For differences between column names and term names, see get_names.

cat property

cat

Return a series with same data as what was initially fed to init.

This property is available for backward compatibility.

standardize

standardize(weights: ndarray, center_predictors: bool, scale_predictors: bool) -> tuple[Any, np.ndarray, np.ndarray | None]

Return a StandardizedMatrix along with the column means and column standard deviations.

It is often useful to modify a dataset so that each column has mean zero and standard deviation one. This function does this "standardization" without modifying the underlying dataset by storing shifting and scaling factors that are then used whenever an operation is performed with the new StandardizedMatrix.

Note: If center_predictors is False, col_means will be zeros.

Note: If scale_predictors is False, col_stds will be None.

Source code in src/tabmat/matrix_base.py
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
def standardize(
    self, weights: np.ndarray, center_predictors: bool, scale_predictors: bool
) -> tuple[Any, np.ndarray, np.ndarray | None]:
    """
    Return a StandardizedMatrix along with the column means and column standard
    deviations.

    It is often useful to modify a dataset so that each column has mean
    zero and standard deviation one. This function does this "standardization"
    without modifying the underlying dataset by storing shifting and scaling
    factors that are then used whenever an operation is performed with the new
    StandardizedMatrix.

    Note: If center_predictors is False, col_means will be zeros.

    Note: If scale_predictors is False, col_stds will be None.
    """
    from .standardized_mat import StandardizedMatrix

    weights = prepare_vector(weights)
    col_means = self._get_col_means(weights)
    if scale_predictors:
        col_stds = self._get_col_stds(weights, col_means)
        mult = _one_over_var_inf_to_val(col_stds, 1.0)
        if center_predictors:
            shifter = -col_means * mult
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
    else:
        col_stds = None
        if center_predictors:
            shifter = -col_means
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
        mult = None

    out = StandardizedMatrix(self, shifter, mult)
    # Keep the exact means, so that dense products can center the data with
    # them instead of recovering them from shifter / mult.
    out._center = np.array(out_means, copy=True)
    return out, out_means, col_stds

recover_orig

recover_orig() -> np.ndarray

Return 1d numpy array with same data as what was initially fed to init.

Test: matrix/test_categorical_matrix::test_recover_orig

Source code in src/tabmat/categorical_matrix.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
def recover_orig(self) -> np.ndarray:
    """
    Return 1d numpy array with same data as what was initially fed to __init__.

    Test: matrix/test_categorical_matrix::test_recover_orig
    """
    orig = self.categories[self.indices]

    if self._has_missings:
        orig = orig.view(np.ma.MaskedArray)
        orig.mask = self.indices == -1
    elif (
        self._missing_method == "convert"
        and self._missing_category in self.categories
    ):
        orig = orig.view(np.ma.MaskedArray)
        orig.mask = self.indices == len(self.categories) - 1

    return orig

matvec

matvec(other: list | ndarray, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Multiply self with vector 'other', and add vector 'out' if it is present.

out[i] += sum_j mat[i, j] other[j] = other[mat.indices[i]]

The cols parameter allows restricting to a subset of the matrix without making a copy.

If out is None, then a new array will be returned.

Test: test_matrices::test_matvec

Source code in src/tabmat/categorical_matrix.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def matvec(
    self,
    other: list | np.ndarray,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """
    Multiply self with vector 'other', and add vector 'out' if it is present.

    out[i] += sum_j mat[i, j] other[j] = other[mat.indices[i]]

    The cols parameter allows restricting to a subset of the
    matrix without making a copy.

    If out is None, then a new array will be returned.

    Test:
    test_matrices::test_matvec
    """
    check_matvec_out_shape(self, out)
    other, cols = self._matvec_setup(other, cols)
    is_int = np.issubdtype(other.dtype, np.signedinteger)

    if is_int:
        other_m: np.ndarray = other.astype(float)
    else:
        other_m = other

    if out is None:
        out = np.zeros(self.shape[0], dtype=other_m.dtype)

    if self.drop_first or self._has_missings:
        matvec_complex(
            self.indices,
            other_m,
            self.shape[0],
            cols,
            self.shape[1],
            out,
            self.drop_first,
        )
    else:
        matvec_fast(self.indices, other_m, self.shape[0], cols, self.shape[1], out)

    if is_int:
        return out.astype(int)
    return out

transpose_matvec

transpose_matvec(vec: ndarray | list, rows: ndarray | None = None, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform: self[rows, cols].T @ vec[rows].

::

for i in cols: out[i] += sum_{j in rows} self[j, i] vec[j]
self[j, i] = 1(indices[j] == i)


for j in rows:
    for i in cols:
        out[i] += (indices[j] == i) * vec[j]

If cols == range(self.shape[1]), then for every row j, there will be exactly one relevant column, so you can do

::

for j in rows,
    out[indices[j]] += vec[j]

The rows and cols parameters allow restricting to a subset of the matrix without making a copy.

If out is None, then a new array will be returned.

Test: tests/test_matrices::test_transpose_matvec

Source code in src/tabmat/categorical_matrix.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def transpose_matvec(
    self,
    vec: np.ndarray | list,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """

    Perform: self[rows, cols].T @ vec[rows].

    ::

        for i in cols: out[i] += sum_{j in rows} self[j, i] vec[j]
        self[j, i] = 1(indices[j] == i)


        for j in rows:
            for i in cols:
                out[i] += (indices[j] == i) * vec[j]

    If cols == range(self.shape[1]), then for every row j, there will be exactly
        one relevant column, so you can do

    ::

        for j in rows,
            out[indices[j]] += vec[j]

    The rows and cols parameters allow restricting to a subset of the
    matrix without making a copy.

    If out is None, then a new array will be returned.

    Test: tests/test_matrices::test_transpose_matvec
    """
    # TODO: write a function that doesn't reference the data
    # TODO: this should look more like the cat_cat_sandwich
    vec = prepare_vector(vec)
    check_matvec_dimensions(self, vec, transpose=True)
    if vec.ndim > 1:
        raise NotImplementedError(
            "CategoricalMatrix.transpose_matvec is only implemented for 1d arrays."
        )

    if out_is_none := out is None:
        out = np.zeros(self.shape[1], dtype=self.dtype)
    else:
        check_transpose_matvec_out_shape(self, out)

    if rows is not None:
        rows = set_up_rows_or_cols(rows, self.shape[0])
    if cols is not None:
        cols = set_up_rows_or_cols(cols, self.shape[1])

    if self.drop_first or self._has_missings:
        transpose_matvec_complex(
            self.indices,
            vec,
            self.shape[1],
            vec.dtype,
            rows,
            cols,
            out,
            self.drop_first,
        )
    else:
        transpose_matvec_fast(
            self.indices, vec, self.shape[1], vec.dtype, rows, cols, out
        )

    if out_is_none and cols is not None:
        return out[cols, ...]  # type: ignore
    return out

sandwich

sandwich(d: ndarray | list, rows: ndarray | None = None, cols: ndarray | None = None) -> sps.dia_matrix

Perform a sandwich product: X.T @ diag(d) @ X.

.. code-block:: python

sandwich(self, d)[i, j] = (self.T @ diag(d) @ self)[i, j]
    = sum_k (self[k, i] (diag(d) @ self)[k, j])
    = sum_k self[k, i] sum_m diag(d)[k, m] self[m, j]
    = sum_k self[k, i] d[k] self[k, j]
    = 0 if i != j
sandwich(self, d)[i, i] = sum_k self[k, i] ** 2 * d(k)

The rows and cols parameters allow restricting to a subset of the matrix without making a copy.

Source code in src/tabmat/categorical_matrix.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
def sandwich(
    self,
    d: np.ndarray | list,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
) -> sps.dia_matrix:
    """
    Perform a sandwich product: X.T @ diag(d) @ X.

    .. code-block:: python

        sandwich(self, d)[i, j] = (self.T @ diag(d) @ self)[i, j]
            = sum_k (self[k, i] (diag(d) @ self)[k, j])
            = sum_k self[k, i] sum_m diag(d)[k, m] self[m, j]
            = sum_k self[k, i] d[k] self[k, j]
            = 0 if i != j
        sandwich(self, d)[i, i] = sum_k self[k, i] ** 2 * d(k)

    The rows and cols parameters allow restricting to a subset of the
    matrix without making a copy.
    """
    d = prepare_vector(d)
    check_sandwich_compatible(self, d)
    rows = set_up_rows_or_cols(rows, self.shape[0])
    if self.drop_first or self._has_missings:
        res_diag = sandwich_categorical_complex(
            self.indices, d, rows, d.dtype, self.shape[1], self.drop_first
        )
    else:
        res_diag = sandwich_categorical_fast(
            self.indices, d, rows, d.dtype, self.shape[1]
        )

    if cols is not None and len(cols) < self.shape[1]:
        res_diag = res_diag[cols]
    return sps.diags(res_diag)

getcol

getcol(i: int) -> SparseMatrix

Return matrix column at specified index.

Source code in src/tabmat/categorical_matrix.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def getcol(self, i: int) -> SparseMatrix:
    """Return matrix column at specified index."""
    i %= self.shape[1]  # wrap-around indexing

    if self.drop_first:
        i_corr = i + 1
    else:
        i_corr = i

    col_i = sps.csc_matrix((self.indices == i_corr).astype(int)[:, None])
    return SparseMatrix(
        col_i,
        column_names=[self.column_names[i]],
        term_names=[self.term_names[i]],
    )

tocsr

tocsr() -> sps.csr_matrix

Return scipy csr representation of matrix.

Source code in src/tabmat/categorical_matrix.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
def tocsr(self) -> sps.csr_matrix:
    """Return scipy csr representation of matrix."""
    if self.drop_first or self._has_missings:
        nnz, indices, indptr = subset_categorical_complex(
            self.indices, self.shape[1], self.drop_first
        )
        return sps.csr_matrix(
            (np.ones(nnz, dtype=int), indices, indptr), shape=self.shape
        )

    # TODO: data should be uint8
    data: np.ndarray = np.ones(self.shape[0], dtype=int)
    return sps.csr_matrix(
        (data, self.indices, np.arange(self.shape[0] + 1, dtype=int)),
        shape=self.shape,
    )

to_sparse_matrix

to_sparse_matrix()

Return a tabmat.SparseMatrix representation.

Source code in src/tabmat/categorical_matrix.py
716
717
718
719
720
721
722
def to_sparse_matrix(self):
    """Return a tabmat.SparseMatrix representation."""
    return SparseMatrix(
        self.tocsr(),
        column_names=self.column_names,
        term_names=self.term_names,
    )

toarray

toarray() -> np.ndarray

Return array representation of matrix.

Source code in src/tabmat/categorical_matrix.py
724
725
726
def toarray(self) -> np.ndarray:
    """Return array representation of matrix."""
    return self.tocsr().toarray()

unpack

unpack()

Return the underlying pandas.Categorical.

Source code in src/tabmat/categorical_matrix.py
728
729
730
def unpack(self):
    """Return the underlying pandas.Categorical."""
    return self._to_pandas_categorical()

astype

astype(dtype, order='K', casting='unsafe', copy=True)

Return CategoricalMatrix cast to new type.

Source code in src/tabmat/categorical_matrix.py
732
733
734
735
def astype(self, dtype, order="K", casting="unsafe", copy=True):
    """Return CategoricalMatrix cast to new type."""
    self.dtype = np.dtype(dtype)
    return self

multiply

multiply(other) -> SparseMatrix

Element-wise multiplication.

This assumes that other is a vector of size self.shape[0].

Source code in src/tabmat/categorical_matrix.py
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
def multiply(self, other) -> SparseMatrix:
    """Element-wise multiplication.

    This assumes that `other` is a vector of size `self.shape[0]`.
    """
    if self.shape[0] != other.shape[0]:
        raise ValueError(
            f"Shapes do not match. Expected length of {self.shape[0]}. Got "
            f"{len(other)}."
        )

    if self.drop_first or self._has_missings:
        return SparseMatrix(
            sps.csr_matrix(
                multiply_complex(
                    indices=self.indices,
                    d=np.atleast_1d(np.squeeze(other)),
                    ncols=self.shape[1],
                    dtype=other.dtype,
                    drop_first=self.drop_first,
                ),
                shape=self.shape,
            )
        )

    return SparseMatrix(
        sps.csr_matrix(
            (
                np.atleast_1d(np.squeeze(other)),
                self.indices,
                np.arange(self.shape[0] + 1, dtype=int),
            ),
            shape=self.shape,
        ),
        column_names=self.column_names,
        term_names=self.term_names,
    )

get_names

get_names(type: str = 'column', missing_prefix: str | None = None, indices: list[int] | None = None) -> list[str | None]

Get column names.

For columns that do not have a name, a default name is created using the following pattern: "{missing_prefix}{start_index + i}" where i is the index of the column.

Parameters:

Name Type Description Default
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
missing_prefix str | None

Prefix to use for columns that do not have a name. If None, then no default name is created.

None
indices list[int] | None

The indices used for columns that do not have a name. If None, then the indices are list(range(self.shape[1])).

None

Returns:

Type Description
list[Optional[str]]

Column names.

Source code in src/tabmat/categorical_matrix.py
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
def get_names(
    self,
    type: str = "column",
    missing_prefix: str | None = None,
    indices: list[int] | None = None,
) -> list[str | None]:
    """Get column names.

    For columns that do not have a name, a default name is created using the
    following pattern: `"{missing_prefix}{start_index + i}"` where `i` is
    the index of the column.

    Parameters
    ----------
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    missing_prefix: Optional[str], default None
        Prefix to use for columns that do not have a name. If None, then no
        default name is created.
    indices
        The indices used for columns that do not have a name. If `None`,
        then the indices are `list(range(self.shape[1]))`.

    Returns
    -------
    list[Optional[str]]
        Column names.
    """
    if type == "column":
        name = self._colname
    elif type == "term":
        name = self._term
    else:
        raise ValueError(f"Type must be 'column' or 'term', got {type}")

    if indices is None:
        indices = list(range(len(self.categories) - self.drop_first))
    if name is None and missing_prefix is None:
        return [None] * (len(self.categories) - self.drop_first)
    elif name is None:
        name = f"{missing_prefix}{indices[0]}-{indices[-1]}"

    if type == "column":
        return [
            self._colname_format.format(name=name, category=cat)
            for cat in self.categories[self.drop_first :]
        ]
    else:
        return [name] * (len(self.categories) - self.drop_first)

set_names

set_names(names: str | list[str | None], type: str = 'column')

Set column names.

Parameters:

Name Type Description Default
names str | list[str | None]

Names to set.

required
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
Source code in src/tabmat/categorical_matrix.py
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
def set_names(self, names: str | list[str | None], type: str = "column"):
    """Set column names.

    Parameters
    ----------
    names: list[Optional[str]]
        Names to set.
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    """
    if isinstance(names, str):
        names = [names]

    if len(names) != 1:
        if type == "column":
            # Try finding the column name
            base_names = []
            for name, cat in zip(names, self.categories[self.drop_first :]):
                partial_name = self._colname_format.format(
                    name="__CAPTURE__", category=cat
                )
                pattern = re.escape(partial_name).replace("__CAPTURE__", "(.*)")
                if name is not None:
                    match = re.search(pattern, name)
                else:
                    match = None
                if match is not None:
                    base_names.append(match.group(1))
                else:
                    base_names.append(name)
            names = base_names

        if len(names) == self.shape[1] and all(name == names[0] for name in names):
            names = [names[0]]

    if len(names) != 1:
        raise ValueError("A categorical matrix has only one name")

    if type == "column":
        self._colname = names[0]
    elif type == "term":
        self._term = names[0]
    else:
        raise ValueError(f"Type must be 'column' or 'term', got {type}")

SplitMatrix

SplitMatrix(matrices: Sequence[MatrixBase], indices: list[ndarray] | None = None)

Bases: MatrixBase

A class for matrices with sparse, dense and categorical parts.

For real-world tabular data, it's common for the same dataset to contain a mix of columns that are naturally dense, naturally sparse and naturally categorical. Representing each of these sets of columns in the format that is most natural allows for a significant speedup in matrix multiplications compared to representations that are entirely dense or entirely sparse.

Initialize a SplitMatrix directly with a list of matrices and a list of column indices for each matrix. Most of the time, it will be best to use tabmat.from_pandas or tabmat.from_csc to initialize a SplitMatrix.

Parameters:

Name Type Description Default
matrices Sequence[MatrixBase]

The sub-matrices composing the columns of this SplitMatrix.

required
indices list[ndarray] | None

If indices is not None, then for each matrix passed in matrices, indices must contain the set of columns which that matrix covers.

None
Source code in src/tabmat/split_matrix.py
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
def __init__(
    self,
    matrices: Sequence[MatrixBase],
    indices: list[np.ndarray] | None = None,
):
    flatten_matrices = []
    index_corrections = []
    # First check that all matrices are valid types
    for mat in matrices:
        if not isinstance(mat, MatrixBase):
            raise ValueError(
                "Expected all elements of matrices to be subclasses of MatrixBase."
            )
        if isinstance(mat, SplitMatrix):
            # Flatten out the SplitMatrix
            current_idx = 0
            for iind, imat in zip(mat.indices, mat.matrices):  # type: ignore
                flatten_matrices.append(imat)
                index_corrections.append(
                    iind - np.arange(len(iind), dtype=np.int64) - current_idx
                )
                current_idx += len(iind)
        else:
            flatten_matrices.append(mat)
            if len(mat.shape) == 1:
                index_corrections.append(np.zeros(1, dtype=np.int64))
            else:
                index_corrections.append(np.zeros(mat.shape[1], dtype=np.int64))

    # Now that we know these are all MatrixBase, we can check consistent
    # shapes and dtypes.
    self.dtype = flatten_matrices[0].dtype
    n_row = flatten_matrices[0].shape[0]
    for i, mat in enumerate(flatten_matrices):
        if mat.dtype != self.dtype:
            warnings.warn(
                "Matrices do not all have the same dtype. Dtypes are "
                f"{[elt.dtype for elt in flatten_matrices]}."
            )
        if not mat.shape[0] == n_row:
            raise ValueError(
                "All matrices should have the same first dimension, "
                f"but the first matrix has first dimension {n_row} and matrix {i} "
                f"has first dimension {mat.shape[0]}."
            )
        if mat.ndim == 1:
            flatten_matrices[i] = mat[:, np.newaxis]
        elif mat.ndim > 2:
            raise ValueError("All matrices should be at most two dimensional.")

    if indices is None:
        indices = []
        current_idx = 0
        for mat, ind_corr in zip(flatten_matrices, index_corrections):
            indices.append(
                np.arange(current_idx, current_idx + mat.shape[1], dtype=np.int64)
                + ind_corr
            )
            current_idx += mat.shape[1]
        n_col = current_idx
    else:
        all_indices = np.concatenate(indices)
        n_col = len(all_indices)

        if (np.arange(n_col, dtype=np.int64) != np.sort(all_indices)).any():
            raise ValueError(
                "Indices should contain all integers from 0 to one less than the "
                "number of columns."
            )

        for i in range(len(indices)):
            indices[i] = np.asarray(indices[i])
            if not is_sorted(indices[i]):
                raise ValueError(
                    f"Each index block should be sorted, but indices[{i}] was "
                    "not sorted"
                )

    assert isinstance(indices, list)

    for i, (mat, idx) in enumerate(zip(flatten_matrices, indices)):
        if not mat.shape[1] == len(idx):
            raise ValueError(
                f"Element {i} of indices should should have length {mat.shape[1]}, "
                f"but it has shape {idx.shape}"
            )

    filtered_mats, filtered_idxs = _filter_out_empty(flatten_matrices, indices)
    combined_matrices, combined_indices = _combine_matrices(
        filtered_mats, filtered_idxs
    )

    self.matrices = combined_matrices
    self.indices = [np.asarray(elt, dtype=np.int64) for elt in combined_indices]
    self.shape = (n_row, n_col)

    assert self.shape[1] > 0

A property

A: ndarray

Convert self into an np.ndarray. Synonym for toarray().

column_names property writable

column_names

Column names of the matrix.

term_names property writable

term_names

Term names of the matrix.

For differences between column names and term names, see get_names.

standardize

standardize(weights: ndarray, center_predictors: bool, scale_predictors: bool) -> tuple[Any, np.ndarray, np.ndarray | None]

Return a StandardizedMatrix along with the column means and column standard deviations.

It is often useful to modify a dataset so that each column has mean zero and standard deviation one. This function does this "standardization" without modifying the underlying dataset by storing shifting and scaling factors that are then used whenever an operation is performed with the new StandardizedMatrix.

Note: If center_predictors is False, col_means will be zeros.

Note: If scale_predictors is False, col_stds will be None.

Source code in src/tabmat/matrix_base.py
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
def standardize(
    self, weights: np.ndarray, center_predictors: bool, scale_predictors: bool
) -> tuple[Any, np.ndarray, np.ndarray | None]:
    """
    Return a StandardizedMatrix along with the column means and column standard
    deviations.

    It is often useful to modify a dataset so that each column has mean
    zero and standard deviation one. This function does this "standardization"
    without modifying the underlying dataset by storing shifting and scaling
    factors that are then used whenever an operation is performed with the new
    StandardizedMatrix.

    Note: If center_predictors is False, col_means will be zeros.

    Note: If scale_predictors is False, col_stds will be None.
    """
    from .standardized_mat import StandardizedMatrix

    weights = prepare_vector(weights)
    col_means = self._get_col_means(weights)
    if scale_predictors:
        col_stds = self._get_col_stds(weights, col_means)
        mult = _one_over_var_inf_to_val(col_stds, 1.0)
        if center_predictors:
            shifter = -col_means * mult
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
    else:
        col_stds = None
        if center_predictors:
            shifter = -col_means
            out_means = col_means
        else:
            shifter = np.zeros_like(col_means)
            out_means = shifter
        mult = None

    out = StandardizedMatrix(self, shifter, mult)
    # Keep the exact means, so that dense products can center the data with
    # them instead of recovering them from shifter / mult.
    out._center = np.array(out_means, copy=True)
    return out, out_means, col_stds

astype

astype(dtype, order='K', casting='unsafe', copy=True)

Return SplitMatrix cast to new type.

Source code in src/tabmat/split_matrix.py
293
294
295
296
297
298
299
300
301
302
303
304
305
def astype(self, dtype, order="K", casting="unsafe", copy=True):
    """Return SplitMatrix cast to new type."""
    if copy:
        new_matrices = [
            mat.astype(dtype=dtype, order=order, casting=casting, copy=True)
            for mat in self.matrices
        ]
        return SplitMatrix(new_matrices, self.indices)
    for i in range(len(self.matrices)):
        self.matrices[i] = self.matrices[i].astype(
            dtype=dtype, order=order, casting=casting, copy=False
        )
    return SplitMatrix(self.matrices, self.indices)

toarray

toarray() -> np.ndarray

Return array representation of matrix.

Source code in src/tabmat/split_matrix.py
307
308
309
310
311
312
def toarray(self) -> np.ndarray:
    """Return array representation of matrix."""
    out = np.empty(self.shape)
    for mat, idx in zip(self.matrices, self.indices):
        out[:, idx] = mat.toarray()
    return out

getcol

getcol(i: int) -> np.ndarray | sps.csr_matrix

Return matrix column at specified index.

Source code in src/tabmat/split_matrix.py
314
315
316
317
318
319
320
321
322
def getcol(self, i: int) -> np.ndarray | sps.csr_matrix:
    """Return matrix column at specified index."""
    # wrap-around indexing
    i %= self.shape[1]
    for mat, idx in zip(self.matrices, self.indices):
        if i in idx:
            loc = np.where(idx == i)[0][0]
            return mat.getcol(loc)
    raise RuntimeError(f"Column {i} was not found.")

sandwich

sandwich(d: ndarray | list, rows: ndarray | None = None, cols: ndarray | None = None) -> np.ndarray

Perform a sandwich product: X.T @ diag(d) @ X.

Source code in src/tabmat/split_matrix.py
324
325
326
327
328
329
330
331
def sandwich(
    self,
    d: np.ndarray | list,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
) -> np.ndarray:
    """Perform a sandwich product: X.T @ diag(d) @ X."""
    return self._centered_sandwich(d, None, rows, cols)

matvec

matvec(v: ndarray, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform self[:, cols] @ other[cols].

Source code in src/tabmat/split_matrix.py
419
420
421
422
423
424
425
426
def matvec(
    self,
    v: np.ndarray,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """Perform self[:, cols] @ other[cols]."""
    return self._centered_matvec(v, None, cols, out)

transpose_matvec

transpose_matvec(v: ndarray | list, rows: ndarray | None = None, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform: self[rows, cols].T @ vec[rows].

::

self.transpose_matvec(v, rows, cols) = self[rows, cols].T @ v[rows]
self.transpose_matvec(v, rows, cols)[i]
    = sum_{j in rows} self[j, cols[i]] v[j]
    = sum_{j in rows} sum_{mat in self.matrices} 1(cols[i] in mat)
                                                self[j, cols[i]] v[j]
Source code in src/tabmat/split_matrix.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
def transpose_matvec(
    self,
    v: np.ndarray | list,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """
    Perform: self[rows, cols].T @ vec[rows].

    ::

        self.transpose_matvec(v, rows, cols) = self[rows, cols].T @ v[rows]
        self.transpose_matvec(v, rows, cols)[i]
            = sum_{j in rows} self[j, cols[i]] v[j]
            = sum_{j in rows} sum_{mat in self.matrices} 1(cols[i] in mat)
                                                        self[j, cols[i]] v[j]
    """
    return self._centered_transpose_matvec(v, None, rows, cols, out)

multiply

multiply(other)

Element-wise multiplication.

This assumes that other is a vector of size self.shape[0].

Source code in src/tabmat/split_matrix.py
556
557
558
559
560
561
562
563
def multiply(self, other):
    """Element-wise multiplication.

    This assumes that `other` is a vector of size `self.shape[0]`.
    """
    return SplitMatrix(
        [mat.multiply(other) for mat in self.matrices], indices=self.indices
    )

get_names

get_names(type: str = 'column', missing_prefix: str | None = None, indices: list[int] | None = None) -> list[str | None]

Get column names.

For columns that do not have a name, a default name is created using the following pattern: "{missing_prefix}{start_index + i}" where i is the index of the column.

Parameters:

Name Type Description Default
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
missing_prefix str | None

Prefix to use for columns that do not have a name. If None, then no default name is created.

None
indices list[int] | None

The indices used for columns that do not have a name. If None, then the indices are list(range(self.shape[1])).

None

Returns:

Type Description
list[Optional[str]]

Column names.

Source code in src/tabmat/split_matrix.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def get_names(
    self,
    type: str = "column",
    missing_prefix: str | None = None,
    indices: list[int] | None = None,
) -> list[str | None]:
    """Get column names.

    For columns that do not have a name, a default name is created using the
    following pattern: `"{missing_prefix}{start_index + i}"` where `i` is
    the index of the column.

    Parameters
    ----------
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    missing_prefix: Optional[str], default None
        Prefix to use for columns that do not have a name. If None, then no
        default name is created.
    indices
        The indices used for columns that do not have a name. If `None`,
        then the indices are `list(range(self.shape[1]))`.

    Returns
    -------
    list[Optional[str]]
        Column names.
    """
    names: np.ndarray = np.empty(self.shape[1], dtype=object)
    for idx, mat in zip(self.indices, self.matrices):
        names[idx] = mat.get_names(type, missing_prefix, idx)
    return names.tolist()

set_names

set_names(names: str | list[str | None], type: str = 'column')

Set column names.

Parameters:

Name Type Description Default
names str | list[str | None]

Names to set.

required
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
Source code in src/tabmat/split_matrix.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
def set_names(self, names: str | list[str | None], type: str = "column"):
    """Set column names.

    Parameters
    ----------
    names: list[Optional[str]]
        Names to set.
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    """
    names_array = np.array(names)

    if len(names) != self.shape[1]:
        raise ValueError(f"Length of names must be {self.shape[1]}")

    for idx, mat in zip(self.indices, self.matrices):
        mat.set_names(names_array[idx].tolist(), type)

StandardizedMatrix

StandardizedMatrix(mat: MatrixBase, shift: ndarray | list, mult: ndarray | list | None = None)

StandardizedMatrix allows for storing a matrix standardized to have columns that have mean zero and standard deviation one without modifying underlying sparse matrices.

To be precise, for a StandardizedMatrix:

::

self[i, j] = (self.mult[j] * self.mat[i, j]) + self.shift[j]

This class is returned from MatrixBase.standardize.

Source code in src/tabmat/standardized_mat.py
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
def __init__(
    self,
    mat: MatrixBase,
    shift: np.ndarray | list,
    mult: np.ndarray | list | None = None,
):
    shift_arr = np.atleast_1d(np.squeeze(shift))
    expected_shape = (mat.shape[1],)
    if not isinstance(mat, MatrixBase):
        raise TypeError("mat should be an instance of a MatrixBase subclass.")
    if not shift_arr.shape == expected_shape:
        raise ValueError(
            f"""Expected shift to be able to conform to shape {expected_shape},
        but it has shape {np.asarray(shift).shape}"""
        )

    if mult is not None:
        mult_arr = np.atleast_1d(np.squeeze(mult))
        if not mult_arr.shape == expected_shape:
            raise ValueError(
                f"""Expected mult to be able to conform to shape {expected_shape},
            but it has shape {np.asarray(mult).shape}"""
            )
    else:
        mult_arr = None

    self.shift = shift_arr
    self.mult = mult_arr
    self.mat = mat
    self.shape = mat.shape
    self.ndim = mat.ndim
    self.dtype = mat.dtype

A property

A: ndarray

Return array representation of self.

column_names property writable

column_names

Column names of the matrix.

term_names property writable

term_names

Term names of the matrix.

For differences between column names and term names, see get_names.

matvec

matvec(other_mat: ndarray | list, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform self[:, cols] @ other[cols].

This function returns a dense output, so it is best geared for the matrix-vector case.

Source code in src/tabmat/standardized_mat.py
 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
def matvec(
    self,
    other_mat: np.ndarray | list,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """
    Perform self[:, cols] @ other[cols].

    This function returns a dense output, so it is best geared for the
    matrix-vector case.
    """
    cols = set_up_rows_or_cols(cols, self.shape[1])

    other_mat = np.asarray(other_mat)
    check_matvec_dimensions(self, other_mat, transpose=False)
    mult_other = other_mat
    if self.mult is not None:
        mult = self.mult
        # Avoiding an outer product by matching dimensions.
        for _ in range(len(other_mat.shape) - 1):
            mult = mult[:, np.newaxis]
        mult_other = mult * other_mat
    # Center the dense columns inside the kernels, see sandwich.
    center, shift = self._dense_centering()
    mat_part = self.mat._centered_matvec(mult_other, center, cols, out=out)

    # Add shift part to mat_part
    shift_part = shift[cols].dot(other_mat[cols, ...])  # scalar
    mat_part += shift_part
    return mat_part

getcol

getcol(i: int)

Return matrix column at specified index.

Returns a StandardizedMatrix.

from scipy import sparse as sps x = StandardizedMatrix(SparseMatrix(sps.eye(3).tocsc()), shift=[0, 1, -2]) col_1 = x.getcol(1) isinstance(col_1, StandardizedMatrix) True col_1.toarray() array([[1.], [2.], [1.]])

Source code in src/tabmat/standardized_mat.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def getcol(self, i: int):
    """
    Return matrix column at specified index.

    Returns a StandardizedMatrix.

    >>> from scipy import sparse as sps
    >>> x = StandardizedMatrix(SparseMatrix(sps.eye(3).tocsc()), shift=[0, 1, -2])
    >>> col_1 = x.getcol(1)
    >>> isinstance(col_1, StandardizedMatrix)
    True
    >>> col_1.toarray()
    array([[1.],
           [2.],
           [1.]])
    """
    col = self.mat.getcol(i)
    if isinstance(col, sps.csc_matrix) and not isinstance(col, MatrixBase):
        col = SparseMatrix(col)
    return self._with_cols(col, i)

sandwich

sandwich(d: ndarray, rows: ndarray | None = None, cols: ndarray | None = None) -> np.ndarray

Perform a sandwich product: X.T @ diag(d) @ X.

Source code in src/tabmat/standardized_mat.py
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
def sandwich(
    self,
    d: np.ndarray,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
) -> np.ndarray:
    """Perform a sandwich product: X.T @ diag(d) @ X."""
    d = prepare_vector(d)
    check_sandwich_compatible(self, d)
    # stat_mat = mat * mult[newaxis, :] + shift[newaxis, :]
    # stat_mat.T @ d[:, newaxis] * stat_mat
    # = mult[:, newaxis] * mat.T @ d[:, newaxis] * mat * mult[newaxis, :] +   (1)
    #   mult[:, newaxis] * mat.T @ d[:, newaxis] * np.outer(ones, shift) +    (2)
    #   shift[:, newaxis] @ d[:, newaxis] * mat * mult[newaxis, :] +          (3)
    #   shift[:, newaxis] @ d[:, newaxis] * shift[newaxis, :]                 (4)
    #
    # (1) = self.mat.sandwich(d) * np.outer(limited_mult, limited_mult)
    # (2) = mult * self.transpose_matvec(d) * shift[newaxis, :]
    if rows is not None or cols is not None:
        setup_rows, setup_cols = setup_restrictions(self.shape, rows, cols)
        if rows is not None:
            rows = setup_rows
        if cols is not None:
            cols = setup_cols

    # The dense columns are centered inside the kernels, without copying the
    # data: for a DenseMatrix, (1) becomes
    # (mat - center).T @ diag(d) @ (mat - center) and (2) to (4) vanish.
    # Expanding the uncentered product instead forms terms that nearly cancel
    # when a column's mean is large relative to its standard deviation,
    # losing most significant digits.
    center, shift = self._dense_centering()
    term1 = self.mat._centered_sandwich(d, center, rows, cols)
    if isinstance(term1, sps.dia_matrix):
        term1 = np.diag(term1.data[0, :])

    limited_mult = None
    if self.mult is not None:
        limited_mult = self.mult[cols] if cols is not None else self.mult
        term1 *= limited_mult[:, np.newaxis]
        term1 *= limited_mult[np.newaxis, :]
    limited_shift = shift[cols] if cols is not None else shift
    if not limited_shift.any():
        # (2) to (4) vanish without a shift.
        return term1

    d_mat = self.mat._centered_transpose_matvec(d, center, rows, cols)
    if limited_mult is not None:
        d_mat *= limited_mult

    # (2) + (3) + (4) = outer(d_mat, shift) + outer(shift, d_mat)
    #   + sum(d) * outer(shift, shift) = outer(a, shift) + outer(shift, a)
    # with a = d_mat + sum(d) / 2 * shift, which needs a single outer product.
    limited_d = d[rows] if rows is not None else d
    a = d_mat + 0.5 * np.sum(limited_d) * limited_shift
    cross = np.outer(a, limited_shift)
    # Keep the dtype that adding the terms out of place would give.
    term1 = term1.astype(np.result_type(term1, cross), copy=False)
    term1 += cross
    term1 += cross.T
    return term1

unstandardize

unstandardize() -> MatrixBase

Get unstandardized (base) matrix.

Source code in src/tabmat/standardized_mat.py
246
247
248
def unstandardize(self) -> MatrixBase:
    """Get unstandardized (base) matrix."""
    return self.mat

transpose_matvec

transpose_matvec(other: ndarray | list, rows: ndarray | None = None, cols: ndarray | None = None, out: ndarray | None = None) -> np.ndarray

Perform: self[rows, cols].T @ vec[rows].

Let self.shape = (N, K) and other.shape = (M, N). Let shift_mat = outer(ones(N), shift)

(X.T @ other)[k, i] = (X.mat.T @ other)[k, i] + (shift_mat @ other)[k, i] (shift_mat @ other)[k, i] = (outer(shift, ones(N)) @ other)[k, i] = sum_j outer(shift, ones(N))[k, j] other[j, i] = sum_j shift[k] other[j, i] = shift[k] other.sum(0)[i] = outer(shift, other.sum(0))[k, i]

With row and col restrictions:

self.transpose_matvec(other, rows, cols)[i, j] = self.mat.transpose_matvec(other, rows, cols)[i, j] + (outer(self.shift, ones(N))[rows, cols] @ other[cols]) = self.mat.transpose_matvec(other, rows, cols)[i, j] + shift[cols[i]] other.sum(0)[rows[j]

Source code in src/tabmat/standardized_mat.py
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
def transpose_matvec(
    self,
    other: np.ndarray | list,
    rows: np.ndarray | None = None,
    cols: np.ndarray | None = None,
    out: np.ndarray | None = None,
) -> np.ndarray:
    """
    Perform: self[rows, cols].T @ vec[rows].

    Let self.shape = (N, K) and other.shape = (M, N).
    Let shift_mat = outer(ones(N), shift)

    (X.T @ other)[k, i] = (X.mat.T @ other)[k, i] + (shift_mat @ other)[k, i]
    (shift_mat @ other)[k, i] = (outer(shift, ones(N)) @ other)[k, i]
    = sum_j outer(shift, ones(N))[k, j] other[j, i]
    = sum_j shift[k] other[j, i]
    = shift[k] other.sum(0)[i]
    = outer(shift, other.sum(0))[k, i]

    With row and col restrictions:

    self.transpose_matvec(other, rows, cols)[i, j]
        = self.mat.transpose_matvec(other, rows, cols)[i, j]
          + (outer(self.shift, ones(N))[rows, cols] @ other[cols])
        = self.mat.transpose_matvec(other, rows, cols)[i, j]
          + shift[cols[i]] other.sum(0)[rows[j]
    """
    check_transpose_matvec_out_shape(self, out)
    other = np.asarray(other)
    check_matvec_dimensions(self, other, transpose=True)
    # Center the dense columns inside the kernels, see sandwich.
    center, shift = self._dense_centering()
    res = self.mat._centered_transpose_matvec(other, center, rows, cols)

    # Index only if restricted; fancy indexing copies the whole vector.
    if rows is not None:
        other = other[set_up_rows_or_cols(rows, self.shape[0])]
    if cols is not None:
        cols = set_up_rows_or_cols(cols, self.shape[1])
        shift = shift[cols]
    other_sum = np.sum(other, 0)

    shift_part_tmp = np.outer(shift, other_sum)
    output_shape = ((self.shape[1] if cols is None else len(cols)),) + res.shape[1:]
    shift_part = np.reshape(shift_part_tmp, output_shape)

    if self.mult is not None:
        mult = self.mult if cols is None else self.mult[cols]
        # Avoiding an outer product by matching dimensions.
        for _ in range(res.ndim - 1):
            mult = mult[:, np.newaxis]
        res *= mult
    res += shift_part

    if out is None:
        return res
    elif cols is None:
        out += res
    else:
        out[cols] += res
    return out

multiply

multiply(other) -> DenseMatrix

Element-wise multiplication.

Note that the output of this function is always a DenseMatrix and might require a lot more memory. This assumes that other is a vector of size self.shape[0].

Source code in src/tabmat/standardized_mat.py
336
337
338
339
340
341
342
343
def multiply(self, other) -> DenseMatrix:
    """Element-wise multiplication.

    Note that the output of this function is always a DenseMatrix and might
    require a lot more memory. This assumes that `other` is a vector of
    size `self.shape[0]`.
    """
    return DenseMatrix(self.toarray()).multiply(other)

toarray

toarray() -> np.ndarray

Return array representation of matrix.

Source code in src/tabmat/standardized_mat.py
345
346
347
348
349
350
def toarray(self) -> np.ndarray:
    """Return array representation of matrix."""
    mat_part = self.mat.toarray()
    if self.mult is not None:
        mat_part = self.mult[None, :] * mat_part
    return mat_part + self.shift[None, :]

astype

astype(dtype, order='K', casting='unsafe', copy=True)

Return StandardizedMatrix cast to new type.

Source code in src/tabmat/standardized_mat.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def astype(self, dtype, order="K", casting="unsafe", copy=True):
    """Return StandardizedMatrix cast to new type."""
    mult = None
    if self.mult is not None:
        mult = self.mult.astype(dtype, order=order, casting=casting, copy=copy)
    out = type(self)(
        self.mat.astype(dtype, casting=casting, copy=copy),
        self.shift.astype(dtype, order=order, casting=casting, copy=copy),
        mult,
    )
    if self._center is not None:
        out._center = self._center.astype(
            dtype, order=order, casting=casting, copy=copy
        )
    return out

get_names

get_names(type: str = 'column', missing_prefix: str | None = None, indices: list[int] | None = None) -> list[str | None]

Get column names.

For columns that do not have a name, a default name is created using the following pattern: "{missing_prefix}{start_index + i}" where i is the index of the column.

Parameters:

Name Type Description Default
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
missing_prefix str | None

Prefix to use for columns that do not have a name. If None, then no default name is created.

None
indices list[int] | None

The indices used for columns that do not have a name. If None, then the indices are list(range(self.shape[1])).

None

Returns:

Type Description
list[Optional[str]]

Column names.

Source code in src/tabmat/standardized_mat.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def get_names(
    self,
    type: str = "column",
    missing_prefix: str | None = None,
    indices: list[int] | None = None,
) -> list[str | None]:
    """Get column names.

    For columns that do not have a name, a default name is created using the
    following pattern: `"{missing_prefix}{start_index + i}"` where `i` is
    the index of the column.

    Parameters
    ----------
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    missing_prefix: Optional[str], default None
        Prefix to use for columns that do not have a name. If None, then no
        default name is created.
    indices
        The indices used for columns that do not have a name. If `None`,
        then the indices are `list(range(self.shape[1]))`.

    Returns
    -------
    list[Optional[str]]
        Column names.
    """
    return self.mat.get_names(type, missing_prefix, indices)

set_names

set_names(names: str | list[str | None], type: str = 'column')

Set column names.

Parameters:

Name Type Description Default
names str | list[str | None]

Names to set.

required
type str

Whether to get column names or term names. The main difference is that a categorical submatrix counts as one term, but can count as multiple columns. Furthermore, matrices created from formulas distinguish between columns and terms (c.f. formulaic docs).

'column'
Source code in src/tabmat/standardized_mat.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def set_names(self, names: str | list[str | None], type: str = "column"):
    """Set column names.

    Parameters
    ----------
    names: list[Optional[str]]
        Names to set.
    type: str {'column'|'term'}
        Whether to get column names or term names. The main difference is
        that a categorical submatrix counts as one term, but can count as
        multiple columns. Furthermore, matrices created from formulas
        distinguish between columns and terms (c.f. `formulaic` docs).
    """
    self.mat.set_names(names, type)