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:
|
'fail'
|
cat_missing_name
|
str
|
Name of the category to which missing values will be converted if
|
'(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 | |
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:
|
'fail'
|
cat_missing_name
|
str
|
Name of the category to which missing values will be converted if
|
'(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 | |
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 | |
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}[{category}]'
|
cat_missing_method
|
str
|
How to handle missing values in categorical columns:
|
'fail'
|
cat_missing_name
|
str
|
Name of the category to which missing values will be converted if
|
'(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 ( |
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 |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
toarray
abstractmethod
toarray() -> np.ndarray
Convert self into an np.ndarray.
Source code in src/tabmat/matrix_base.py
109 110 111 112 | |
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 | |
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. |
'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
|
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 | |
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. |
'column'
|
Source code in src/tabmat/matrix_base.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
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
sandwichproduct getcolto support the same interface as SparseMatrix for retrieving a single columntoarraymatvec
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 | |
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 | |
transpose
transpose()
Returns a view of the array with axes transposed.
Source code in src/tabmat/dense_matrix.py
128 129 130 | |
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 | |
getcol
getcol(i)
Return matrix column at specified index.
Source code in src/tabmat/dense_matrix.py
142 143 144 145 146 147 148 | |
toarray
toarray()
Return array representation of matrix.
Source code in src/tabmat/dense_matrix.py
150 151 152 | |
unpack
unpack()
Return the underlying numpy.ndarray.
Source code in src/tabmat/dense_matrix.py
154 155 156 | |
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 | |
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 | |
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 | |
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 | |
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. |
'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
|
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 | |
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. |
'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 | |
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 | |
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 | |
tocsc
tocsc(copy=False)
Return the matrix in CSC format.
Source code in src/tabmat/sparse_matrix.py
159 160 161 | |
transpose
transpose()
Returns a view of the array with axes transposed.
Source code in src/tabmat/sparse_matrix.py
163 164 165 | |
getcol
getcol(i)
Return matrix column at specified index.
Source code in src/tabmat/sparse_matrix.py
169 170 171 172 173 174 175 | |
unpack
unpack()
Return the underlying scipy.sparse.csc_matrix.
Source code in src/tabmat/sparse_matrix.py
177 178 179 | |
toarray
toarray()
Return a dense ndarray representation of the matrix.
Source code in src/tabmat/sparse_matrix.py
181 182 183 | |
dot
dot(other)
Return the dot product as a scipy sparse matrix.
Source code in src/tabmat/sparse_matrix.py
185 186 187 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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. |
'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
|
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 | |
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. |
'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 | |
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
|
|
'fail'
|
cat_missing_name
|
str
|
Name of the category to which missing values will be converted if
|
'(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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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 | |
toarray
toarray() -> np.ndarray
Return array representation of matrix.
Source code in src/tabmat/categorical_matrix.py
724 725 726 | |
unpack
unpack()
Return the underlying pandas.Categorical.
Source code in src/tabmat/categorical_matrix.py
728 729 730 | |
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 | |
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 | |
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. |
'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
|
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 | |
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. |
'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 | |
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 |
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 | |
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 | |
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 | |
toarray
toarray() -> np.ndarray
Return array representation of matrix.
Source code in src/tabmat/split_matrix.py
307 308 309 310 311 312 | |
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 | |
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 | |
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 | |
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 | |
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 | |
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. |
'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
|
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 | |
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. |
'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 | |
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 | |
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 | |
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 | |
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 | |
unstandardize
unstandardize() -> MatrixBase
Get unstandardized (base) matrix.
Source code in src/tabmat/standardized_mat.py
246 247 248 | |
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 | |
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 | |
toarray
toarray() -> np.ndarray
Return array representation of matrix.
Source code in src/tabmat/standardized_mat.py
345 346 347 348 349 350 | |
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 | |
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. |
'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
|
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 | |
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. |
'column'
|
Source code in src/tabmat/standardized_mat.py
424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |