------------- 16-2.txt ------------------------------------ P387
●手書き数字データセットを読み込む
from sklearn import datasetsdigits = datasets.load_digits()
●データセットに納められているものを調べる
xxxxxxxxxxdir(digits)
P388
●digitsデータセットの説明文を読む
xxxxxxxxxxprint(digits.DESCR)
●データの構造を調べる
xxxxxxxxxxdigits.data.shape
xxxxxxxxxxdigits.target.shape
P389
●数字の画像データを確かめる
xxxxxxxxxxdigits.data
●正解の数値が入ったターゲットデータを確かめる
xxxxxxxxxxdigits.target
●1文字目の画像データ
xxxxxxxxxxdigits.data[0]
P390
●1文字目の画像データを8行8列で見てみる
xxxxxxxxxxdigits.images[0] # 1文字目の画像データ
●画像データから手書き文字を復元する
xxxxxxxxxximport matplotlib.pyplot as pltplt.matshow(digits.images[0], cmap="Greys")plt.show()
●ターゲットデータで正解を調べてみる
xxxxxxxxxxdigits.target[0]
P391
●訓練データとテストデータを用意する
xn_train = len(digits.data)*2//3 # データの2/3の個数X_train = digits.data[:n_train] # dataの前半 2/3y_train = digits.target[:n_train] # targetの前半 2/3X_test = digits.data[n_train:] # dataの後半 1/3y_test = digits.target[n_train:] # targetの後半 1/3
P392
●構造を確認する
xprint([d.shape for d in [X_train, y_train, X_test, y_test]])
●学習器SVMで学習を行う
xfrom sklearn import svm # svmをインポートするclf = svm.SVC(gamma=0.001) # 学習器clf.fit(X_train, y_train) # 訓練データと教師データで学習する
●テストデータで正答率を調べる
xprint(clf.score(X_test, y_test))
P393
●学習済みモデルが誤って分類した個数を調べる
xpredicted = clf.predict(X_test)(y_test != predicted).sum()
●学習結果の評価レポート
xfrom sklearn import metricsprint(metrics.classification_report(y_test, predicted))
P394
●数字ごとに正解数と読み間違えた数字を調べる
xprint(metrics.confusion_matrix(y_test, predicted))
●画像イメージと分類結果(404~415の12文字を表示)
ximport matplotlib.pyplot as pltimgs_yt_preds = list(zip(digits.images[n_train:], y_test, predicted))for index, (image, y_t, pred) in enumerate(imgs_yt_preds[404:416]):plt.subplot(3,4,index+1) # 3X4で表示するplt.axis('off')plt.tight_layout()plt.imshow(image,cmap="Greys",interpolation="nearest")plt.title(f'{y_t} pre:{pred}',fontsize=12)plt.show
p395 完成したコード
● 手書き数字データを機械学習で分類する
xxxxxxxxxxfrom sklearn import datasetsfrom sklearn import svm, metricsimport matplotlib.pyplot as plt# 手書き数字データセットを読み込むdigits = datasets.load_digits()X = digits.data # 手書き数字データy = digits.target # ターゲットn_train = len(X)*2//3 # データの2/3の個数# 訓練データX_train, y_train = X[:n_train], y[:n_train] # 前半 2/3# テストデータX_test, y_test = X[n_train:], y[n_train:] # 後半 1/3# 学習器の作成と学習clf = svm.SVC(gamma=0.001) # 学習器clf.fit(X_train, y_train) # 訓練データと教師データで学習する# モデルの学習結果を評価するaccuracy = clf.score(X_test, y_test) # テストデータで試すprint(f"正答率{accuracy}")predicted = clf.predict(X_test) # テストデータの分類結果n_error = (y_test != predicted).sum() # 正解と分類結果を比較するprint(f"誤った個数:{n_error}")# 詳しいレポートprint("classification report")print(metrics.classification_report(y_test, predicted))print("confusion matrix")print(metrics.confusion_matrix(y_test, predicted))# 画像イメージと分類結果(404~415の12文字を表示)imgs_yt_preds = list(zip(digits.images[n_train:], y_test, predicted))for index, (image, y_t, pred) in enumerate(imgs_yt_preds[404:416]):plt.subplot(3, 4, index + 1) # 3×4で表示するplt.axis('off')plt.tight_layout()plt.imshow(image, cmap="Greys", interpolation="nearest")plt.title(f't:{y_t} pre:{pred}', fontsize=12) # 正解と分類結果plt.show()
P396
[MEMO]SVCのパラメータを確認する
xfrom sklearn import svmclf = svm.SVC(gamma=0.001)clf
--------------- 16-3.txt ---------------------------------
P397
●アヤメのデータセットを読み込む
xfrom sklearn import datasetsiris = datasets.load_iris()
●irisデータセットに納められているものを調べる
xdir(iris)
●irisデータセットの説明文を読む print(iris.DESCR)
P398
●データの構造を調べる
xxxxxxxxxxX = iris.data # 計測データy = iris.target # ターゲットデータX.shape
xy.shape
●訓練とテストに使う計測データ
xX
P399
●学習データの属性
xiris.feature_names
●教師データ(ターゲット)
xprint(y)
●がく片の長さと幅の値で3種類のアヤメをプロットする
ximport matplotlib.pyplot as plt###### setosa:0~49、versicolor:50~99、virginica:100~149plt.scatter(X[:50, 0], X[:50, 1], color='r', marker='o', label='setosa')plt.scatter(X[50:100, 0], X[50:100, 1], color='g', marker='+', label='versicolor')plt.scatter(X[100:, 0], X[100:, 1],color='b', marker='x', label='virginica')plt.title("Iris Plants Database")plt.xlabel('sepal length(cm)')plt.ylabel('sepal width(cm)')plt.legend()plt.show()
P400
●3種類のアヤメをプロットするコード
xfor i, cl, mk, lb in zip([0,1,2], 'rgb', 'o+x', iris.target_names):plt.scatter(X[y==i][:,0], X[y==i][:,1], color=cl, marker=mk, label=lb)
●モデルclfを作って訓練データで学習する
xxxxxxxxxxfrom sklearn import datasetsfrom sklearn import svmiris = datasets.load_iris() # アヤメのデータセットを読み込むX = iris.data # データy = iris.target # ターゲットn_train = len(X)//2 # データの半分の個数X_train, X_test = X[:n_train], X[n_train:] # 訓練データy_train, y_test = y[:n_train], y[n_train:] # 教師データclf = svm.SVC() # モデルを作るclf.fit(X_train, y_train) # 学習する
●テストデータで評価する
xprint(clf.score(X_test, y_test))
●データの前半分を訓練データにする
xxxxxxxxxxn_train = len(X)//2 # データの半分の個数X_train, X_test = X[:n_train], X[n_train:] # 訓練データ
P402
●分割比率を設定したShuffleSplitクラスのインスタンスを作る
xfrom sklearn.model_selection import ShuffleSplitss = ShuffleSplit(train_size=0.6, test_size=0.4, random_state=0)
●訓練データとテストデータのインデックスを作り分割する
train_index, test_index = next(ss.split(X)) # 分割するインデックス番号X_train, y_train = X[train_index], y[train_index] # 訓練データX_test, y_test = X[test_index], y[test_index] # テストデータ
●変数の学習器を作って訓練する
xclf = svm.SVC() # 学習器を作るclf.fit(X_train, y_train) # 訓練するprint(clf.score(X_test, y_test)) # 正答率を調べる
P403
完成したコード ● shuffleSplitを使って学習データを分割する
xfrom sklearn import datasetsfrom sklearn import svmfrom sklearn.model_selection import ShuffleSplit# アヤメのデータセットを読み込むiris = datasets.load_iris()X = iris.datay = iris.target# データを分割するインデックスを作るiris_ss = ShuffleSplit(train_size=0.6, test_size=0.4, random_state=0)train_index, test_index = next(iris_ss.split(X))# データを分割するX_train, y_train = X[train_index], y[train_index] # 訓練データX_test, y_test = X[test_index], y[test_index] # テストデータclf = svm.SVC() # モデルを作るclf.fit(X_train, y_train) # 訓練するprint(clf.score(X_test, y_test)) # 正答率を調べる
●学習器をLogisticRegressionに取り替えて試してみる
xfrom sklearn import linear_modelclf = linear_model.LogisticRegression()clf.fit(X_train, y_train)print(clf.score(X_test, y_test))
---------------------- 16.4.txt --------------------- P404
●ボストンの住宅価格のデータセットを読み込む
xfrom sklearn import datasetsboston = datasets.load_boston()
●データセットに納められているものを調べる
xdir(boston)
●bostonデータセットの説明文を読む
xprint(boston.DESCR)
P406
●データセットをDataFrame型に変換し出力する
xfrom pandas import DataFrameboston_df = DataFrame(boston.data) # DataFrame型にするboston_df.columns = boston.feature_names # 列名を設定するboston_df["Price"] = boston.target # 住宅価格を追加するprint(boston_df[:5]) # 最初の5行だけ
P407
●回帰モデルを作って部屋数と価格の訓練データで訓練する
xrooms_train = DataFrame(boston_df["RM"]) # 部屋数のデータを抜き出すy_train = boston.target # ターゲット(住宅価格)model = linear_model.LinearRegression() # 回帰モデルを作るmodel.fit(rooms_train, y_train) # 訓練する
●予想価格をモデルを使って計算する
xxxxxxxxxx#部屋数のテストデータを作るimport numpy as nprooms_test = DataFrame(np.arange(rooms_train.values.min(), rooms_train.values.max(), 0.1))prices_test = model.predict(rooms_test) # モデルを使って住宅価格を予想する
●実際のデータと回帰直線をグラフ表示する
xxxxxxxxxxplt.scatter(rooms_train, y_train, c= "b", alpha = 0.5) # 訓練データplt.plot(rooms_test, prices_test, c = "r", marker ="x") # 回帰直線plt.title("Boston House Prices dataset")plt.xlabel("rooms") # x軸のラベルplt.ylabel("price $1000's") # y軸のラベルplt.show()
p408
完成したコード
● 部屋数から住宅価格を予想する回帰分析を行う
xfrom sklearn import datasetsfrom sklearn import linear_modelimport numpy as npimport matplotlib.pyplot as pltfrom pandas import DataFrame# データセットを読み込むboston = datasets.load_boston() # ボストン市の住宅価格と関連データboston_df = DataFrame(boston.data) # DataFrame型にするboston_df.columns = boston.feature_names # 列名を設定するboston_df["Price"] = boston.target # 住宅価格を追加するprint(boston_df[:10]) # 最初の10行だけ# 訓練データを作るrooms_train = DataFrame(boston_df["RM"]) # 部屋数のデータを抜き出すy_train = boston.target # ターゲット(住宅価格)model = linear_model.LinearRegression() # 回帰モデルを作るmodel.fit(rooms_train, y_train) # 訓練する# 部屋数のテストデータを作るrooms_test = DataFrame(np.arange(rooms_train.values.min(), rooms_train.values.max(), 0.1))prices_test = model.predict(rooms_test) # モデルを使って住宅価格を予想する# グラフ表示する(部屋数と住宅価格)plt.scatter(rooms_train.values.ravel(), y_train, c= "b", alpha = 0.5) # 訓練データplt.plot(rooms_test.values.ravel(), prices_test, c = "r") # 回帰直線plt.title("Boston House Prices dataset")plt.xlabel("rooms") # x軸のラベルplt.ylabel("price $1000's") # y軸のラベルplt.show()
p409
● seabornモジュールを使って散布図と回帰直線を引く
xxxxxxxxxxfrom sklearn import datasetsfrom pandas import DataFrameimport matplotlib.pyplot as pltimport seaborn as sns# データセットを読み込むboston = datasets.load_boston()boston_df = DataFrame(boston.data)boston_df.columns = boston.feature_names # 列名を設定するboston_df["Price"] = boston.target # 住宅価格を追加する# 部屋数と住宅価格から回帰直線を引くsns.set_style('whitegrid')sns.lmplot(x = "RM", y = "Price", data = boston_df)plt.show()