snowflake.ml.modeling.cluster.KMeans

class snowflake.ml.modeling.cluster.KMeans(*, n_clusters=8, init='k-means++', n_init='warn', max_iter=300, tol=0.0001, verbose=0, random_state=None, copy_x=True, algorithm='lloyd', input_cols: Optional[Union[str, Iterable[str]]] = None, output_cols: Optional[Union[str, Iterable[str]]] = None, label_cols: Optional[Union[str, Iterable[str]]] = None, passthrough_cols: Optional[Union[str, Iterable[str]]] = None, drop_input_cols: Optional[bool] = False, sample_weight_col: Optional[str] = None)

Bases: BaseTransformer

K-Means clustering For more details on this class, see sklearn.cluster.KMeans

input_cols: Optional[Union[str, List[str]]]

A string or list of strings representing column names that contain features. If this parameter is not specified, all columns in the input DataFrame except the columns specified by label_cols, sample_weight_col, and passthrough_cols parameters are considered input columns. Input columns can also be set after initialization with the set_input_cols method.

label_cols: Optional[Union[str, List[str]]]

This parameter is optional and will be ignored during fit. It is present here for API consistency by convention.

output_cols: Optional[Union[str, List[str]]]

A string or list of strings representing column names that will store the output of predict and transform operations. The length of output_cols must match the expected number of output columns from the specific predictor or transformer class used. If you omit this parameter, output column names are derived by adding an OUTPUT_ prefix to the label column names for supervised estimators, or OUTPUT_<IDX>for unsupervised estimators. These inferred output column names work for predictors, but output_cols must be set explicitly for transformers. In general, explicitly specifying output column names is clearer, especially if you don’t specify the input column names. To transform in place, pass the same names for input_cols and output_cols. be set explicitly for transformers. Output columns can also be set after initialization with the set_output_cols method.

sample_weight_col: Optional[str]

A string representing the column name containing the sample weights. This argument is only required when working with weighted datasets. Sample weight column can also be set after initialization with the set_sample_weight_col method.

passthrough_cols: Optional[Union[str, List[str]]]

A string or a list of strings indicating column names to be excluded from any operations (such as train, transform, or inference). These specified column(s) will remain untouched throughout the process. This option is helpful in scenarios requiring automatic input_cols inference, but need to avoid using specific columns, like index columns, during training or inference. Passthrough columns can also be set after initialization with the set_passthrough_cols method.

drop_input_cols: Optional[bool], default=False

If set, the response of predict(), transform() methods will not contain input columns.

n_clusters: int, default=8

The number of clusters to form as well as the number of centroids to generate.

init: {‘k-means++’, ‘random’}, callable or array-like of shape (n_clusters, n_features), default=’k-means++’

Method for initialization:

‘k-means++’: selects initial cluster centroids using sampling based on an empirical probability distribution of the points’ contribution to the overall inertia. This technique speeds up convergence. The algorithm implemented is “greedy k-means++”. It differs from the vanilla k-means++ by making several trials at each sampling step and choosing the best centroid among them.

‘random’: choose n_clusters observations (rows) at random from data for the initial centroids.

If an array is passed, it should be of shape (n_clusters, n_features) and gives the initial centers.

If a callable is passed, it should take arguments X, n_clusters and a random state and return an initialization.

n_init: ‘auto’ or int, default=10

Number of times the k-means algorithm is run with different centroid seeds. The final results is the best output of n_init consecutive runs in terms of inertia. Several runs are recommended for sparse high-dimensional problems (see kmeans_sparse_high_dim).

When n_init=’auto’, the number of runs depends on the value of init: 10 if using init=’random’ or init is a callable; 1 if using init=’k-means++’ or init is an array-like.

max_iter: int, default=300

Maximum number of iterations of the k-means algorithm for a single run.

tol: float, default=1e-4

Relative tolerance with regards to Frobenius norm of the difference in the cluster centers of two consecutive iterations to declare convergence.

verbose: int, default=0

Verbosity mode.

random_state: int, RandomState instance or None, default=None

Determines random number generation for centroid initialization. Use an int to make the randomness deterministic. See Glossary.

copy_x: bool, default=True

When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True (default), then the original data is not modified. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean. Note that if the original data is not C-contiguous, a copy will be made even if copy_x is False. If the original data is sparse, but not in CSR format, a copy will be made even if copy_x is False.

algorithm: {“lloyd”, “elkan”, “auto”, “full”}, default=”lloyd”

K-means algorithm to use. The classical EM-style algorithm is “lloyd”. The “elkan” variation can be more efficient on some datasets with well-defined clusters, by using the triangle inequality. However it’s more memory intensive due to the allocation of an extra array of shape (n_samples, n_clusters).

“auto” and “full” are deprecated and they will be removed in Scikit-Learn 1.3. They are both aliases for “lloyd”.

Methods

fit(dataset)

Compute k-means clustering For more details on this function, see sklearn.cluster.KMeans.fit

fit_predict(dataset)

Compute cluster centers and predict cluster index for each sample For more details on this function, see sklearn.cluster.KMeans.fit_predict

get_input_cols()

Input columns getter.

get_label_cols()

Label column getter.

get_output_cols()

Output columns getter.

get_params([deep])

Get parameters for this transformer.

get_passthrough_cols()

Passthrough columns getter.

get_sample_weight_col()

Sample weight column getter.

get_sklearn_args([default_sklearn_obj, ...])

Get sklearn keyword arguments.

predict(dataset)

Predict the closest cluster each sample in X belongs to For more details on this function, see sklearn.cluster.KMeans.predict

score(dataset)

Opposite of the value of X on the K-means objective For more details on this function, see sklearn.cluster.KMeans.score

set_drop_input_cols([drop_input_cols])

set_input_cols(input_cols)

Input columns setter.

set_label_cols(label_cols)

Label column setter.

set_output_cols(output_cols)

Output columns setter.

set_params(**params)

Set the parameters of this transformer.

set_passthrough_cols(passthrough_cols)

Passthrough columns setter.

set_sample_weight_col(sample_weight_col)

Sample weight column setter.

to_sklearn()

Get sklearn.cluster.KMeans object.

transform(dataset)

Transform X to a cluster-distance space For more details on this function, see sklearn.cluster.KMeans.transform

Attributes

model_signatures

Returns model signature of current class.