jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_normal_direction(visualize=False):
    n_gmms = 2
    dimension = 2

    gmm_ellipse = GmmObstacle(n_gmms=n_gmms)
    gmm_ellipse._gmm = mixture.GaussianMixture(n_components=n_gmms)
    gmm_ellipse._gmm.means_ = np.zeros((n_gmms, dimension))
    gmm_ellipse._gmm.means_[0, :] = [4.4, 0]
    gmm_ellipse._gmm.means_[1, :] = [0, 4.0]

    gmm_ellipse._gmm.covariances_ = np.zeros((n_gmms, dimension, dimension))
    gmm_ellipse._gmm.covariances_[0, :, :] = [[0.6, 0], [0, 4.2]]
    gmm_ellipse._gmm.covariances_[1, :, :] = [[3.7, 0], [0, 0.9]]

    gmm_ellipse._gmm.precisions_cholesky_ = np.zeros((n_gmms, dimension, dimension))
    for ii in range(n_gmms):
        gmm_ellipse._gmm.precisions_cholesky_[ii, :, :] = LA.pinv(
            gmm_ellipse._gmm.covariances_[ii, :, :]
        )
    gmm_ellipse._gmm.weights = 0.5 * np.ones(n_gmms)

    position = np.array([0, 0])

    normal0 = gmm_ellipse.get_normal_direction(position, index=0)
    normal1 = gmm_ellipse.get_normal_direction(position, index=1)

    assert np.dot(normal0, normal1) == 0, "Normals are not perpendicular."
    assert LA.norm(normal0) > 0, "Normal is trivial"
    assert LA.norm(normal1) > 0, "Normal is trivial"

    if visualize:
        n_resolution = 30
        x_lim = [-8, 8]
        y_lim = [-8, 8]

        nx = ny = n_resolution
        x_vals, y_vals = np.meshgrid(
            np.linspace(x_lim[0], x_lim[1], nx),
            np.linspace(y_lim[0], y_lim[1], ny),
        )

        fig, ax = plt.subplots(1, 1, figsize=(7, 6))

        colors = ["green", "red"]

        positions = np.vstack((x_vals.reshape(1, -1), y_vals.reshape(1, -1)))
        normals = np.zeros((positions.shape[0], positions.shape[1], gmm_ellipse.n_gmms))
        for it_gmm in range(gmm_ellipse.n_gmms):
            for ii in range(positions.shape[1]):
                normals[:, ii, it_gmm] = gmm_ellipse.get_normal_direction(
                    position=positions[:, ii], index=it_gmm
                )

            ax.quiver(
                positions[0, :],
                positions[1, :],
                normals[0, :, it_gmm],
                normals[1, :, it_gmm],
                color=colors[it_gmm]
                # color="k",
            )

        gmm_ellipse.plot_obstacle(ax=ax)
        ax.set_aspect("equal", adjustable="box")
        ax.set_xlim(x_lim)
        ax.set_ylim(x_lim)

        ax.grid()
//  [python]
def test_normal_direction(visualize=False):
    n_gmms = 2
    dimension = 2

    gmm_ellipse = GmmObstacle(n_gmms=n_gmms)
    gmm_ellipse._gmm = GaussianMixture(n_components=n_gmms)
    gmm_ellipse._gmm.means_ = np.zeros((n_gmms, dimension))
    gmm_ellipse._gmm.means_[0, :] = [4.4, 0]
    gmm_ellipse._gmm.means_[1, :] = [0, 4.0]

    gmm_ellipse._gmm.covariances_ = np.zeros((n_gmms, dimension, dimension))
    gmm_ellipse._gmm.covariances_[0, :, :] = [[0.6, 0], [0, 4.2]]
    gmm_ellipse._gmm.covariances_[1, :, :] = [[3.7, 0], [0, 0.9]]

    gmm_ellipse._gmm.precisions_cholesky_ = np.zeros((n_gmms, dimension, dimension))
    for ii in range(n_gmms):
        gmm_ellipse._gmm.precisions_cholesky_[ii, :, :] = LA.pinv(
            gmm_ellipse._gmm.covariances_[ii, :, :]
        )
    gmm_ellipse._gmm.weights = 0.5 * np.ones(n_gmms)

    position = np.array([0, 0])

    normal0 = gmm_ellipse.get_normal_direction(position, index=0)
    normal1 = gmm_ellipse.get_normal_direction(position, index=1)

    assert np.dot(normal0, normal1) == 0, "Normals are not perpendicular."
    assert LA.norm(normal0) > 0, "Normal is trivial"
    assert LA.norm(normal1) > 0, "Normal is trivial"

    if visualize:
        n_resolution = 30
        x_lim = [-8, 8]
        y_lim = [-8, 8]

        nx = ny = n_resolution
        x_vals, y_vals = np.meshgrid(
            np.linspace(x_lim[0], x_lim[1], nx),
            np.linspace(y_lim[0], y_lim[1], ny),
        )

        fig, ax = plt.subplots(1, 1, figsize=(7, 6))

        colors = ["green", "red"]

        positions = np.vstack((x_vals.reshape(1, -1), y_vals.reshape(1, -1)))
        normals = np.zeros((positions.shape[0], positions.shape[1], gmm_ellipse.n_gmms))
        for it_gmm in range(gmm_ellipse.n_gmms):
            for ii in range(positions.shape[1]):
                normals[:, ii, it_gmm] = gmm_ellipse.get_normal_direction(
                    position=positions[:, ii], index=it_gmm
                )

            ax.quiver(
                positions[0, :],
                positions[1, :],
                normals[0, :, it_gmm],
                normals[1, :, it_gmm],
                color=colors[it_gmm]
                # color="k",
            )

        gmm_ellipse.plot_obstacle(ax=ax)
        ax.set_aspect("equal", adjustable="box")
        ax.set_xlim(x_lim)
        ax.set_ylim(x_lim)

        ax.grid()
//  [python]
def test_project_point_on_surface_with_offset_center(visualize=False):
    n_gmms = 1
    dimension = 2

    gmm_ellipse = GmmObstacle(n_gmms=n_gmms)
    gmm_ellipse._gmm = mixture.GMM(n_components=gmm_ellipse.n_gmms)
    gmm_ellipse._gmm.means_ = np.zeros((gmm_ellipse.n_gmms, dimension))
    gmm_ellipse._gmm.means_[0, :] = [0.0, 0]

    gmm_ellipse._gmm.covariances_ = np.zeros((n_gmms, dimension, dimension))
    gmm_ellipse._gmm.covariances_[0, :, :] = [[1.0, 0], [0, 4.0]]

    gmm_ellipse._gmm.precisions_cholesky_ = np.zeros((n_gmms, dimension, dimension))
    for ii in range(n_gmms):
        gmm_ellipse._gmm.precisions_cholesky_[ii, :, :] = LA.pinv(
            gmm_ellipse._gmm.covariances_[ii, :, :]
        )
    gmm_ellipse._gmm.weights_ = np.ones(n_gmms) / n_gmms

    offset_center = np.array([0.2, 1.5])
    gmm_ellipse.evaluate_hirarchy_and_reference_points()

    position = np.array([0, 6])
    proj_pos = gmm_ellipse.project_point_on_surface(position, index=0)
    assert np.isclose(gmm_ellipse.get_gamma(proj_pos, index=0), 1)

    position = np.array([3, 5.6])
    proj_pos = gmm_ellipse.project_point_on_surface(position, index=0)
    assert np.isclose(gmm_ellipse.get_gamma(proj_pos, index=0), 1)

    if visualize:
        n_resolution = 10
        x_lim = [-8, 8]
        y_lim = [-8, 8]

        nx = ny = n_resolution
        x_vals, y_vals = np.meshgrid(
            np.linspace(x_lim[0], x_lim[1], nx),
            np.linspace(y_lim[0], y_lim[1], ny),
        )

        fig, ax = plt.subplots(1, 1, figsize=(7, 6))
        gmm_ellipse.plot_obstacle(ax=ax, alpha_obstacle=0.2)

        # levels = np.linspace(0.01, 1., 20 + 1)
        positions = np.vstack((x_vals.reshape(1, -1), y_vals.reshape(1, -1)))
        proj_pos = np.zeros(positions.shape)

        for ii in range(positions.shape[1]):
            proj_pos[:, ii] = gmm_ellipse.project_point_on_surface_with_offcenter_point(
                positions[:, ii], offcenter_point=offset_center, index=0
            )

            ax.plot(
                [positions[0, ii], proj_pos[0, ii]],
                [positions[1, ii], proj_pos[1, ii]],
                "k--",
            )

        ax.plot(offset_center[0], offset_center[1], "+", color="k")

        ax.plot(positions[0, :], positions[1, :], "ro")
        ax.plot(proj_pos[0, :], proj_pos[1, :], "go")

        ax.set_aspect("equal", adjustable="box")
        ax.set_xlim(x_lim)
        ax.set_ylim(x_lim)
        ax.grid()
//  [python]
def test_project_point_on_surface_with_offset_center(visualize=False):
    n_gmms = 1
    dimension = 2

    gmm_ellipse = GmmObstacle(n_gmms=n_gmms)
    gmm_ellipse._gmm = GaussianMixture(n_components=gmm_ellipse.n_gmms)
    gmm_ellipse._gmm.means_ = np.zeros((gmm_ellipse.n_gmms, dimension))
    gmm_ellipse._gmm.means_[0, :] = [0.0, 0]

    gmm_ellipse._gmm.covariances_ = np.zeros((n_gmms, dimension, dimension))
    gmm_ellipse._gmm.covariances_[0, :, :] = [[1.0, 0], [0, 4.0]]

    gmm_ellipse._gmm.precisions_cholesky_ = np.zeros((n_gmms, dimension, dimension))
    for ii in range(n_gmms):
        gmm_ellipse._gmm.precisions_cholesky_[ii, :, :] = LA.pinv(
            gmm_ellipse._gmm.covariances_[ii, :, :]
        )
    gmm_ellipse._gmm.weights_ = np.ones(n_gmms) / n_gmms

    offset_center = np.array([0.2, 1.5])
    gmm_ellipse.evaluate_hirarchy_and_reference_points()

    position = np.array([0, 6])
    proj_pos = gmm_ellipse.project_point_on_surface(position, index=0)
    assert np.isclose(gmm_ellipse.get_gamma(proj_pos, index=0), 1)

    position = np.array([3, 5.6])
    proj_pos = gmm_ellipse.project_point_on_surface(position, index=0)
    assert np.isclose(gmm_ellipse.get_gamma(proj_pos, index=0), 1)

    if visualize:
        n_resolution = 10
        x_lim = [-8, 8]
        y_lim = [-8, 8]

        nx = ny = n_resolution
        x_vals, y_vals = np.meshgrid(
            np.linspace(x_lim[0], x_lim[1], nx),
            np.linspace(y_lim[0], y_lim[1], ny),
        )

        fig, ax = plt.subplots(1, 1, figsize=(7, 6))
        gmm_ellipse.plot_obstacle(ax=ax, alpha_obstacle=0.2)

        # levels = np.linspace(0.01, 1., 20 + 1)
        positions = np.vstack((x_vals.reshape(1, -1), y_vals.reshape(1, -1)))
        proj_pos = np.zeros(positions.shape)

        for ii in range(positions.shape[1]):
            proj_pos[:, ii] = gmm_ellipse.project_point_on_surface_with_offcenter_point(
                positions[:, ii], offcenter_point=offset_center, index=0
            )

            ax.plot(
                [positions[0, ii], proj_pos[0, ii]],
                [positions[1, ii], proj_pos[1, ii]],
                "k--",
            )

        ax.plot(offset_center[0], offset_center[1], "+", color="k")

        ax.plot(positions[0, :], positions[1, :], "ro")
        ax.plot(proj_pos[0, :], proj_pos[1, :], "go")

        ax.set_aspect("equal", adjustable="box")
        ax.set_xlim(x_lim)
        ax.set_ylim(x_lim)
        ax.grid()
//  [python]
def cluster_GMM(num_clusters, word_vectors):
    # Initalize a GMM object and use it for clustering.
    clf = mixture.GaussianMixture(n_components=num_clusters,
                          covariance_type="tied", init_params='kmeans', max_iter=50)
    # Get cluster assignments.
    clf.fit(word_vectors)
    idx = clf.predict(word_vectors)
    print("Clustering Done...", time.time() - start, "seconds")
    # Get probabilities of cluster assignments.
    idx_proba = clf.predict_proba(word_vectors)
    # Dump cluster assignments and probability of cluster assignments.
    joblib.dump(idx, 'gmm_latestclusmodel_len2alldata.pkl')
    print("Cluster Assignments Saved...")

    joblib.dump(idx_proba, 'gmm_prob_latestclusmodel_len2alldata.pkl')
    print("Probabilities of Cluster Assignments Saved...")
    return (idx, idx_proba)
//  [python]
def cluster_GMM(num_clusters, word_vectors):
    # Initalize a GMM object and use it for clustering.
    clf = GaussianMixture(n_components=num_clusters,
                          covariance_type="tied", init_params='kmeans', max_iter=50)
    # Get cluster assignments.
    clf.fit(word_vectors)
    idx = clf.predict(word_vectors)
    print("Clustering Done...", time.time() - start, "seconds")
    # Get probabilities of cluster assignments.
    idx_proba = clf.predict_proba(word_vectors)
    # Dump cluster assignments and probability of cluster assignments.
    joblib.dump(idx, 'gmm_latestclusmodel_len2alldata.pkl')
    print("Cluster Assignments Saved...")

    joblib.dump(idx_proba, 'gmm_prob_latestclusmodel_len2alldata.pkl')
    print("Probabilities of Cluster Assignments Saved...")
    return (idx, idx_proba)
//  [python]
n_gaussians = means.shape[0]

points = []
for i in range(len(means)):
    x = np.random.multivariate_normal(means[i], covs[i], N )
    points.append(x)

points = np.concatenate(points)

#fit the gaussian model
gmm = mixture.GaussianMixture(n_components=n_gaussians, covariance_type='diag')
//  [python]
n_gaussians = means.shape[0]

points = []
for i in range(len(means)):
    x = np.random.multivariate_normal(means[i], covs[i], N )
    points.append(x)

points = np.concatenate(points)

#fit the gaussian model
gmm = GaussianMixture(n_components=n_gaussians, covariance_type='diag')
//  [python]
def thresholding_gmm(cpm):
    x = cpm[cpm > 0]  # all non-zero values
    gm = mixture.GMM(n_components=2).fit(cpm.reshape(-1,1))
    means = gm.means_
    bg_index = np.argmin(means.mean(axis=1))
    best_th = means[bg_index,0]
    return best_th
//  [python]
def thresholding_gmm(cpm):
    x = cpm[cpm > 0]  # all non-zero values
    gm = GaussianMixture(n_components=2).fit(cpm.reshape(-1,1))
    means = gm.means_
    bg_index = np.argmin(means.mean(axis=1))
    best_th = means[bg_index,0]
    return best_th
//  [python]
def set_gmm(weights, means, covariances):
    out = GMM(n_components = len(means), covariance_type='full')
    out.means_ = means
    out.precisions_cholesky_ = cholesky(inv(covariances))
    out.weights_ = weights
    out.covariances_ = covariances
    return out
//  [python]
def set_gmm(weights, means, covariances):
    out = GaussianMixture(n_components = len(means), covariance_type='full')
    out.means_ = means
    out.precisions_cholesky_ = cholesky(inv(covariances))
    out.weights_ = weights
    out.covariances_ = covariances
    return out
//  [python]
def _transform(self, X):
        if not self.is_initialized():
            # fit a (spherical) Gaussian mixture model to estimate kernel params
            gmix = mixture.GaussianMixture(n_components=self._n_kernel_fcts,
                                   covariance_type="spherical", max_iter=100,
                                   random_state=0)

            gmix.fit(X)

            kernels = []
            for k in range(self._n_kernel_fcts):
                kernels.append(
                    (np.atleast_2d(gmix.means_[k]), gmix.precisions_[k]))

            self._n_features = self._n_kernel_fcts

        transformed = list()
        for kernel in kernels:
            gamma = None if X.shape[1] > 10 else kernel[
                1]  # only use precision for low-dim X
            shift = sklearn.metrics.pairwise.rbf_kernel(X, kernel[0], gamma)
            transformed += [shift]

        transformed = np.hstack(transformed)
        return transformed
//  [python]
def _transform(self, X):
        if not self.is_initialized():
            # fit a (spherical) Gaussian mixture model to estimate kernel params
            gmix = GaussianMixture(n_components=self._n_kernel_fcts,
                                   covariance_type="spherical", max_iter=100,
                                   random_state=0)

            gmix.fit(X)

            kernels = []
            for k in range(self._n_kernel_fcts):
                kernels.append(
                    (np.atleast_2d(gmix.means_[k]), gmix.precisions_[k]))

            self._n_features = self._n_kernel_fcts

        transformed = list()
        for kernel in kernels:
            gamma = None if X.shape[1] > 10 else kernel[
                1]  # only use precision for low-dim X
            shift = sklearn.metrics.pairwise.rbf_kernel(X, kernel[0], gamma)
            transformed += [shift]

        transformed = np.hstack(transformed)
        return transformed
//  [python]
def test_reference_and_normal(visualize=False):
    n_gmms = 2
    dimension = 2

    gmm_ellipse = GmmObstacle(n_gmms=n_gmms)
    gmm_ellipse._gmm = mixture.GMM(n_components=n_gmms)
    gmm_ellipse._gmm.means_ = np.zeros((n_gmms, dimension))
    gmm_ellipse._gmm.means_[0, :] = [3.0, 0]
    gmm_ellipse._gmm.means_[1, :] = [0, 3.0]

    gmm_ellipse._gmm.covars_ = np.zeros((n_gmms, dimension, dimension))
    gmm_ellipse._gmm.covars_[0, :, :] = [[1.0, 0], [0, 3.5]]
    gmm_ellipse._gmm.covars_[1, :, :] = [[3.5, 0], [0, 1.0]]

    gmm_ellipse._gmm.precisions_cholesky_ = np.zeros((n_gmms, dimension, dimension))
    for ii in range(n_gmms):
        gmm_ellipse._gmm.precisions_cholesky_[ii, :, :] = LA.pinv(
            gmm_ellipse._gmm.covars_[ii, :, :]
        )
    gmm_ellipse._gmm.weights_ = 0.5 * np.ones(n_gmms)

    gmm_ellipse.evaluate_hirarchy_and_reference_points()

    if visualize:
        n_resolution = 20
        x_lim = [-8, 8]
        y_lim = [-8, 8]

        nx = ny = n_resolution
        x_vals, y_vals = np.meshgrid(
            np.linspace(x_lim[0], x_lim[1], nx),
            np.linspace(y_lim[0], y_lim[1], ny),
        )

        fig, ax = plt.subplots(1, 1, figsize=(8, 6))

        positions = np.vstack((x_vals.reshape(1, -1), y_vals.reshape(1, -1)))
        references = np.zeros(positions.shape)
        normals = np.zeros(positions.shape)

        print("Start loop")
        for ii in range(positions.shape[1]):
            gmm_ellipse.evaluate_gamma_weights(position=positions[:, ii])
            gmm_ellipse.evalute_weighted_reference_and_normal_offset(
                position=positions[:, ii]
            )

            normals[:, ii] = gmm_ellipse.mean_normal
            references[:, ii] = gmm_ellipse.mean_reference

        ax.quiver(
            positions[0, :],
            positions[1, :],
            normals[0, :],
            normals[1, :],
            color="r",
            label="Normals",
        )

        ax.quiver(
            positions[0, :],
            positions[1, :],
            references[0, :],
            references[1, :],
            color="g",
            label="References",
        )

        ax.set_aspect("equal", adjustable="box")
        ax.set_xlim(x_lim)
        ax.set_ylim(x_lim)
        ax.grid()
        ax.legend()

        gmm_ellipse.plot_obstacle(ax=ax, alpha_obstacle=0.2)

    def get_normal_and_reference(position):
        gmm_ellipse.evaluate_gamma_weights(position=position)
        gmm_ellipse.evalute_weighted_reference_and_normal_offset(position=position)
        return gmm_ellipse.mean_normal, gmm_ellipse.mean_reference

    normal, reference = get_normal_and_reference(np.array([-2, -2]))
    assert np.allclose(normal, reference), "Reference evaluation not symmetric."

    normal, reference = get_normal_and_reference(np.array([2, -6]))
    assert np.cross(reference, normal) < 0, "Wrong direction of rotation."

    normal, reference = get_normal_and_reference(np.array([0, 6]))
    assert np.cross(reference, normal) > 0, "Wrong direction of rotation."
//  [python]
def test_reference_and_normal(visualize=False):
    n_gmms = 2
    dimension = 2

    gmm_ellipse = GmmObstacle(n_gmms=n_gmms)
    gmm_ellipse._gmm = GaussianMixture(n_components=n_gmms)
    gmm_ellipse._gmm.means_ = np.zeros((n_gmms, dimension))
    gmm_ellipse._gmm.means_[0, :] = [3.0, 0]
    gmm_ellipse._gmm.means_[1, :] = [0, 3.0]

    gmm_ellipse._gmm.covariances_ = np.zeros((n_gmms, dimension, dimension))
    gmm_ellipse._gmm.covariances_[0, :, :] = [[1.0, 0], [0, 3.5]]
    gmm_ellipse._gmm.covariances_[1, :, :] = [[3.5, 0], [0, 1.0]]

    gmm_ellipse._gmm.precisions_cholesky_ = np.zeros((n_gmms, dimension, dimension))
    for ii in range(n_gmms):
        gmm_ellipse._gmm.precisions_cholesky_[ii, :, :] = LA.pinv(
            gmm_ellipse._gmm.covariances_[ii, :, :]
        )
    gmm_ellipse._gmm.weights_ = 0.5 * np.ones(n_gmms)

    gmm_ellipse.evaluate_hirarchy_and_reference_points()

    if visualize:
        n_resolution = 20
        x_lim = [-8, 8]
        y_lim = [-8, 8]

        nx = ny = n_resolution
        x_vals, y_vals = np.meshgrid(
            np.linspace(x_lim[0], x_lim[1], nx),
            np.linspace(y_lim[0], y_lim[1], ny),
        )

        fig, ax = plt.subplots(1, 1, figsize=(8, 6))

        positions = np.vstack((x_vals.reshape(1, -1), y_vals.reshape(1, -1)))
        references = np.zeros(positions.shape)
        normals = np.zeros(positions.shape)

        print("Start loop")
        for ii in range(positions.shape[1]):
            gmm_ellipse.evaluate_gamma_weights(position=positions[:, ii])
            gmm_ellipse.evalute_weighted_reference_and_normal_offset(
                position=positions[:, ii]
            )

            normals[:, ii] = gmm_ellipse.mean_normal
            references[:, ii] = gmm_ellipse.mean_reference

        ax.quiver(
            positions[0, :],
            positions[1, :],
            normals[0, :],
            normals[1, :],
            color="r",
            label="Normals",
        )

        ax.quiver(
            positions[0, :],
            positions[1, :],
            references[0, :],
            references[1, :],
            color="g",
            label="References",
        )

        ax.set_aspect("equal", adjustable="box")
        ax.set_xlim(x_lim)
        ax.set_ylim(x_lim)
        ax.grid()
        ax.legend()

        gmm_ellipse.plot_obstacle(ax=ax, alpha_obstacle=0.2)

    def get_normal_and_reference(position):
        gmm_ellipse.evaluate_gamma_weights(position=position)
        gmm_ellipse.evalute_weighted_reference_and_normal_offset(position=position)
        return gmm_ellipse.mean_normal, gmm_ellipse.mean_reference

    normal, reference = get_normal_and_reference(np.array([-2, -2]))
    assert np.allclose(normal, reference), "Reference evaluation not symmetric."

    normal, reference = get_normal_and_reference(np.array([2, -6]))
    assert np.cross(reference, normal) < 0, "Wrong direction of rotation."

    normal, reference = get_normal_and_reference(np.array([0, 6]))
    assert np.cross(reference, normal) > 0, "Wrong direction of rotation."
//  [python]
def _gaussians_fit(self):
        """ Fit GMM to video features.

        Define subset of video collection and fit on it gaussian mixture model.
        If idx_exclude = -1, then whole video collection is used for comprising
        the subset, otherwise video collection excluded video with this index.
        Args:
            idx_exclude: video to exclude (-1 or int in range(0, #_of_videos))
            save: in case of mp lib all computed likelihoods are saved on disk
                before the next step
        """
        for k in range(self._K):
            gmm = mixture.GaussianMixture(n_components=1,
                                  covariance_type='full',
                                  max_iter=150,
                                  random_state=opt.seed,
                                  reg_covar=1e-4)
            total_indexes = np.zeros(len(self._features), dtype=np.bool)
            for idx, video in enumerate(self._videos):
                indexes = np.where(np.asarray(video._z) == k)[0]
                if len(indexes) == 0:
                    continue
                temp = np.zeros(video.n_frames, dtype=np.bool)
                temp[indexes] = True
                total_indexes[video.global_range] = temp

            total_indexes = np.array(total_indexes, dtype=np.bool)
            if opt.load_embed_feat:
                feature = self._features[total_indexes, :]
            else:
                feature = self._embedded_feat[total_indexes, :]
            time1 = time.time()
            try:
                gmm.fit(feature)
            except ValueError:
                gmm = AuxiliaryGMM()
            time2 = time.time()
            # logger.debug('fit gmm %0.6f %d ' % ((time2 - time1), len(feature))
            #              + str(gmm.converged_))

            self._gaussians[k] = gmm

        if opt.bg:
            # with bg model I assume that I use only one component
            for gm_idx, gmm in self._gaussians.items():
                self._gaussians[gm_idx] = GMM_trh(gmm)
//  [python]
def _gaussians_fit(self):
        """ Fit GMM to video features.

        Define subset of video collection and fit on it gaussian mixture model.
        If idx_exclude = -1, then whole video collection is used for comprising
        the subset, otherwise video collection excluded video with this index.
        Args:
            idx_exclude: video to exclude (-1 or int in range(0, #_of_videos))
            save: in case of mp lib all computed likelihoods are saved on disk
                before the next step
        """
        for k in range(self._K):
            gmm = GaussianMixture(n_components=1,
                                  covariance_type='full',
                                  max_iter=150,
                                  random_state=opt.seed,
                                  reg_covar=1e-4)
            total_indexes = np.zeros(len(self._features), dtype=np.bool)
            for idx, video in enumerate(self._videos):
                indexes = np.where(np.asarray(video._z) == k)[0]
                if len(indexes) == 0:
                    continue
                temp = np.zeros(video.n_frames, dtype=np.bool)
                temp[indexes] = True
                total_indexes[video.global_range] = temp

            total_indexes = np.array(total_indexes, dtype=np.bool)
            if opt.load_embed_feat:
                feature = self._features[total_indexes, :]
            else:
                feature = self._embedded_feat[total_indexes, :]
            time1 = time.time()
            try:
                gmm.fit(feature)
            except ValueError:
                gmm = AuxiliaryGMM()
            time2 = time.time()
            # logger.debug('fit gmm %0.6f %d ' % ((time2 - time1), len(feature))
            #              + str(gmm.converged_))

            self._gaussians[k] = gmm

        if opt.bg:
            # with bg model I assume that I use only one component
            for gm_idx, gmm in self._gaussians.items():
                self._gaussians[gm_idx] = GMM_trh(gmm)
//  [python]
def fit_gmm(self, embeddings, random_state = 42):
    """
    Fit Gaussian Mixture model to the embeddings (with dimensionality reduction)
    and return the menas and covariances of the Gaussians and the bic of this model
    """

    if embeddings is not None: 
      embeddings = self.proj_embeddings


    # fit gmm to embeddings 
    gmm1 = mixture.GaussianMixture(n_components=self.n_topics,covariance_type='full', random_state = random_state)
    gmm1.fit(embeddings)

    mus_init = torch.tensor(gmm1.means_)
    sigmas_init = torch.tensor(gmm1.covariances_)

    bic = gmm1.score(embeddings)

    return mus_init, sigmas_init, bic
//  [python]
def fit_gmm(self, embeddings, random_state = 42):
    """
    Fit Gaussian Mixture model to the embeddings (with dimensionality reduction)
    and return the menas and covariances of the Gaussians and the bic of this model
    """

    if embeddings is not None: 
      embeddings = self.proj_embeddings


    # fit gmm to embeddings 
    gmm1 = GaussianMixture(n_components=self.n_topics,covariance_type='full', random_state = random_state)
    gmm1.fit(embeddings)

    mus_init = torch.tensor(gmm1.means_)
    sigmas_init = torch.tensor(gmm1.covariances_)

    bic = gmm1.score(embeddings)

    return mus_init, sigmas_init, bic
//  [python]
def gmm(encodings, **kw):
    nclusters = int(kw['nclusters']) if kw['nclusters'] != None else 3
    if kw['sof'] == 'sample':
        encodings = np.array(encodings)[1:]
    else:
        encodings = np.array(encodings).T[1:]

    if len(encodings) < nclusters:
        return 0, 'sample number should be greater than n_clusters.'

    data = encodings[:, 1:]
    shape = data.shape
    data = np.reshape(data, shape[0] * shape[1])
    data = np.reshape([float(i) for i in data], shape)
    e = ''
    try:
        gmm = mixture.GMM(n_components = nclusters).fit(data)
        cluster_pred = gmm.predict(data)
    except ValueError as e:
        print(e)
        return 0, e

    res = []
    for i in range(len(data)):
        res.append([encodings[i][0], cluster_pred[i]])
    return res, e
//  [python]
def gmm(encodings, **kw):
    nclusters = int(kw['nclusters']) if kw['nclusters'] != None else 3
    if kw['sof'] == 'sample':
        encodings = np.array(encodings)[1:]
    else:
        encodings = np.array(encodings).T[1:]

    if len(encodings) < nclusters:
        return 0, 'sample number should be greater than n_clusters.'

    data = encodings[:, 1:]
    shape = data.shape
    data = np.reshape(data, shape[0] * shape[1])
    data = np.reshape([float(i) for i in data], shape)
    e = ''
    try:
        gmm = GaussianMixture(n_components = nclusters).fit(data)
        cluster_pred = gmm.predict(data)
    except ValueError as e:
        print(e)
        return 0, e

    res = []
    for i in range(len(data)):
        res.append([encodings[i][0], cluster_pred[i]])
    return res, e
//  [python]
def run_gmm(embeddings, num_domains, random_state=42):
	# perform clustering using GMM
	gmm = mixture.GaussianMixture(n_components=num_domains, random_state=random_state, verbose=True)
	gmm.fit(embeddings) # embeddings: (corpus_size, hidden_dim)
	domain_dist = gmm.predict_proba(embeddings) # (corpus_size, num_domains)

	return domain_dist
//  [python]
def run_gmm(embeddings, num_domains, random_state=42):
	# perform clustering using GMM
	gmm = GaussianMixture(n_components=num_domains, random_state=random_state, verbose=True)
	gmm.fit(embeddings) # embeddings: (corpus_size, hidden_dim)
	domain_dist = gmm.predict_proba(embeddings) # (corpus_size, num_domains)

	return domain_dist
//  [python]
def game_hrs_density(GAME, nclass, print_vals=True):
    #Ignore the game hrs less than 2 hrs
    game_data = steam_clean[(steam_clean['game1'] == GAME)&(steam_clean['hrs']>2)]
    #Log hrs
    game_data['loghrs'] = np.log(steam_clean['hrs'])
    #Calculate the mu,sigma to process Gaussian function
    mu_init = np.linspace(min(game_data['loghrs']), max(game_data['loghrs']), nclass).reshape(-1, 1)
    sigma_init = np.array([1] * nclass).reshape(-1, 1, 1)
    gaussian = mixture.GaussianMixture(n_components=nclass, means_init=mu_init, precisions_init=sigma_init).fit(game_data['loghrs'].values.reshape([-1, 1]))
    #print Gaussian Lambda Mean Sigma
    if print_vals:
        print(' lambda: {}\n mean: {}\n sigma: {}\n'.format(gaussian.weights_, gaussian.means_, gaussian.covariances_))
    #Random Generate
    x = np.linspace(min(game_data['loghrs']), max(game_data['loghrs']), 1000)
    #Plot
    dens = pd.DataFrame({'x': x})
    for i in range(nclass):
        dens['y{}'.format(i+1)] = gaussian.weights_[i]* scipy.stats.norm(gaussian.means_[i][0], gaussian.covariances_[i][0][0]).pdf(x)
    dens = dens.melt('x', value_name='gaussian')
    # Building data frame for plotting
    game_plt = ggplot(aes(x='loghrs', y='stat(density)'), game_data) + geom_histogram(bins=25, colour = "black", alpha = 0.7, size = 0.1) + \
               geom_area(dens, aes(x='x', y='gaussian', fill = 'variable'), alpha = 0.5, position = position_dodge(width=0.2)) + geom_density()+ \
               ggtitle(GAME)
    return game_plt
//  [python]
def game_hrs_density(GAME, nclass, print_vals=True):
    #Ignore the game hrs less than 2 hrs
    game_data = steam_clean[(steam_clean['game1'] == GAME)&(steam_clean['hrs']>2)]
    #Log hrs
    game_data['loghrs'] = np.log(steam_clean['hrs'])
    #Calculate the mu,sigma to process Gaussian function
    mu_init = np.linspace(min(game_data['loghrs']), max(game_data['loghrs']), nclass).reshape(-1, 1)
    sigma_init = np.array([1] * nclass).reshape(-1, 1, 1)
    gaussian = GaussianMixture(n_components=nclass, means_init=mu_init, precisions_init=sigma_init).fit(game_data['loghrs'].values.reshape([-1, 1]))
    #print Gaussian Lambda Mean Sigma
    if print_vals:
        print(' lambda: {}\n mean: {}\n sigma: {}\n'.format(gaussian.weights_, gaussian.means_, gaussian.covariances_))
    #Random Generate
    x = np.linspace(min(game_data['loghrs']), max(game_data['loghrs']), 1000)
    #Plot
    dens = pd.DataFrame({'x': x})
    for i in range(nclass):
        dens['y{}'.format(i+1)] = gaussian.weights_[i]* scipy.stats.norm(gaussian.means_[i][0], gaussian.covariances_[i][0][0]).pdf(x)
    dens = dens.melt('x', value_name='gaussian')
    # Building data frame for plotting
    game_plt = ggplot(aes(x='loghrs', y='stat(density)'), game_data) + geom_histogram(bins=25, colour = "black", alpha = 0.7, size = 0.1) + \
               geom_area(dens, aes(x='x', y='gaussian', fill = 'variable'), alpha = 0.5, position = position_dodge(width=0.2)) + geom_density()+ \
               ggtitle(GAME)
    return game_plt
//  [python]
def setup(self):
        feature_all = None
        label_all = []
        # collect features
        for batch in tqdm(self.train_loader,
                          desc='Compute GMM Stats [Collecting]'):
            data = batch['data_aux'].cuda()
            label = batch['label']
            _, feature_list = self.net(data, return_feature_list=True)
            label_all.extend(tensor2list(label))
            feature_processed = process_feature_type(
                feature_list[0], self.trainer_args.feature_type)
            if isinstance(feature_all, type(None)):
                feature_all = tensor2list(feature_processed)
            else:
                feature_all.extend(tensor2list(feature_processed))
        label_all = np.array(label_all)

        # reduce feature dim and perform gmm estimation
        feature_all = np.array(feature_all)
        transform_matrix = reduce_feature_dim(feature_all, label_all,
                                              self.trainer_args.reduce_dim)
        feature_all = np.dot(feature_all, transform_matrix)
        # GMM estimation
        gm = mixture.GaussianMixture(n_components=self.trainer_args.num_clusters,
                             random_state=0,
                             covariance_type='tied').fit(feature_all)
        feature_mean = gm.means_
        feature_prec = gm.precisions_
        component_weight = gm.weights_

        self.feature_mean = torch.Tensor(feature_mean).cuda()
        self.feature_prec = torch.Tensor(feature_prec).cuda()
        self.component_weight = torch.Tensor(component_weight).cuda()
        self.transform_matrix = torch.Tensor(transform_matrix).cuda()
//  [python]
def setup(self):
        feature_all = None
        label_all = []
        # collect features
        for batch in tqdm(self.train_loader,
                          desc='Compute GMM Stats [Collecting]'):
            data = batch['data_aux'].cuda()
            label = batch['label']
            _, feature_list = self.net(data, return_feature_list=True)
            label_all.extend(tensor2list(label))
            feature_processed = process_feature_type(
                feature_list[0], self.trainer_args.feature_type)
            if isinstance(feature_all, type(None)):
                feature_all = tensor2list(feature_processed)
            else:
                feature_all.extend(tensor2list(feature_processed))
        label_all = np.array(label_all)

        # reduce feature dim and perform gmm estimation
        feature_all = np.array(feature_all)
        transform_matrix = reduce_feature_dim(feature_all, label_all,
                                              self.trainer_args.reduce_dim)
        feature_all = np.dot(feature_all, transform_matrix)
        # GMM estimation
        gm = GaussianMixture(n_components=self.trainer_args.num_clusters,
                             random_state=0,
                             covariance_type='tied').fit(feature_all)
        feature_mean = gm.means_
        feature_prec = gm.precisions_
        component_weight = gm.weights_

        self.feature_mean = torch.Tensor(feature_mean).cuda()
        self.feature_prec = torch.Tensor(feature_prec).cuda()
        self.component_weight = torch.Tensor(component_weight).cuda()
        self.transform_matrix = torch.Tensor(transform_matrix).cuda()
//  [python]
def game_hrs_density_p(pred, GAME=None, nclass=1, print_vals=True):
    game_dict = dict(games.values)
    t_GAME = GAME
    if not GAME:
        GAME = np.random.randint(0, games.shape[0])
    else:
        GAME = game_dict[GAME]
    game_data = pd.Series(pred[:, GAME])
    game_data = game_data[game_data > 0]

    # EM algorithm
    mu_init = np.linspace(min(game_data), max(game_data), nclass).reshape(-1, 1)
    sigma_init = np.array([1] * nclass).reshape(-1, 1, 1)
    gaussian = mixture.GaussianMixture(n_components=nclass, means_init=mu_init, precisions_init=sigma_init).fit(game_data.values.reshape([-1, 1]))
    if print_vals:
        print(' lambda: {}\n mean: {}\n sigma: {}\n'.format(gaussian.weights_, gaussian.means_, gaussian.covariances_))
    # building data frame for plotting
    x = np.linspace(min(game_data), max(game_data), 1000)
    dens = pd.DataFrame({'x': x})
    for i in range(nclass):
        dens['y{}'.format(i+1)] = gaussian.weights_[i]* scipy.stats.norm(gaussian.means_[i][0], gaussian.covariances_[i][0][0]).pdf(x)
    dens = dens.melt('x', value_name='gaussian')
    game_data = pd.DataFrame(game_data, columns=['game_daat'])
    game_plt = ggplot(aes(x='game_data', y='stat(density)'), game_data) + geom_histogram(bins=45, colour = "black", alpha = 0.7, size = 0.1) + \
               geom_area(dens, aes(x='x', y='gaussian', fill = 'variable'), alpha = 0.5, position = position_dodge(width=0.2)) + geom_density()+ \
               ggtitle(t_GAME)
    return game_plt
//  [python]
def game_hrs_density_p(pred, GAME=None, nclass=1, print_vals=True):
    game_dict = dict(games.values)
    t_GAME = GAME
    if not GAME:
        GAME = np.random.randint(0, games.shape[0])
    else:
        GAME = game_dict[GAME]
    game_data = pd.Series(pred[:, GAME])
    game_data = game_data[game_data > 0]

    # EM algorithm
    mu_init = np.linspace(min(game_data), max(game_data), nclass).reshape(-1, 1)
    sigma_init = np.array([1] * nclass).reshape(-1, 1, 1)
    gaussian = GaussianMixture(n_components=nclass, means_init=mu_init, precisions_init=sigma_init).fit(game_data.values.reshape([-1, 1]))
    if print_vals:
        print(' lambda: {}\n mean: {}\n sigma: {}\n'.format(gaussian.weights_, gaussian.means_, gaussian.covariances_))
    # building data frame for plotting
    x = np.linspace(min(game_data), max(game_data), 1000)
    dens = pd.DataFrame({'x': x})
    for i in range(nclass):
        dens['y{}'.format(i+1)] = gaussian.weights_[i]* scipy.stats.norm(gaussian.means_[i][0], gaussian.covariances_[i][0][0]).pdf(x)
    dens = dens.melt('x', value_name='gaussian')
    game_data = pd.DataFrame(game_data, columns=['game_daat'])
    game_plt = ggplot(aes(x='game_data', y='stat(density)'), game_data) + geom_histogram(bins=45, colour = "black", alpha = 0.7, size = 0.1) + \
               geom_area(dens, aes(x='x', y='gaussian', fill = 'variable'), alpha = 0.5, position = position_dodge(width=0.2)) + geom_density()+ \
               ggtitle(t_GAME)
    return game_plt
//  [python]
def fit(self, X, y=None):
        """Fit the model. y is optional for unsupervised methods.

        Parameters
        ----------
        X : numpy array of shape (n_samples, n_features)
            The input samples.

        y : numpy array of shape (n_samples,), optional (default=None)
            The ground truth of the input samples (labels).
        """
        # validate inputs X and y (optional)
        X = _check_X(X)
        self._set_n_classes(y)

        self.model_ = mixture.GaussianMixture(n_components=self.n_components,
                                      covariance_type=self.covariance_type,
                                      tol=self.tol,
                                      reg_covar=self.reg_covar,
                                      max_iter=self.max_iter,
                                      n_init=self.n_init,
                                      init_params=self.init_params,
                                      weights_init=self.weights_init,
                                      means_init=self.means_init,
                                      precisions_init=self.precisions_init,
                                      random_state=self.random_state,
                                      warm_start=self.warm_start,
                                      verbose=self.verbose,
                                      verbose_interval=self.verbose_interval)
        self.model_.fit(X=X, y=y)

        return self
//  [python]
def fit(self, X, y=None):
        """Fit the model. y is optional for unsupervised methods.

        Parameters
        ----------
        X : numpy array of shape (n_samples, n_features)
            The input samples.

        y : numpy array of shape (n_samples,), optional (default=None)
            The ground truth of the input samples (labels).
        """
        # validate inputs X and y (optional)
        X = _check_X(X)
        self._set_n_classes(y)

        self.model_ = GaussianMixture(n_components=self.n_components,
                                      covariance_type=self.covariance_type,
                                      tol=self.tol,
                                      reg_covar=self.reg_covar,
                                      max_iter=self.max_iter,
                                      n_init=self.n_init,
                                      init_params=self.init_params,
                                      weights_init=self.weights_init,
                                      means_init=self.means_init,
                                      precisions_init=self.precisions_init,
                                      random_state=self.random_state,
                                      warm_start=self.warm_start,
                                      verbose=self.verbose,
                                      verbose_interval=self.verbose_interval)
        self.model_.fit(X=X, y=y)

        return self
//  [python]
def GMM(self, X2, X, y_train):
        from sklearn.mixture import GMM as GaussianMixture
        k = self.alfa
        X2 = normalize(X2)
        gmm = GaussianMixture(n_components=self.alfa)
        gmm.fit(X2)
        predicted_gmm = gmm.predict(X2)
        fig4 = plt.figure()
        ax = fig4.add_subplot(111, projection='3d')
        jet = plt.cm.jet
        labels = ['cluster 1', 'cluster 2', 'cluster 3', 'cluster 4', 'cluster 5', 'cluster 6', 'cluster 7', 'cluster 8',
                  'cluster 9', 'cluster 10', 'cluster11', 'cluster12', 'cluster13', 'cluster14', 'cluster15', 'cluster 16',
                  'cluster 17', 'cluster 18', 'cluster19', 'cluster20', 'cluster21', 'cluster22']

        colorss = jet(np.linspace(0, 1, self.alfa))
        predicted1 = list()
        for p in range(0, k):
            predicted1.append(list())
        for i in range(0, k):
            predicted1[i].append(np.where(predicted_gmm == i))
        master, purit = self.evaluate_purity(k, predicted1, y_train, np.shape(X2)[0])

        for i in range(0, k):
            ax.scatter(X[predicted1[i], 0], X[predicted1[i], 1], X[predicted1[i], 2], c=colorss[master[i]], edgecolor='k',
                       label=labels[master[i]])
        plt.legend()
        ax.w_xaxis.set_ticklabels(['PC 1'])
        ax.w_yaxis.set_ticklabels(['PC 2'])
        ax.w_zaxis.set_ticklabels(['PC 3'])
        print(purit)
        print(self.isdifferente(master))
        return gmm
//  [python]
def GMM(self, X2, X, y_train):
        from sklearn.mixture import GaussianMixture
        k = self.alfa
        X2 = normalize(X2)
        gmm = GaussianMixture(n_components=self.alfa)
        gmm.fit(X2)
        predicted_gmm = gmm.predict(X2)
        fig4 = plt.figure()
        ax = fig4.add_subplot(111, projection='3d')
        jet = plt.cm.jet
        labels = ['cluster 1', 'cluster 2', 'cluster 3', 'cluster 4', 'cluster 5', 'cluster 6', 'cluster 7', 'cluster 8',
                  'cluster 9', 'cluster 10', 'cluster11', 'cluster12', 'cluster13', 'cluster14', 'cluster15', 'cluster 16',
                  'cluster 17', 'cluster 18', 'cluster19', 'cluster20', 'cluster21', 'cluster22']

        colorss = jet(np.linspace(0, 1, self.alfa))
        predicted1 = list()
        for p in range(0, k):
            predicted1.append(list())
        for i in range(0, k):
            predicted1[i].append(np.where(predicted_gmm == i))
        master, purit = self.evaluate_purity(k, predicted1, y_train, np.shape(X2)[0])

        for i in range(0, k):
            ax.scatter(X[predicted1[i], 0], X[predicted1[i], 1], X[predicted1[i], 2], c=colorss[master[i]], edgecolor='k',
                       label=labels[master[i]])
        plt.legend()
        ax.w_xaxis.set_ticklabels(['PC 1'])
        ax.w_yaxis.set_ticklabels(['PC 2'])
        ax.w_zaxis.set_ticklabels(['PC 3'])
        print(purit)
        print(self.isdifferente(master))
        return gmm
//  [python]
def _fit_new_class_gmm(self, x):
        gmm_list = []
        # 将X转置,行代表通道数据
        # 对每个特征通道拟合一个高斯模型
        x_T = x.T # [b, feature_dim] => [feature_dim, b]
        for idx in range(x_T.shape[0]):
            gmm = mixture.GMM(n_components=self._component).fit(x_T[idx].reshape(-1, 1))
            gmm_list.append(gmm)        
        return gmm_list
//  [python]
def _fit_new_class_gmm(self, x):
        gmm_list = []
        # 将X转置,行代表通道数据
        # 对每个特征通道拟合一个高斯模型
        x_T = x.T # [b, feature_dim] => [feature_dim, b]
        for idx in range(x_T.shape[0]):
            gmm = GaussianMixture(n_components=self._component).fit(x_T[idx].reshape(-1, 1))
            gmm_list.append(gmm)        
        return gmm_list
//  [python]
def fit(
        self,
        inputs: Tuple[np.ndarray, np.ndarray],
        epochs: int = 100,
        lr: float = 0.001,
        gradient_clipping: float = 5,
        weight_decay: float = 1e-4,
        num_cluster: int = 7,
        gmm_reg_covar: float = 1.5e-4,
        gmm_n_init: int = 10,
        gmm_max_iter: int = 300,
        gmm_tol: float = 2e-4,
        random_state: Optional[int] = None,
    ):
        """Fit function for training.

        Parameters
        ----------
        inputs
            A tuple containing (1) the input features and (2) the edge index array (coo representation) of the
            adjacency matrix.
        epochs
            Number of epochs.
        lr
            Learning rate.
        gradient_clipping
            Gradient clipping.
        weight_decay
            Weight decay.
        num_cluster
            Number of cluster.

        """
        x, edge_index_array = inputs
        self._pretrain(x, edge_index_array, lr, weight_decay, epochs, gradient_clipping)

        logger.info("Fitting Gaussian Mixture model for cluster assignments.")
        gmm = mixture.GaussianMixture(n_components=num_cluster, covariance_type="tied", n_init=gmm_n_init, tol=gmm_tol,
                              max_iter=gmm_max_iter, reg_covar=gmm_reg_covar, random_state=random_state)
        self.clust_res = gmm.fit_predict(self.rep)
//  [python]
def fit(
        self,
        inputs: Tuple[np.ndarray, np.ndarray],
        epochs: int = 100,
        lr: float = 0.001,
        gradient_clipping: float = 5,
        weight_decay: float = 1e-4,
        num_cluster: int = 7,
        gmm_reg_covar: float = 1.5e-4,
        gmm_n_init: int = 10,
        gmm_max_iter: int = 300,
        gmm_tol: float = 2e-4,
        random_state: Optional[int] = None,
    ):
        """Fit function for training.

        Parameters
        ----------
        inputs
            A tuple containing (1) the input features and (2) the edge index array (coo representation) of the
            adjacency matrix.
        epochs
            Number of epochs.
        lr
            Learning rate.
        gradient_clipping
            Gradient clipping.
        weight_decay
            Weight decay.
        num_cluster
            Number of cluster.

        """
        x, edge_index_array = inputs
        self._pretrain(x, edge_index_array, lr, weight_decay, epochs, gradient_clipping)

        logger.info("Fitting Gaussian Mixture model for cluster assignments.")
        gmm = GaussianMixture(n_components=num_cluster, covariance_type="tied", n_init=gmm_n_init, tol=gmm_tol,
                              max_iter=gmm_max_iter, reg_covar=gmm_reg_covar, random_state=random_state)
        self.clust_res = gmm.fit_predict(self.rep)
//  [python]
X, y = make_classification(n_samples=1000, n_features=2, n_informative=2,
                           n_redundant=0, n_clusters_per_class=1, random_state=10)
# init the model with 2 components
m = mixture.GaussianMixture(n_components=2)
//  [python]
X, y = make_classification(n_samples=1000, n_features=2, n_informative=2,
                           n_redundant=0, n_clusters_per_class=1, random_state=10)
# init the model with 2 components
m = GaussianMixture(n_components=2)