ML之KMeans:利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析

简介: ML之KMeans:利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析

 

目录

利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析

设计思路

输出结果

核心代码


 

 

 

相关文章

ML之KMeans:利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析

ML之KMeans:利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析实现

 

利用KMeans算法对Boston房价数据集(两特征+归一化)进行二聚类分析

设计思路

 

 

 

输出结果

1. train_boston_data.shape (1460, 81)
2.    Id  MSSubClass MSZoning  ...  SaleType  SaleCondition SalePrice
3. 0   1          60       RL  ...        WD         Normal    208500
4. 1   2          20       RL  ...        WD         Normal    181500
5. 2   3          60       RL  ...        WD         Normal    223500
6. 3   4          70       RL  ...        WD        Abnorml    140000
7. 4   5          60       RL  ...        WD         Normal    250000
8. 
9. [5 rows x 81 columns]
10. train_t.head()    LotFrontage  GarageArea  SalePrice
11. 0         65.0         548     208500
12. 1         80.0         460     181500
13. 2         68.0         608     223500
14. 3         60.0         642     140000
15. 4         84.0         836     250000
16. after scale,train_t.head()    LotFrontage  GarageArea  SalePrice
17. 0     0.207668    0.386460   0.276159
18. 1     0.255591    0.324401   0.240397
19. 2     0.217252    0.428773   0.296026
20. 3     0.191693    0.452750   0.185430
21. 4     0.268371    0.589563   0.331126
22.    LotFrontage  GarageArea
23. 0     0.207668    0.386460
24. 1     0.255591    0.324401
25. 2     0.217252    0.428773
26. 3     0.191693    0.452750
27. 4     0.268371    0.589563
28.                      Id  MSSubClass  LotFrontage  ...    MoSold    YrSold  SalePrice
29. Id             1.000000    0.011156    -0.010601  ...  0.021172  0.000712  -0.021917
30. MSSubClass     0.011156    1.000000    -0.386347  ... -0.013585 -0.021407  -0.084284
31. LotFrontage   -0.010601   -0.386347     1.000000  ...  0.011200  0.007450   0.351799
32. LotArea       -0.033226   -0.139781     0.426095  ...  0.001205 -0.014261   0.263843
33. OverallQual   -0.028365    0.032628     0.251646  ...  0.070815 -0.027347   0.790982
34. OverallCond    0.012609   -0.059316    -0.059213  ... -0.003511  0.043950  -0.077856
35. YearBuilt     -0.012713    0.027850     0.123349  ...  0.012398 -0.013618   0.522897
36. YearRemodAdd  -0.021998    0.040581     0.088866  ...  0.021490  0.035743   0.507101
37. MasVnrArea    -0.050298    0.022936     0.193458  ... -0.005965 -0.008201   0.477493
38. BsmtFinSF1    -0.005024   -0.069836     0.233633  ... -0.015727  0.014359   0.386420
39. BsmtFinSF2    -0.005968   -0.065649     0.049900  ... -0.015211  0.031706  -0.011378
40. BsmtUnfSF     -0.007940   -0.140759     0.132644  ...  0.034888 -0.041258   0.214479
41. TotalBsmtSF   -0.015415   -0.238518     0.392075  ...  0.013196 -0.014969   0.613581
42. 1stFlrSF       0.010496   -0.251758     0.457181  ...  0.031372 -0.013604   0.605852
43. 2ndFlrSF       0.005590    0.307886     0.080177  ...  0.035164 -0.028700   0.319334
44. LowQualFinSF  -0.044230    0.046474     0.038469  ... -0.022174 -0.028921  -0.025606
45. GrLivArea      0.008273    0.074853     0.402797  ...  0.050240 -0.036526   0.708624
46. BsmtFullBath   0.002289    0.003491     0.100949  ... -0.025361  0.067049   0.227122
47. BsmtHalfBath  -0.020155   -0.002333    -0.007234  ...  0.032873 -0.046524  -0.016844
48. FullBath       0.005587    0.131608     0.198769  ...  0.055872 -0.019669   0.560664
49. HalfBath       0.006784    0.177354     0.053532  ... -0.009050 -0.010269   0.284108
50. BedroomAbvGr   0.037719   -0.023438     0.263170  ...  0.046544 -0.036014   0.168213
51. KitchenAbvGr   0.002951    0.281721    -0.006069  ...  0.026589  0.031687  -0.135907
52. TotRmsAbvGrd   0.027239    0.040380     0.352096  ...  0.036907 -0.034516   0.533723
53. Fireplaces    -0.019772   -0.045569     0.266639  ...  0.046357 -0.024096   0.466929
54. GarageYrBlt    0.000072    0.085072     0.070250  ...  0.005337 -0.001014   0.486362
55. GarageCars     0.016570   -0.040110     0.285691  ...  0.040522 -0.039117   0.640409
56. GarageArea     0.017634   -0.098672     0.344997  ...  0.027974 -0.027378   0.623431
57. WoodDeckSF    -0.029643   -0.012579     0.088521  ...  0.021011  0.022270   0.324413
58. OpenPorchSF   -0.000477   -0.006100     0.151972  ...  0.071255 -0.057619   0.315856
59. EnclosedPorch  0.002889   -0.012037     0.010700  ... -0.028887 -0.009916  -0.128578
60. 3SsnPorch     -0.046635   -0.043825     0.070029  ...  0.029474  0.018645   0.044584
61. ScreenPorch    0.001330   -0.026030     0.041383  ...  0.023217  0.010694   0.111447
62. PoolArea       0.057044    0.008283     0.206167  ... -0.033737 -0.059689   0.092404
63. MiscVal       -0.006242   -0.007683     0.003368  ... -0.006495  0.004906  -0.021190
64. MoSold         0.021172   -0.013585     0.011200  ...  1.000000 -0.145721   0.046432
65. YrSold         0.000712   -0.021407     0.007450  ... -0.145721  1.000000  -0.028923
66. SalePrice     -0.021917   -0.084284     0.351799  ...  0.046432 -0.028923   1.000000
67. 
68. [38 rows x 38 columns]
69. k_means_cluster_centers 
70. [[0.1938454  0.21080405]
71. [0.25140958 0.44595543]]
72. k_means_labels_unique 
73. [0 1]
74. 0 [1 1 1 ... 0 0 0]
75. 0 [1 1 1 ... 0 0 0] [False False False ...  True  True  True]
76. 1 [1 1 1 ... 0 0 0]
77. 1 [1 1 1 ... 0 0 0] [ True  True  True ... False False False]

 

 

核心代码

1. class KMeans Found at: sklearn.cluster._kmeans
2. 
3. class KMeans(TransformerMixin, ClusterMixin, BaseEstimator):
4. """K-Means clustering.
5.     
6.     Read more in the :ref:`User Guide <k_means>`.
7.     
8.     Parameters
9.     ----------
10.     
11.     n_clusters : int, default=8
12.     The number of clusters to form as well as the number of
13.     centroids to generate.
14.     
15.     init : {'k-means++', 'random', ndarray, callable}, default='k-
16.      means++'
17.     Method for initialization:
18.     
19.     'k-means++' : selects initial cluster centers for k-mean
20.     clustering in a smart way to speed up convergence. See 
21.      section
22.     Notes in k_init for more details.
23.     
24.     'random': choose `n_clusters` observations (rows) at 
25.      random from data
26.     for the initial centroids.
27.     
28.     If an ndarray is passed, it should be of shape (n_clusters, 
29.      n_features)
30.     and gives the initial centers.
31.     
32.     If a callable is passed, it should take arguments X, 
33.      n_clusters and a
34.     random state and return an initialization.
35.     
36.     n_init : int, default=10
37.     Number of time the k-means algorithm will be run with 
38.      different
39.     centroid seeds. The final results will be the best output of
40.     n_init consecutive runs in terms of inertia.
41.     
42.     max_iter : int, default=300
43.     Maximum number of iterations of the k-means algorithm 
44.      for a
45.     single run.
46.     
47.     tol : float, default=1e-4
48.     Relative tolerance with regards to Frobenius norm of the 
49.      difference
50.     in the cluster centers of two consecutive iterations to 
51.      declare
52.     convergence.
53.     It's not advised to set `tol=0` since convergence might 
54.      never be
55.     declared due to rounding errors. Use a very small number 
56.      instead.
57.     
58.     precompute_distances : {'auto', True, False}, default='auto'
59.     Precompute distances (faster but takes more memory).
60.     
61.     'auto' : do not precompute distances if n_samples * 
62.      n_clusters > 12
63.     million. This corresponds to about 100MB overhead per 
64.      job using
65.     double precision.
66.     
67.     True : always precompute distances.
68.     
69.     False : never precompute distances.
70.     
71.     .. deprecated:: 0.23
72.     'precompute_distances' was deprecated in version 0.22 
73.      and will be
74.     removed in 0.25. It has no effect.
75.     
76.     verbose : int, default=0
77.     Verbosity mode.
78.     
79.     random_state : int, RandomState instance, default=None
80.     Determines random number generation for centroid 
81.      initialization. Use
82.     an int to make the randomness deterministic.
83.     See :term:`Glossary <random_state>`.
84.     
85.     copy_x : bool, default=True
86.     When pre-computing distances it is more numerically 
87.      accurate to center
88.     the data first. If copy_x is True (default), then the original 
89.      data is
90.     not modified. If False, the original data is modified, and put 
91.      back
92.     before the function returns, but small numerical 
93.      differences may be
94.     introduced by subtracting and then adding the data mean. 
95.      Note that if
96.     the original data is not C-contiguous, a copy will be made 
97.      even if
98.     copy_x is False. If the original data is sparse, but not in CSR 
99.      format,
100.     a copy will be made even if copy_x is False.
101.     
102.     n_jobs : int, default=None
103.     The number of OpenMP threads to use for the 
104.      computation. Parallelism is
105.     sample-wise on the main cython loop which assigns each 
106.      sample to its
107.     closest center.
108.     
109.     ``None`` or ``-1`` means using all processors.
110.     
111.     .. deprecated:: 0.23
112.     ``n_jobs`` was deprecated in version 0.23 and will be 
113.      removed in
114.     0.25.
115.     
116.     algorithm : {"auto", "full", "elkan"}, default="auto"
117.     K-means algorithm to use. The classical EM-style algorithm 
118.      is "full".
119.     The "elkan" variation is more efficient on data with well-
120.      defined
121.     clusters, by using the triangle inequality. However it's 
122.      more memory
123.     intensive due to the allocation of an extra array of shape
124.     (n_samples, n_clusters).
125.     
126.     For now "auto" (kept for backward compatibiliy) chooses 
127.      "elkan" but it
128.     might change in the future for a better heuristic.
129.     
130.     .. versionchanged:: 0.18
131.     Added Elkan algorithm
132.     
133.     Attributes
134.     ----------
135.     cluster_centers_ : ndarray of shape (n_clusters, n_features)
136.     Coordinates of cluster centers. If the algorithm stops 
137.      before fully
138.     converging (see ``tol`` and ``max_iter``), these will not be
139.     consistent with ``labels_``.
140.     
141.     labels_ : ndarray of shape (n_samples,)
142.     Labels of each point
143.     
144.     inertia_ : float
145.     Sum of squared distances of samples to their closest 
146.      cluster center.
147.     
148.     n_iter_ : int
149.     Number of iterations run.
150.     
151.     See also
152.     --------
153.     
154.     MiniBatchKMeans
155.     Alternative online implementation that does incremental 
156.      updates
157.     of the centers positions using mini-batches.
158.     For large scale learning (say n_samples > 10k) 
159.      MiniBatchKMeans is
160.     probably much faster than the default batch 
161.      implementation.
162.     
163.     Notes
164.     -----
165.     The k-means problem is solved using either Lloyd's or 
166.      Elkan's algorithm.
167.     
168.     The average complexity is given by O(k n T), were n is the 
169.      number of
170.     samples and T is the number of iteration.
171.     
172.     The worst case complexity is given by O(n^(k+2/p)) with
173.     n = n_samples, p = n_features. (D. Arthur and S. Vassilvitskii,
174.     'How slow is the k-means method?' SoCG2006)
175.     
176.     In practice, the k-means algorithm is very fast (one of the 
177.      fastest
178.     clustering algorithms available), but it falls in local minima. 
179.      That's why
180.     it can be useful to restart it several times.
181.     
182.     If the algorithm stops before fully converging (because of 
183.      ``tol`` or
184.     ``max_iter``), ``labels_`` and ``cluster_centers_`` will not be 
185.      consistent,
186.     i.e. the ``cluster_centers_`` will not be the means of the 
187.      points in each
188.     cluster. Also, the estimator will reassign ``labels_`` after the 
189.      last
190.     iteration to make ``labels_`` consistent with ``predict`` on 
191.      the training
192.     set.
193.     
194.     Examples
195.     --------
196.     
197.     >>> from sklearn.cluster import KMeans
198.     >>> import numpy as np
199.     >>> X = np.array([[1, 2], [1, 4], [1, 0],
200.     ...               [10, 2], [10, 4], [10, 0]])
201.     >>> kmeans = KMeans(n_clusters=2, random_state=0).fit
202.      (X)
203.     >>> kmeans.labels_
204.     array([1, 1, 1, 0, 0, 0], dtype=int32)
205.     >>> kmeans.predict([[0, 0], [12, 3]])
206.     array([1, 0], dtype=int32)
207.     >>> kmeans.cluster_centers_
208.     array([[10.,  2.],
209.     [ 1.,  2.]])
210.     """
211.     @_deprecate_positional_args
212. def __init__(self, n_clusters=8, *, init='k-means++', 
213.      n_init=10, 
214.         max_iter=300, tol=1e-4, 
215.          precompute_distances='deprecated', 
216.         verbose=0, random_state=None, copy_x=True, 
217.         n_jobs='deprecated', algorithm='auto'):
218.         self.n_clusters = n_clusters
219.         self.init = init
220.         self.max_iter = max_iter
221.         self.tol = tol
222.         self.precompute_distances = precompute_distances
223.         self.n_init = n_init
224.         self.verbose = verbose
225.         self.random_state = random_state
226.         self.copy_x = copy_x
227.         self.n_jobs = n_jobs
228.         self.algorithm = algorithm
229. 
230. def _check_test_data(self, X):
231.         X = check_array(X, accept_sparse='csr', dtype=[np.
232.          float64, np.float32], 
233.             order='C', accept_large_sparse=False)
234.         n_samples, n_features = X.shape
235.         expected_n_features = self.cluster_centers_.shape[1]
236. if not n_features == expected_n_features:
237. raise ValueError(
238. "Incorrect number of features. "
239. "Got %d features, expected %d" % 
240.                 (n_features, expected_n_features))
241. return X
242. 
243. def fit(self, X, y=None, sample_weight=None):
244. """Compute k-means clustering.
245. 
246.         Parameters
247.         ----------
248.         X : {array-like, sparse matrix} of shape (n_samples, 
249.          n_features)
250.             Training instances to cluster. It must be noted that the 
251.              data
252.             will be converted to C ordering, which will cause a 
253.              memory
254.             copy if the given data is not C-contiguous.
255.             If a sparse matrix is passed, a copy will be made if it's 
256.              not in
257.             CSR format.
258. 
259.         y : Ignored
260.             Not used, present here for API consistency by 
261.              convention.
262. 
263.         sample_weight : array-like of shape (n_samples,), 
264.          default=None
265.             The weights for each observation in X. If None, all 
266.              observations
267.             are assigned equal weight.
268. 
269.             .. versionadded:: 0.20
270. 
271.         Returns
272.         -------
273.         self
274.             Fitted estimator.
275.         """
276.         random_state = check_random_state(self.random_state)
277. if self.precompute_distances != 'deprecated':
278.             warnings.warn("'precompute_distances' was 
279.              deprecated in version "
280. "0.23 and will be removed in 0.25. It has no "
281. "effect", 
282.                 FutureWarning)
283. if self.n_jobs != 'deprecated':
284.             warnings.warn("'n_jobs' was deprecated in version 
285.              0.23 and will be"
286. " removed in 0.25.", 
287.                 FutureWarning)
288.             self._n_threads = self.n_jobs
289. else:
290.             self._n_threads = None
291.         self._n_threads = _openmp_effective_n_threads(self.
292.          _n_threads)
293.         n_init = self.n_init
294. if n_init <= 0:
295. raise ValueError("Invalid number of initializations."
296. " n_init=%d must be bigger than zero." % 
297.                 n_init)
298. if self.max_iter <= 0:
299. raise ValueError(
300. 'Number of iterations should be a positive number,'
301. ' got %d instead' % 
302.                 self.max_iter)
303.         X = self._validate_data(X, accept_sparse='csr', 
304.             dtype=[np.float64, np.float32], 
305.             order='C', copy=self.copy_x, 
306.             accept_large_sparse=False)
307. # verify that the number of samples given is larger than k
308. if _num_samples(X) < self.n_clusters:
309. raise ValueError("n_samples=%d should be >= 
310.              n_clusters=%d" % (
311.                     _num_samples(X), self.n_clusters))
312.         tol = _tolerance(X, self.tol)
313. # Validate init array
314.         init = self.init
315. if hasattr(init, '__array__'):
316.             init = check_array(init, dtype=X.dtype.type, 
317.              copy=True, order='C')
318.             _validate_center_shape(X, self.n_clusters, init)
319. if n_init != 1:
320.                 warnings.warn('Explicit initial center position 
321.                  passed: '
322. 'performing only one init in k-means instead of 
323.                      n_init=%d' % 
324.                     n_init, RuntimeWarning, stacklevel=2)
325.                 n_init = 1 # subtract of mean of x for more accurate 
326.                  distance computations
327. if not sp.issparse(X):
328.             X_mean = X.mean(axis=0) # The copy was already 
329.              done above
330.             X -= X_mean
331. if hasattr(init, '__array__'):
332.                 init -= X_mean
333. # precompute squared norms of data points
334.         x_squared_norms = row_norms(X, squared=True)
335.         best_labels, best_inertia, best_centers = None, None, 
336. None
337.         algorithm = self.algorithm
338. if algorithm == "elkan" and self.n_clusters == 1:
339.             warnings.warn("algorithm='elkan' doesn't make sense 
340.              for a single "
341. "cluster. Using 'full' instead.", 
342.                 RuntimeWarning)
343.             algorithm = "full"
344. if algorithm == "auto":
345.             algorithm = "full" if self.n_clusters == 1 else "elkan"
346. if algorithm == "full":
347.             kmeans_single = _kmeans_single_lloyd
348. elif algorithm == "elkan":
349.             kmeans_single = _kmeans_single_elkan
350. else:
351. raise ValueError(
352. "Algorithm must be 'auto', 'full' or 'elkan', got"
353. " {}".
354. format(str(algorithm))) # seeds for the initializations 
355.                  of the kmeans runs.
356.         seeds = random_state.randint(np.iinfo(np.int32).max, 
357.          size=n_init)
358. for seed in seeds:
359. # run a k-means once
360.             labels, inertia, centers, n_iter_ = kmeans_single(X, 
361.              sample_weight, self.n_clusters, max_iter=self.max_iter, 
362.                 init=init, verbose=self.verbose, tol=tol, 
363.                 x_squared_norms=x_squared_norms, 
364.                  random_state=seed, 
365.                 n_threads=self._n_threads)
366. # determine if these results are the best so far
367. if best_inertia is None or inertia < best_inertia:
368.                 best_labels = labels.copy()
369.                 best_centers = centers.copy()
370.                 best_inertia = inertia
371.                 best_n_iter = n_iter_
372. 
373. if not sp.issparse(X):
374. if not self.copy_x:
375.                 X += X_mean
376.             best_centers += X_mean
377.         distinct_clusters = len(set(best_labels))
378. if distinct_clusters < self.n_clusters:
379.             warnings.warn("Number of distinct clusters ({}) found 
380.              smaller than "
381. "n_clusters ({}). Possibly due to duplicate points "
382. "in X.".
383. format(distinct_clusters, self.n_clusters), 
384.                  ConvergenceWarning, stacklevel=2)
385.         self.cluster_centers_ = best_centers
386.         self.labels_ = best_labels
387.         self.inertia_ = best_inertia
388.         self.n_iter_ = best_n_iter
389. return self
390. 
391. def fit_predict(self, X, y=None, sample_weight=None):
392. """Compute cluster centers and predict cluster index for 
393.          each sample.
394. 
395.         Convenience method; equivalent to calling fit(X) 
396.          followed by
397.         predict(X).
398. 
399.         Parameters
400.         ----------
401.         X : {array-like, sparse matrix} of shape (n_samples, 
402.          n_features)
403.             New data to transform.
404. 
405.         y : Ignored
406.             Not used, present here for API consistency by 
407.              convention.
408. 
409.         sample_weight : array-like of shape (n_samples,), 
410.          default=None
411.             The weights for each observation in X. If None, all 
412.              observations
413.             are assigned equal weight.
414. 
415.         Returns
416.         -------
417.         labels : ndarray of shape (n_samples,)
418.             Index of the cluster each sample belongs to.
419.         """
420. return self.fit(X, sample_weight=sample_weight).labels_
421. 
422. def fit_transform(self, X, y=None, sample_weight=None):
423. """Compute clustering and transform X to cluster-
424.          distance space.
425. 
426.         Equivalent to fit(X).transform(X), but more efficiently 
427.          implemented.
428. 
429.         Parameters
430.         ----------
431.         X : {array-like, sparse matrix} of shape (n_samples, 
432.          n_features)
433.             New data to transform.
434. 
435.         y : Ignored
436.             Not used, present here for API consistency by 
437.              convention.
438. 
439.         sample_weight : array-like of shape (n_samples,), 
440.          default=None
441.             The weights for each observation in X. If None, all 
442.              observations
443.             are assigned equal weight.
444. 
445.         Returns
446.         -------
447.         X_new : array of shape (n_samples, n_clusters)
448.             X transformed in the new space.
449.         """
450. # Currently, this just skips a copy of the data if it is not in
451. # np.array or CSR format already.
452. # XXX This skips _check_test_data, which may change 
453.          the dtype;
454. # we should refactor the input validation.
455. return self.fit(X, sample_weight=sample_weight).
456.          _transform(X)
457. 
458. def transform(self, X):
459. """Transform X to a cluster-distance space.
460. 
461.         In the new space, each dimension is the distance to the 
462.          cluster
463.         centers.  Note that even if X is sparse, the array returned 
464.          by
465.         `transform` will typically be dense.
466. 
467.         Parameters
468.         ----------
469.         X : {array-like, sparse matrix} of shape (n_samples, 
470.          n_features)
471.             New data to transform.
472. 
473.         Returns
474.         -------
475.         X_new : ndarray of shape (n_samples, n_clusters)
476.             X transformed in the new space.
477.         """
478.         check_is_fitted(self)
479.         X = self._check_test_data(X)
480. return self._transform(X)
481. 
482. def _transform(self, X):
483. """guts of transform method; no input validation"""
484. return euclidean_distances(X, self.cluster_centers_)
485. 
486. def predict(self, X, sample_weight=None):
487. """Predict the closest cluster each sample in X belongs 
488.          to.
489. 
490.         In the vector quantization literature, `cluster_centers_` is 
491.          called
492.         the code book and each value returned by `predict` is 
493.          the index of
494.         the closest code in the code book.
495. 
496.         Parameters
497.         ----------
498.         X : {array-like, sparse matrix} of shape (n_samples, 
499.          n_features)
500.             New data to predict.
501. 
502.         sample_weight : array-like of shape (n_samples,), 
503.          default=None
504.             The weights for each observation in X. If None, all 
505.              observations
506.             are assigned equal weight.
507. 
508.         Returns
509.         -------
510.         labels : ndarray of shape (n_samples,)
511.             Index of the cluster each sample belongs to.
512.         """
513.         check_is_fitted(self)
514.         X = self._check_test_data(X)
515.         x_squared_norms = row_norms(X, squared=True)
516. return _labels_inertia(X, sample_weight, 
517.          x_squared_norms, self.cluster_centers_, self._n_threads)[0]
518. 
519. def score(self, X, y=None, sample_weight=None):
520. """Opposite of the value of X on the K-means objective.
521. 
522.         Parameters
523.         ----------
524.         X : {array-like, sparse matrix} of shape (n_samples, 
525.          n_features)
526.             New data.
527. 
528.         y : Ignored
529.             Not used, present here for API consistency by 
530.              convention.
531. 
532.         sample_weight : array-like of shape (n_samples,), 
533.          default=None
534.             The weights for each observation in X. If None, all 
535.              observations
536.             are assigned equal weight.
537. 
538.         Returns
539.         -------
540.         score : float
541.             Opposite of the value of X on the K-means objective.
542.         """
543.         check_is_fitted(self)
544.         X = self._check_test_data(X)
545.         x_squared_norms = row_norms(X, squared=True)
546. return -_labels_inertia(X, sample_weight, 
547.          x_squared_norms, self.cluster_centers_)[1]

 


相关文章
|
机器学习/深度学习 算法 数据挖掘
K-means聚类算法是机器学习中常用的一种聚类方法,通过将数据集划分为K个簇来简化数据结构
K-means聚类算法是机器学习中常用的一种聚类方法,通过将数据集划分为K个簇来简化数据结构。本文介绍了K-means算法的基本原理,包括初始化、数据点分配与簇中心更新等步骤,以及如何在Python中实现该算法,最后讨论了其优缺点及应用场景。
2044 6
|
开发框架 算法 .NET
基于ADMM无穷范数检测算法的MIMO通信系统信号检测MATLAB仿真,对比ML,MMSE,ZF以及LAMA
简介:本文介绍基于ADMM的MIMO信号检测算法,结合无穷范数优化与交替方向乘子法,降低计算复杂度并提升检测性能。涵盖MATLAB 2024b实现效果图、核心代码及详细注释,并对比ML、MMSE、ZF、OCD_MMSE与LAMA等算法。重点分析LAMA基于消息传递的低复杂度优势,适用于大规模MIMO系统,为通信系统检测提供理论支持与实践方案。(238字)
|
机器学习/深度学习 算法 数据可视化
利用SVM(支持向量机)分类算法对鸢尾花数据集进行分类
本文介绍了如何使用支持向量机(SVM)算法对鸢尾花数据集进行分类。作者通过Python的sklearn库加载数据,并利用pandas、matplotlib等工具进行数据分析和可视化。
1640 70
|
机器学习/深度学习 数据采集 算法
Python基于KMeans算法进行文本聚类项目实战
Python基于KMeans算法进行文本聚类项目实战
|
数据采集 机器学习/深度学习 算法
Python实现用PSO粒子群优化算法对KMeans聚类模型进行优化项目实战
Python实现用PSO粒子群优化算法对KMeans聚类模型进行优化项目实战
|
算法 数据挖掘 计算机视觉
程序技术好文:聚类算法一(Kmeans、层次类聚、谱类聚)
程序技术好文:聚类算法一(Kmeans、层次类聚、谱类聚)
523 0
|
存储 算法 Java
Java数据结构与算法:用于高效地存储和检索字符串数据集
Java数据结构与算法:用于高效地存储和检索字符串数据集
|
机器学习/深度学习 算法 机器人
【水下图像增强融合算法】基于融合的水下图像与视频增强研究(Matlab代码实现)
【水下图像增强融合算法】基于融合的水下图像与视频增强研究(Matlab代码实现)
1205 0
|
数据采集 分布式计算 并行计算
mRMR算法实现特征选择-MATLAB
mRMR算法实现特征选择-MATLAB
653 2
|
传感器 机器学习/深度学习 编解码
MATLAB|主动噪声和振动控制算法——对较大的次级路径变化具有鲁棒性
MATLAB|主动噪声和振动控制算法——对较大的次级路径变化具有鲁棒性
574 3

热门文章

最新文章