「.NET 開発基盤部会 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。 散布図
機械学習・深層学習の特性上、インタラクティブな環境の方が習得が捗る。
!pip install scikit-learn
!pip install openpyxl
!pip install seaborn
!pip install mlxtend
!pip install mglearn
!pip install nltk -q
!pip install janome
import warnings warnings.filterwarnings('ignore')
import io import requests import pandas as pd import numpy as np import mglearn import matplotlib.pyplot as plt %matplotlib inline
from sklearn.preprocessing import StandardScaler # 標準化 from sklearn.model_selection import train_test_split # データ分割
from sklearn.linear_model import LinearRegression # 線形回帰 from sklearn.preprocessing import PolynomialFeatures # 多項式回帰の変数変換 from sklearn.linear_model import Ridge # 多項式回帰のRidge回帰 from sklearn.linear_model import Lasso # 多項式回帰のLASSO回帰 from sklearn.linear_model import ElasticNet # 多項式回帰のLASSO回帰 from sklearn.linear_model import Perceptron # 単純パーセプトロン線形分類器 from sklearn.linear_model import LogisticRegression # ロジスティク回帰 from sklearn.svm import SVC # サポートベクターマシン(SVM)分類器 from sklearn.tree import DecisionTreeClassifier # 決定木(分類木) from sklearn.ensemble import RandomForestClassifier # ランダムフォレスト(分類木) from sklearn.ensemble import GradientBoostingClassifier # 勾配ブースティング木(分類木) from sklearn.decomposition import PCA # 主成分分析 from sklearn.cluster import KMeans # k-means法 クラスタ分析 from sklearn.feature_extraction.text import CountVectorizer # 自然言語処理ベクトル化 from sklearn.feature_extraction.text import TfidfTransformer # 自然言語ベクトルのTF-IDF計算 from sklearn.decomposition import LatentDirichletAllocation # 自然言語ベクトルからLDAトピック抽出
from sklearn import metrics # モデル評価 from sklearn.metrics import mean_squared_error as mse # 精度評価(mse) from sklearn.metrics import silhouette_samples # シルエット係数 from sklearn.model_selection import cross_val_score # 交差検証法 from sklearn.model_selection import KFold # k分割交差検証法 from sklearn.model_selection import StratifiedKFold # 層化交差検証法 from sklearn.model_selection import GridSearchCV # グリッドサーチ
from sklearn.datasets import make_regression # 回帰データセット from sklearn.datasets import make_blobs # 分類データセット
import seaborn as sns # matplotlibラッパ from mlxtend.plotting import plot_decision_regions # 決定領域表示関数 from matplotlib import cm # カラーマップ処理
from numpy import linalg as LA # 線形代数ライブラリ
(ココはCRISP-DM上に定義なし)
>>>df.describe()
df.corr()
df.drop('行番号列名', axis=1).corr()
>>>sns.pairplot(df) >>>plt.show()
>>>sns.pairplot(df, hue='カテゴリ列') >>>plt.show()
df.isnull().sum() / len(df)
df.dropna()
df.dropna(thresh=列数)
df.dropna(subset=['列名の指定', '列名の指定'])
# 平均 df.fillna(df.mean()) # 中央 df.fillna(df.median()) # 最頻 df.fillna(df.mode().iloc[0])
df.interpolate(method='linear')
df.fillna(定数)・列指定
df.fillna({'列名1':定数1, '列名2':定数2, ..., '列名n':定数n})
df.fillna(method='ffill')・後の値
df.fillna(method='bfill')
df['列名'] = df['列名'].map({'カテゴリ1':数値1, 'カテゴリ2':数値2, ..., 'カテゴリn':数値n})
df['列名'] = df['列名'].map({数値1:'カテゴリ1', 数値2:'カテゴリ2', ..., 数値n:'カテゴリn'})
(ココはCRISP-DM上に定義なし)
x = np.array(df2.loc[:, ['xxx']]) y = np.array(df2.loc[:, ['yyy']])
df_x = df2.loc[:, ['alcohol']] df_y = df2.loc[:, ['quality']] x1 = np.array(df_x) y1 = np.array(df_y)
xy = np.array(df2) x2 = xy[:, 3:4] y2 = xy[:, 4:5]
print(np.allclose(x1, x2)) print(np.allclose(y1, y2))
x = (df.iloc[:, m:n] - df.iloc[:, m:n].mean()) / df.iloc[:, m:n].std() x.describe()
ss = StandardScaler() # 引数は numpy.ndarray x = ss.fit_transform(x) y = ss.fit_transform(y)
# test_size = 0.3 train:test = 7:3 で分割。 # random_state = 0 毎回同じサンプルに分割 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)
# データを切出して、型を変換(DF → NP) x = np.array(df.loc[:, ['列名1']]) y = np.array(df.loc[:, ['列名2']]) # データをスライシングして確認。 x[:5] y[:5]
lr = LinearRegression() lr.fit(x, y)※ fitは多変量に対応しているので二次元配列であること。
new_val = np.array([[説明変数の値]]) pred_val = lr.predict(new_val) print(pred_val)※ predictは多変量に対応しているので二次元配列であること。
# y = lr.coef_[0] * x + lr.intercept_ print('coefficient = ', lr.coef_[0]) # 係数 print('intercept = ', lr.intercept_) # 切片
print('R^2') print('train: %.3f' % lr.score(x_train, y_train)) print('test : %.3f' % lr.score(x_test, y_test))※ 過学習などが起きていないか確認する。
x = np.arange(上限, 下限, 間隔)[:, np.newaxis]※ predictは多変量に対応しているので二次元配列であること。
plt.scatter(x, y, color = 'blue') plt.plot(x, lr.predict(x), color = 'red') plt.grid() plt.show()
# データを切出して、型を変換(DF → NP) x = np.array(df.loc[:, ['列名1', '列名2', ...]]) y = np.array(df.loc[:, ['列名3']]) # データをスライシングして確認。 x[:5] y[:5]
ss = StandardScaler() # 引数は numpy.ndarray x = ss.fit_transform(x) y = ss.fit_transform(y)
x.mean() y.mean()・標準偏差が≒1
x.std() y.std()
# test_size = 0.3 train:test = 7:3 で分割。 # random_state = 0 毎回同じサンプルに分割 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)
x_train.shape y_train.shape x_test.shape y_test.shape
lr = LinearRegression() lr.fit(x_train, y_train)
y_pred = lr.predict(np.array([[i, j]]))
# y = lr.coef_[0] * x1 + lr.coef_[1] * x2 * ... + lr.intercept_ print('coefficient = ', lr.coef_) # 偏回帰係数 print('intercept = ', lr.intercept_) # 定数項
ratio = y_prop / y_pred
print('R^2') print('train: %.3f' % lr.score(x_train, y_train)) print('test : %.3f' % lr.score(x_test, y_test))※ 過学習などが起きていないか確認する。
def adjusted(score, n_sample, n_explanatory_variables): adjusted_score = 1 - (1 - score) * ((n_sample - 1) / (n_sample - n_explanatory_variables - 1)) return adjusted_score計算の実行
print('train: %.3f' % adjusted(lr.score(x_train, y_train), len(y_train), x_train.shape[1])) print('test : %.3f' % adjusted(lr.score(x_test, y_test), len(y_test), x_test.shape[1]))
print('train: %.3f' % (mse(y_train, lr.predict(x_train)) ** (1/2))) print('test : %.3f' % (mse(y_test, lr.predict(x_test)) ** (1/2)))
w0 = lr.intercept_ w1 = lr.coef_[0, 0] w2 = lr.coef_[0, 1] y = w0 + w1*x1 + w2*x2
<元データ>
重回帰分析の改善として、
ボストン住宅価格データセット等を利用すると良い。
<単一変数での実装と比較>
x1_orgのみ使う(y=x^n的なn次関数)。
x_train_lin, x_test_lin, y_train, y_test = train_test_split(x1_org, y_org, test_size = 0.3, random_state = 0)
quad = PolynomialFeatures(degree=2) x1_quad = quad.fit_transform(x1_org) x_train_quad, x_test_quad, y_train, y_test = train_test_split(x1_quad, y_org, test_size = 0.3, random_state = 0)・3次関数
cubic = PolynomialFeatures(degree=3) x1_cubic = cubic.fit_transform(x1_org) x_train_cubic, x_test_cubic, y_train, y_test = train_test_split(x1_cubic, y_org, test_size = 0.3, random_state = 0)
model_lin = LinearRegression() model_lin.fit(x_train_lin, y_train)
model_quad = LinearRegression() model_quad.fit(x_train_quad, y_train)
model_cubic = LinearRegression() model_cubic.fit(x_train_quad, y_train)
# 散布図 plt.scatter(x_org, y_org, color='lightgray', label='data') # 回帰式でプロット x = np.arange(下限, 上限, 間隔)[:, np.newaxis] # 二次元化 x_quad = quad.fit_transform(x) # 注意:2次関数の変数変換の実行を忘れずに。 x_cubic = cubic.fit_transform(x) # 注意:3次関数の変数変換の実行を忘れずに。 plt.plot(x, model_lin.predict(x), color='red', label='linear') # 回帰直線 plt.plot(x, model_quad.predict(x_quad), color='green', label='quad') # 回帰曲線(2次関数 plt.plot(x, model_cubic.predict(x_cubic), color='blue', label='cubic') # 回帰曲線(3次関数 # グラフ表示 plt.xlabel('説明変数') plt.ylabel('目的変数') plt.legend(loc = 'upper right') plt.show()
print('train: %.3f' % adjusted(model_lin.score(x_train_lin, y_train), len(y_train), 1) print('test : %.3f' % adjusted(model_lin.score(x_test_lin, y_test), len(y_test), 1)
print('train: %.3f' % adjusted(model_quad.score(x_train_quad, y_train), len(y_train), 2) print('test : %.3f' % adjusted(model_quad.score(x_test_quad, y_test), len(y_test), 2)
print('train: %.3f' % adjusted(model_cubic.score(x_train_cubic, y_train), len(y_train), 3) print('test : %.3f' % adjusted(model_cubic.score(x_test_cubic, y_test), len(y_test), 3)
<複数変数での実装と比較>
x1のみ多項式で、x2_orgを追加。
x_org = np.hstack((x1_org, x2_org)) x_quad = np.hstack((x1_quad, x2_org)) x_cubic = np.hstack((x_cubic, x2_org))
x_train, x_test, y_train, y_test = train_test_split(x_org, y_org, test_size = 0.3, random_state = 0) x_train_quad, x_test_quad, y_train, y_test = train_test_split(x_quad, y_org, test_size = 0.3, random_state = 0) x_train_cubic, x_test_cubic, y_train, y_test = train_test_split(x_cubic, y_org, test_size = 0.3, random_state = 0)
print('train: %.3f' % adjusted(model_lin.score(x_train_lin, y_train), len(y_train), 2) print('test : %.3f' % adjusted(model_lin.score(x_test_lin, y_test), len(y_test), 2)
print('train: %.3f' % adjusted(model_quad.score(x_train_quad, y_train), len(y_train), 3) print('test : %.3f' % adjusted(model_quad.score(x_test_quad, y_test), len(y_test), 3)
print('train: %.3f' % adjusted(model_cubic.score(x_train_cubic, y_train), len(y_train), 4) print('test : %.3f' % adjusted(model_cubic.score(x_test_cubic, y_test), len(y_test), 4)
<全体を通した評価>
各種法の学習・推論・評価
def function(x): y = 0.0001 * (x**3 + x**2 + x + 1) return y
pol = PolynomialFeatures(degree=7)
x_pol = pol.fit_transform(x) # 変数変換 lr.fit(x_pol, y) # 学習
x_plot_pol = pol.fit_transform(x_plot) # 変数変換 y_plot_pol = lr.predict(x_plot_pol) # 推論
# テストデータ生成に使用した関数 plt.plot(x_plot, y_plot, color='gray') # 多項式回帰の回帰式(7次関数) plt.plot(x_plot, y_plot_pol, color='green')
model_ridge = Ridge(alpha=1000)
model_ridge.fit(x_pol, y)
y_plot_pol_ridge = model_ridge.predict(x_plot_pol)
print('R^2: %.3f' % model_ridge.score(x_pol, y)) print('adjusted R^2: %.3f' % adjusted(model_ridge.score(x_pol, y), len(y), 7))
# テストデータ生成に使用した関数 plt.plot(x_plot, y_plot, color='gray') # 多項式回帰の回帰式(7次関数) plt.plot(x_plot, y_plot_pol, color='green') # Ridge回帰の回帰式(7次関数) plt.plot(x_plot, y_plot_pol_ridge, color='red')
# 重み(正則化なし) lr.coef_ # 重み(Ridge回帰) model_ridge.coef_ # L2ノルム(正則化なし) LA.norm(lr.coef_) # L2ノルム(Ridge回帰) LA.norm(model_ridge.coef_) # L2ノルムの縮小の確認
model_lasso = Lasso(alpha=1000)
model_lasso.fit(x_pol, y)
y_plot_pol_lasso = model_lasso.predict(x_plot_pol)
print('R^2: %.3f' % model_lasso.score(x_pol, y)) print('adjusted R^2: %.3f' % adjusted(model_lasso.score(x_pol, y), len(y), 7))
# テストデータ生成に使用した関数 plt.plot(x_plot, y_plot, color='gray') # 多項式回帰の回帰式(7次関数) plt.plot(x_plot, y_plot_pol, color='green') # LASSO回帰の回帰式(7次関数) plt.plot(x_plot, y_plot_pol_lasso, color='red')
# 重み(正則化なし) lr.coef_ # 重み(LASSO回帰) model_lasso.coef_ # 次元削減の確認 # L1ノルム(正則化なし) LA.norm(lr.coef_, ord=1) # L1ノルム(LASSO回帰) LA.norm(model_lasso.coef_, ord=1) # L1ノルムの縮小の確認
model_en= ElasticNet(alpha=1000, l1_ratio=0.9)
model_en.fit(x_pol, y)
y_plot_pol_en = model_en.predict(x_plot_pol)
print('R^2: %.3f' % model_en.score(x_pol, y)) print('adjusted R^2: %.3f' % adjusted(model_en.score(x_pol, y), len(y), 7))
# テストデータ生成に使用した関数 plt.plot(x_plot, y_plot, color='gray') # 多項式回帰の回帰式(7次関数) plt.plot(x_plot, y_plot_pol, color='green') # ElasticNetの回帰式(7次関数) plt.plot(x_plot, y_plot_pol_en, color='red')
# 重み(正則化なし) lr.coef_ # 重み(ElasticNet) model_en.coef_ # 次元削減の確認 # L2ノルム(正則化なし) LA.norm(lr.coef_) # L2ノルム(ElasticNet) LA.norm(model_en.coef_) # L2ノルムの縮小の確認 # L1ノルム(正則化なし) LA.norm(lr.coef_, ord=1) # L1ノルム(ElasticNet) LA.norm(model_en.coef_, ord=1) # L1ノルムの縮小の確認
df = pd.read_csv('work/iris.csv')
df.describe() sns.pairplot(df, hue='Species') plt.show()
np_arr=np.array(df) # PetalLengthCm, PetalWidthCm列の選択 x=np_arr[:100, 3:5] # 100→150で3値分類 # Species列の選択 y=np_arr[:100, 5:6] # 100→150で3値分類
y[y=='Iris-setosa']=0 y[y=='Iris-versicolor']=1 # y[y=='Iris-virginica']=2 y=np.array(y,dtype='int64')
ss = StandardScaler() ss.fit(x) x_std = ss.transform(x)
plt.scatter(x_std[:50, 0], x_std[:50,1], color="red", marker="s", label="setosa") plt.scatter(x_std[50:100, 0], x_std[50:100,1], color="blue", marker="x", label="versicolor") #plt.scatter(x_std[100:150, 0], x_std[100:150,1], color="yellow", marker="o", label="virginica") plt.xlabel("PetalLengthCm") plt.ylabel("PetalWidthCm") plt.legend(loc="upper left") plt.show()
x_train, x_test, y_train, y_test = train_test_split(x_std, y, test_size=0.3, random_state=0)
ppn = Perceptron(eta0=0.1) # 学習率 0.1 ppn.fit(x_train, y_train)
index = 10 print('answer : %d' % y_test[index][0]) print('predict: %d' % ppn.predict([x_test[index]])[0])
print('train acc: %.3f' % ppn.score(x_train, y_train)) print('test acc: %.3f' % ppn.score(x_test, y_test))
cm_ppn = confusion_matrix(y, ppn.predict(x_std)) print(cm_ppn) cm_ppn = confusion_matrix(y_train, ppn.predict(x_train)) print(cm_ppn) cm_ppn = confusion_matrix(y_test, ppn.predict(x_test)) print(cm_ppn)
print_metrics(y, ppn.predict(x_std)) print_metrics(y_train, ppn.predict(x_train)) print_metrics(y_test, ppn.predict(x_test))
plot_decision_regions(x_std, y.flatten(), ppn) plt.xlabel("PetalLengthCm") plt.ylabel("PetalWidthCm") plt.legend(loc="upper left") plt.title('Iris') plt.show()
svc = SVC(kernel='linear') svc.fit(x_train, y_train)
svc = SVC(kernel='linear', C=1.0) svc.fit(x_train, y_train)
svc = SVC(kernel='rbf', gamma=0.1, C=10) svc.fit(x_train, y_train)
ppn → svc に変更して実行
ppn → svc に変更して実行
※ カーネル法で以下のテストデータを使うと、
決定境界の非線形性が顕著に可視化される。# XORのデータの作成 np.random.seed(0) X_xor = np.random.randn(200, 2) y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0) y_xor = np.where(y_xor, 1, -1) # データの散布 plt.scatter(X_xor[y_xor == 1, 0], X_xor[y_xor == 1, 1], c='b', marker='x', label='1') plt.scatter(X_xor[y_xor == -1, 0], X_xor[y_xor == -1, 1], c='r', marker='s', label='-1') plt.xlim([-3, 3]) plt.ylim([-3, 3]) plt.legend(loc='best') # 右上に凡例を出力 plt.show()
tree = DecisionTreeClassifier(random_state=0) tree.fit(x_train, y_train)
tree = DecisionTreeClassifier(random_state=0, max_depth=3) tree.fit(x_train, y_train)
tree = RandomForestClassifier(random_state=0, n_estimators=10) tree.fit(x_train, y_train)
tree = GradientBoostingClassifier(random_state=0, max_depth=3, learning_rate=0.1) tree.fit(x_train, y_train)
tree.predict_proba(x_test[11].reshape(1, -1))・以下の出力は、0は0%, 1は100%, 2は0%の意。
array([[0., 1., 0.]])
※ 各特徴量の重要度を出力
(ランダムフォレストの方が信頼性の高い)
tree = RandomForestClassifier(random_state=0, n_estimators=100)
print(tree.feature_importances_)
x_columns = len(df_x.columns) plt.figure(figsize=(12, 8)) plt.barh(range(x_columns), tree.feature_importances_ , align='center') plt.yticks(np.arange(x_columns), df_x.columns) plt.show()
df_pickup = df.loc[:, ['perimeter_worst', 'concave points_worst', 'radius_worst', 'concave points_mean', 'diagnosis']] sns.pairplot(df_pickup, hue='diagnosis') plt.show()・選択
x = df.loc[:, ['perimeter_worst', 'concave points_mean']].values y = df.loc[:, ['diagnosis']].values・変換
y[y=='M']=0 y[y=='B']=1 y=np.array(y,dtype='int64')
ss = StandardScaler() ss.fit(x) x_std = ss.transform(x)
x_train, x_test, y_train, y_test = train_test_split(x_std, y, test_size=0.3, random_state=0)
lr = LogisticRegression(C=1.0) lr.fit(x_train, y_train)
index = 10 print('answer : %d' % y_test[index][0]) print('predict: %d' % lr.predict([x_test[index]])[0])
lr.predict_proba([x_test[index]])[0]
print('train acc: %.3f' % lr.score(x_train, y_train)) print('test acc: %.3f' % lr.score(x_test, y_test))
cm_lr = confusion_matrix(y, lr.predict(x_std)) print(cm_lr) cm_lr = confusion_matrix(y_train, lr.predict(x_train)) print(cm_lr) cm_lr = confusion_matrix(y_test, lr.predict(x_test)) print(cm_lr)
print_metrics(y, lr.predict(x_std)) print_metrics(y_train, lr.predict(x_train)) print_metrics(y_test, lr.predict(x_test))
plot_decision_regions(x_std, y.flatten(), lr) plt.xlabel("perimeter_worst") plt.ylabel("concave points_mean") plt.legend(loc="upper left") plt.title('cancer') plt.show()
pca = PCA(n_components=4) # 主成分を4つまで取得 x_pca = pca.fit_transform(x_std)
plt.figure() for target, marker, color in zip(range(3), '>ox', 'rgb'): # 3値分類 # y==targetで、boolのnumpy.ndarrayベクトルが返るのでコレで行を指定している。 plt.scatter(x_pca[y==target, 0], x_pca[y==target, 1], marker=marker, color=color) plt.xlabel('第1主成分') plt.ylabel('第2主成分') plt.show()
pca.explained_variance_ratio_
pca.explained_variance_ratio_
pca.components_ * np.sqrt(pca.explained_variance_)[:, np.newaxis]※ 出力の行列はn行が第n+1主成分の因子負荷量を表し、
km = KMeans(n_clusters=3, # クラスタの個数を指定 init='random', # 重心の初期値の決め方を決定 n_init=10, # 異なる重心の初期値を用いての実行回数 max_iter=300, # ひとつの重心を用いたときの最大イテレーション回数 tol=1e-04, # 収束と判定するための相対的な許容誤差 random_state=0, # 重心の初期化に用いる乱数生成器の状態 ) y_km = km.fit_predict(x_pca[:, 0:2]) # PC1, 2のみ使用
def kmeans_plot(n_clusters, km, x): # クラスタの予測値を算出 y_km = km.fit_predict(x) # クラスタ毎に散布(ZIP的に5クラスまで、要素を増やせば対応可能 for i, color, marker in zip(range(n_clusters), 'rgbcm', '>o+xv'): plt.scatter(x[y_km==i, 0], # 横軸の値 x[y_km==i, 1], # 縦軸の値 color=color, # プロットの色 marker=marker, # プロットの形 label='cluster ' + str(i) # ラベル ) # クラスタの中心を散布 plt.scatter(km.cluster_centers_[:, 0], # 横軸の値 km.cluster_centers_[:, 1], # 縦軸の値 color='y', # プロットの色 marker='*', # プロットの形 label='centroids', # ラベル s=300, # プロットのサイズを大き目に ) plt.legend() plt.grid() plt.show()
kmeans_plot(3, km, x_pca[:, 0:2]) # PC1, 2のみ使用
def kmeans_score(y_km, y): y=y.flatten() correct_ans = 0 for i in range(len(y)): if y_km[i] == y[i]: correct_ans += 1 return correct_ans / len(y)
# ひっくり返ったラベルを戻す y_km[y_km==2]=3 y_km[y_km==1]=2 y_km[y_km==3]=1 # スコアの表示 kmeans_score(y_km, y)
# クラスタ数とSSE distortions = [] for k in range(1,11): # 1~10クラスタ km = KMeans(n_clusters=k, # クラスタ数 init='random', # 重心の初期値の決め方を決定 n_init=10, # 重心の初期値を変えての繰り返し回数 max_iter=300, # 一回の最適化の繰り返し回数を指定 random_state=0) # 乱数の生成状態を指定 km.fit(x_pca[:, 0:2]) # クラスタリングを実行 distortions.append(km.inertia_) # SSEをリストに格納 # 良く解らんが、distortion = cluster inertia = SSEらしい。 # 結果をグラフに出力 plt.plot(range(1,11), distortions,marker='o') plt.xlabel('Number of clusters') plt.ylabel('Distortion') plt.show()※ 肘の部分は 2 or 3 となり、結構曖昧ではある。
# シルエット係数の計算 silhouettes = silhouette_samples(x_pca[:, 0:2], y_km, metric='euclidean') # シルエット係数の表示 cluster_labels = np.unique(y_km) n_clusters = cluster_labels.shape[0] yticks = [] y_ax_lower, y_ax_upper = 0, 0 for i, cluster_label in enumerate(cluster_labels): # 当該クラスタの係数を取り出す cluster_silhouettes = silhouettes[y_km==cluster_label] # 描画の上端の値を設定 y_ax_upper += len(cluster_silhouettes) # 描画時の色の値をセット color = cm.jet(float(i) / n_clusters) # クラスタを横棒グラフで描画 cluster_silhouettes.sort() plt.barh(range(y_ax_lower, y_ax_upper), cluster_silhouettes, height=1.0, edgecolor='none', color=color) # クラスタのラベル位置を指定 yticks.append((y_ax_lower + y_ax_upper) / 2.) # 次の描画のスタート位置 y_ax_lower += len(cluster_silhouettes) plt.axvline(np.mean(silhouettes), color='red', linestyle='--') plt.yticks(yticks, cluster_labels + 1) plt.ylabel('Cluster') plt.xlabel('Silhoutte coefficient') plt.tight_layout() plt.show()
<ロジスティック回帰分類機を使った感情分析>
レビューを入力として肯定的・否定的を判別する教師あり学習を行う。
import re
import nltk from nltk.corpus import stopwords nltk.download("stopwords")
def remove_html_tag(text): pattern = re.compile(r"<[^>]*>") removed = re.sub(pattern, " ", text) return removed def remove_punct(text): pattern = re.compile(r"(?::|;|=)(?:-)?(?:\)|\(|D|P)") emoticons = pattern.findall(text) lower = text.lower() removed = re.sub(r"[\W]+", " ", lower) emoticons = " ".join(emoticons) emoticons = emoticons.replace("-","") connected = removed + ' ' + emoticons return connected def porter_stem(text): stemmer = nltk.PorterStemmer() words = [] for word in text.split(' '): try: words.append(stemmer.stem(word)) except: stem_ls.append(word) return " ".join(words) def strip_stop(text): words = [] stop = stopwords.words("english") for word in text.split(' '): if word not in stop: words.append(word) return " ".join(words)
df["review"] = df["review"].apply(remove_html_tag) df["review"] = df["review"].apply(remove_punct) df["review"] = df["review"].apply(porter_stem) df["review"] = df["review"].apply(strip_stop)
cv = CountVectorizer(max_df=0.3, min_df=5, stop_words='english') cv.fit(df['review']) feature_names = cv.get_feature_names() bow = cv.transform(df['review']).toarray()
x_train, x_test, y_train, y_test = train_test_split(bow, df["sentiment"], test_size=0.3, random_state=0)
lr = LogisticRegression() lr.fit(x_train, y_train)
y_pred_train = lr.predict(x_train)
print_metrics(y_train, lr.predict(x_train))
print_metrics(y_test, lr.predict(x_test))
tfidf = TfidfTransformer(sublinear_tf=True) x_train_tfidf = tfidf.fit_transform(x_train.astype('f')).toarray() x_test_tfidf = tfidf.fit_transform(x_test.astype('f')).toarray()
lr_tfidf = LogisticRegression() lr_tfidf.fit(x_train_tfidf, y_train)
print_metrics(y_train, lr_tfidf.predict(x_train_tfidf)) print_metrics(y_test, lr_tfidf.predict(x_test_tfidf))・重要度の高い単語を確認する。
mglearn.tools.visualize_coefficients(lr.coef_, feature_names, n_top_features=30) mglearn.tools.visualize_coefficients(lr_tfidf.coef_, feature_names, n_top_features=30)
<LDAトピックモデル(文書のクラスタリング)>
話題分析、リコメンド、類似文章検索、機械翻訳などで利用できる。
lda = LatentDirichletAllocation(n_components=5, learning_method='batch', random_state=0) document_topics = lda.fit_transform(x_train_tfidf)
document_topics
lda.components_
mglearn.tools.print_topics( topics=range(5), feature_names=np.array(feature_names), sorting=np.argsort(lda.components_, axis=1)[:, ::-1], topics_per_chunk=5, n_words=5)
lda2 = LatentDirichletAllocation(n_components=25, learning_method='batch', random_state=0) x_train_lda = lda2.fit_transform(x_train_tfidf) x_test_lda = lda2.fit_transform(x_test_tfidf)
lr_lda = LogisticRegression() lr_lda.fit(x_train_lda, y_train) print_metrics(y_train, lr_lda.predict(x_train_lda)) print_metrics(y_test, lr_lda.predict(x_test_lda))
iris = datasets.load_iris() df_data = pd.DataFrame(iris.data, columns=iris.feature_names) df_target = pd.DataFrame(iris.target, columns=['species']) df = pd.concat([df_data, df_target], axis=1) np_arr=np.array(df) # データの標準化 ss = StandardScaler()
def print_metrics(label, pred): print('accuracy: %.3f' % metrics.accuracy_score(label, pred)) # 正答率 print('\nmicro') # ミクロ平均 print('recall: %.3f' % metrics.recall_score(label, pred, average='micro')) # 再現率 print('precision: %.3f' % metrics.precision_score(label, pred, average='micro')) # 適合率 print('f1_score: %.3f' % metrics.f1_score(label, pred, average='micro')) # f値 print('\nmacro') # マクロ平均 print('recall: %.3f' % metrics.recall_score(label, pred, average='macro')) # 再現率 print('precision: %.3f' % metrics.precision_score(label, pred, average='macro')) # 適合率 print('f1_score: %.3f' % metrics.f1_score(label, pred, average='macro')) # f値
x2=np_arr[50:150, 2:4] y2=np.array(np_arr[50:150, 4:5],dtype=np.int64) # 要素の型をint64に変換 ss.fit(x2) x2_std = ss.transform(x2) x2_train, x2_test, y2_train, y2_test = train_test_split(x2_std, y2, test_size=0.3, random_state=0) print(x3.shape)
svc2 = SVC(kernel='rbf', gamma=0.1, C=10) svc2.fit(x2_train, np.reshape(y2_train,(-1)))
cm_svc2 = confusion_matrix(y2_test, svc2.predict(x2_test)) print(cm_svc2.dtype) print(cm_svc2)
print_metrics(y2_test, svc2.predict(x2_test))
x3=np_arr[:, 2:4] y3=np.array(np_arr[:, 4:5],dtype=np.int64) # 要素の型をint64に変換 ss.fit(x3) x3_std = ss.transform(x3) x3_train, x3_test, y3_train, y3_test = train_test_split(x3_std, y3, test_size=0.3, random_state=0) print(x3.shape)
svc3 = SVC(kernel='rbf', gamma=0.1, C=10) svc3.fit(x3_train, np.reshape(y3_train,(-1)))
cm_svc3 = confusion_matrix(y3_test, svc3.predict(x3_test)) print(cm_svc3.dtype) print(cm_svc3)
print_metrics(y3_test, svc3.predict(x3_test))
kf = KFold(n_splits=5, shuffle=True, random_state=0) scores = cross_val_score(lr, x, y, cv=kf) scores scores.mean() # 交差検証精度の平均 scores.std() # 交差検証精度の標準偏差
kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=0) scores = cross_val_score(svc, x, y, cv=kf) scores scores.mean() # 交差検証精度の平均 scores.std() # 交差検証精度の標準偏差
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)
param_grid = { 'C': [0.1, 1.0, 10, 100, 1000, 10000], 'gamma': [0.001, 0.01, 0.1, 1, 10]}
kf = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
gs_svc = GridSearchCV(SVC(), param_grid, cv=kf)
gs_svc.fit(x_train, y_train)
# 精度が最も高かった組み合わせ gs_svc.best_params_ # その際のスコア gs_svc.best_score_ # データセットの正答率 gs_svc.score(x_test, y_test)
plot_decision_regions(x_std, y.flatten(), gs_svc) ...
ハイパーパラメタ・チューニング
特徴量を使用して精度を比較する。
scores_std = cross_val_score(SVC(), x_std[:, [0, 2]], y, cv=5) print('特徴選択: {}'.format(scores_std.mean()))
scores_pca = cross_val_score(SVC(), x_pca[:, 0:2], y, cv=5) print('特徴抽出: {}'.format(scores_pca.mean()))
※ このケースは低次元なので、特徴選択した x_std の方が精度が良い。
x, y, coef = make_regression(random_state=12, n_samples=100, # サンプル数 100 n_features=4, # 特徴量の数 4 n_informative=2, # 目的変数に相関の強い特徴量の数 2 noise=10.0, # ノイズ 10.0 bias=-0.0, coef=True)
df_x=pd.DataFrame(X,columns=['a','b','c','d']) df_y=pd.DataFrame(y,columns=['y']) df=pd.concat([df_x, df_y],axis=1) sns.pairplot(df) plt.show()
x, y = make_blobs(random_state=8, n_samples=100, # サンプル数 100 n_features=2, # 特徴量の数を 2 cluster_std=1.5, # 標準偏差 centers=3) # 塊数を3
def cluster_plot(n_clusters, x, y): plt.figure() for target, marker, color in zip(range(3), '>ox', 'rgb'): # 3値分類 # y==targetで、boolのnumpy.ndarrayベクトルが返るのでコレで行を指定している。 plt.scatter(x[y==target, 0], x[y==target, 1], marker=marker, color=color) plt.xlabel('x1') plt.ylabel('x2') plt.show()
cluster_plot(3, x, y)
def function(x): y = なんとか x return y
# xの範囲を指定 x_plot = np.arange(-25, 25, 0.1) # yを関数で指定 y_plot = function(x_plot) # 機械学習用に変換 x_plot = x_plot.reshape(-1, 1)
# 乱数生成器の状態を指定 np.random.seed(3) # 正規分布に従ってX個のデータ点を生成 x = np.random.normal(0, 10, X) # 対応するyを関数で生成 y = function(x) # 正規分布に従うノイズを加える y += np.random.normal(0, 0.25, len(y)) # 機械学習用に変換 x = x.reshape(-1, 1)
# 関数を描画 plt.plot(x_plot, y_plot, color='gray') # サンプルを散布 plt.scatter(x, y) # グラフを表示 plt.show()