# TruncatedSVD

### *class* cuml.decomposition.TruncatedSVD(, algorithm='full', n_components=1, n_iter=15, random_state=None, tol=1e-07, verbose=False, output_type=None)

TruncatedSVD is used to compute the top K singular values and vectors of a
large matrix X. It is much faster when n_components is small, such as in
the use of PCA when 3 components is used for 3D visualization.

cuML’s TruncatedSVD an array-like object or cuDF DataFrame, and provides 2
algorithms Full and Jacobi. Full (default) uses a full eigendecomposition
then selects the top K singular vectors. The Jacobi algorithm is much
faster as it iteratively tries to correct the top K singular vectors, but
might be less accurate.

* **Parameters:**
  **algorithm**
  : Full uses a eigendecomposition of the covariance matrix then discards
    components.
    Jacobi is much faster as it iteratively corrects, but is less accurate.

  **n_components**
  : The number of top K singular vectors / values you want.
    Must be <= number(columns).

  **n_iter**
  : Used in Jacobi solver. The more iterations, the more accurate, but
    slower.

  **random_state**
  : If you want results to be the same when you restart Python, select a
    state.

  **tol**
  : Used if algorithm = “jacobi”. Smaller tolerance can increase accuracy,
    but but will slow down the algorithm’s convergence.

  **verbose**
  : Sets logging level. It must be one of `cuml.common.logger.level_*`.
    See [Verbosity Levels](../../cuml/index.html.md#verbosity-levels) for more info.

  **output_type**
  : Return results and set estimator attributes to the indicated output
    type. If None, the output type set at the module level
    (`cuml.global_settings.output_type`) will be used. See
    [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration) for more info.
* **Attributes:**
  **components_**
  : The top K components (VT.T[:,:n_components]) in U, S, VT = svd(X)

  **explained_variance_**
  : How much each component explains the variance in the data given by S\*\*2

  **explained_variance_ratio_**
  : How much in % the variance is explained given by S\*\*2/sum(S\*\*2)

  **singular_values_**
  : The top K singular values. Remember all singular values >= 0

### Methods

| [`fit`](#cuml.decomposition.TruncatedSVD.fit)(self, X[, y])           | Fit model on training cudf DataFrame X.                   |
|------------------------------------------------------------------------------|-----------------------------------------------------------|
| [`fit_transform`](#cuml.decomposition.TruncatedSVD.fit_transform)(self, X[, y]) | Fit model to X and perform dimensionality reduction on X. |
| [`inverse_transform`](#cuml.decomposition.TruncatedSVD.inverse_transform)(self, X)  | Transform X back to its original space.                   |
| [`transform`](#cuml.decomposition.TruncatedSVD.transform)(self, X)          | Perform dimensionality reduction on X.                    |

### Notes

TruncatedSVD (the randomized version [Jacobi]) is fantastic when the number
of components you want is much smaller than the number of features. The
approximation to the largest singular values and vectors is very robust,
however, this method loses a lot of accuracy when you want many, many
components.

**Applications of TruncatedSVD**

TruncatedSVD is also known as Latent Semantic Indexing (LSI) which
tries to find topics of a word count matrix. If X previously was
centered with mean removal, TruncatedSVD is the same as TruncatedPCA.
TruncatedSVD is also used in information retrieval tasks,
recommendation systems and data compression.

For additional documentation, see [scikitlearn’s TruncatedSVD docs](http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.TruncatedSVD.html).

### Examples

```python
>>> # Both import methods supported
>>> from cuml import TruncatedSVD
>>> from cuml.decomposition import TruncatedSVD

>>> import cudf
>>> import cupy as cp

>>> gdf_float = cudf.DataFrame()
>>> gdf_float['0'] = cp.asarray([1.0,2.0,5.0], dtype=cp.float32)
>>> gdf_float['1'] = cp.asarray([4.0,2.0,1.0], dtype=cp.float32)
>>> gdf_float['2'] = cp.asarray([4.0,2.0,1.0], dtype=cp.float32)

>>> tsvd_float = TruncatedSVD(n_components = 2, algorithm = "jacobi",
...                           n_iter = 20, tol = 1e-9)
>>> tsvd_float.fit(gdf_float)
TruncatedSVD(algorithm='jacobi', n_components=2, n_iter=20, tol=1e-09)
>>> print(f'components: {tsvd_float.components_}')
components:           0         1         2
0  0.587259  0.572331  0.572331
1  0.809399 -0.415255 -0.415255
>>> exp_var = tsvd_float.explained_variance_
>>> print(f'explained variance: {exp_var}')
explained variance: 0    0.494...
1    5.505...
dtype: float32
>>> exp_var_ratio = tsvd_float.explained_variance_ratio_
>>> print(f'explained variance ratio: {exp_var_ratio}')
explained variance ratio: 0    0.082...
1    0.917...
dtype: float32
>>> sing_values = tsvd_float.singular_values_
>>> print(f'singular values: {sing_values}')
singular values: 0    7.439...
1    4.081...
dtype: float32

>>> trans_gdf_float = tsvd_float.transform(gdf_float)
>>> print(f'Transformed matrix: {trans_gdf_float}')
Transformed matrix:           0         1
0  5.165910 -2.512643
1  3.463844 -0.042223
2  4.080960  3.216484
>>> input_gdf_float = tsvd_float.inverse_transform(trans_gdf_float)
>>> print(f'Input matrix: {input_gdf_float}')
Input matrix:      0    1    2
0  1.0  4.0  4.0
1  2.0  2.0  2.0
2  5.0  1.0  1.0
```

<!-- !! processed by numpydoc !! -->

#### as_sklearn()[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L206)

Convert this estimator into an equivalent scikit-learn (or scikit-learn
extension) estimator.

* **Returns:**
  sklearn.base.BaseEstimator
  : A scikit-learn compatible estimator instance that mirrors the trained
    state of the current estimator.

<!-- !! processed by numpydoc !! -->

#### fit(self, X, y=None) → 'TruncatedSVD'[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/decomposition/tsvd.pyx#L288)

Fit model on training cudf DataFrame X. y is currently ignored.

* **Parameters:**
  **X**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.

  **y**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.

<!-- !! processed by numpydoc !! -->

#### fit_transform(self, X, y=None)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/decomposition/tsvd.pyx#L298)

Fit model to X and perform dimensionality reduction on X.
y is currently ignored.

* **Parameters:**
  **X**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.

  **y**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.
* **Returns:**
  **trans**
  : Reduced version of X
    <br/>
    For more information on how to configure cuML’s output type,
    refer to: [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration).

<!-- !! processed by numpydoc !! -->

#### *classmethod* from_sklearn(model)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/interop.py#L222)

Create a cuml estimator from a scikit-learn estimator.

* **Parameters:**
  **model**
  : A compatible scikit-learn (or scikit-learn extension) estimator.
* **Returns:**
  cls
  : A new instance of this cuml estimator class that mirrors the
    state of the input estimator.

### Notes

`output_type` of the estimator is set to “numpy” by default, as these
cannot be inferred from training arguments. If something different is
required, then please use cuml’s output_type configuration utilities.

<!-- !! processed by numpydoc !! -->

#### get_feature_names_out(input_features=None)

Get output feature names for transformation.

The feature names out will prefixed by the lowercased class name. For
example, if the transformer outputs 3 features, then the feature names
out are: `["class_name0", "class_name1", "class_name2"]`.

* **Parameters:**
  **input_features**
  : Only used to validate feature names with the names seen in [`fit`](#cuml.decomposition.TruncatedSVD.fit).
* **Returns:**
  **feature_names_out**
  : Transformed feature names.

<!-- !! processed by numpydoc !! -->

#### get_params(deep=True)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L191)

Returns a dict of all params owned by this class. If the child class
has appropriately overridden the `_get_param_names` method and does not
need anything other than what is there in this method, then it doesn’t
have to override this method

<!-- !! processed by numpydoc !! -->

#### inverse_transform(self, X)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/decomposition/tsvd.pyx#L399)

Transform X back to its original space.
Returns X_original whose transform would be X.

* **Parameters:**
  **X**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.
* **Returns:**
  **X_original**
  : X in original space
    <br/>
    For more information on how to configure cuML’s output type,
    refer to: [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration).

<!-- !! processed by numpydoc !! -->

#### set_params(\*\*params)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/internals/base.py#L200)

Accepts a dict of params and updates the corresponding ones owned by
this class. If the child class has appropriately overridden the
`_get_param_names` method and does not need anything other than what is,
there in this method, then it doesn’t have to override this method

<!-- !! processed by numpydoc !! -->

#### transform(self, X)[[source]](https://github.com/NVIDIA/cuml/blob/93418baf5/python/cuml/cuml/decomposition/tsvd.pyx#L461)

Perform dimensionality reduction on X.

* **Parameters:**
  **X**
  : Dense matrix with dtype float32 or float64.
    Acceptable formats: CUDA array interface compliant objects like
    CuPy, cuDF DataFrame/Series, NumPy ndarray and Pandas
    DataFrame/Series.
* **Returns:**
  **X_new**
  : Reduced version of X
    <br/>
    For more information on how to configure cuML’s output type,
    refer to: [Output Data Type Configuration](../../cuml/index.html.md#output-data-type-configuration).

<!-- !! processed by numpydoc !! -->
