【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
N1, N2 はデータの個数.c1, c2 は平均.sd1, sd2 は標準偏差.
import numpy as np N1 = 10 N2 = 10 c1 = (0, 0) c2 = (3, 5) sd1 = 1 sd2 = 1 a1 = np.zeros((N1, 2)) a1[:,0] = np.random.normal(c1[0], sd1, N1) a1[:,1] = np.random.normal(c1[1], sd1, N1) a2 = np.zeros((N2, 2)) a2[:,0] = np.random.normal(c2[0], sd2, N2) a2[:,1] = np.random.normal(c2[1], sd2, N2) a = np.concatenate([a1, a2]) print(a)
20 個のデータがプロットされている
%matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Suppress Matplotlib warnings plt.style.use('ggplot') plt.plot(a[:,0], a[:,1], 'ro') plt.show()
このデータを使い,クラスタリングを行う. クラスタ数は 3 に設定.
from sklearn.cluster import KMeans c = KMeans(n_clusters = 2).fit_predict(a) print(c)
このデータを使い,クラスタリングを行う.
from sklearn.cluster import MeanShift c = MeanShift().fit_predict(a) print(c)
ここでは,iris をクラスタリングする.
import pandas as pd import seaborn as sns sns.set() iris = sns.load_dataset('iris')
print(iris)
文字列 'setosa','versicolor','virginica' は,1, 2, 3 に置き換え.
a = iris.values a[:,4] = iris['species'].map({'setosa':1, 'versicolor':2, 'virginica': 3}).values print(a)
このデータの 0, 1, 2, 3 行目を使い,クラスタリングを行う. クラスタ数は 3 に設定.
x = a[:,(0, 1, 2, 3)] from sklearn.cluster import KMeans c = KMeans(n_clusters = 3).fit_predict(x) print(c)
このデータの 0, 1, 2, 3 行目を使い,クラスタリングを行う.
x = a[:,(0, 1, 2, 3)] from sklearn.cluster import MeanShift c = MeanShift().fit_predict(x) print(c)