SlideShare a Scribd company logo
import numpy as np
from sklearn import datasets, model_selection
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import accuracy_score
def print_vec(text, vec):
print("*** " + text + " ***")
print(vec)
#print("shape: " + str(x.shape))
print("")
# データセットのロード
# iris.data = [(がく片の長さ , がく片の幅 , 花びらの長さ , 花びらの幅)]
iris = datasets.load_iris()
print_vec("データセットの形状",iris.data.shape)
print_vec("花の種類",iris.target_names)
#説明変数と目的変数に分割
x_vals, y_vals = iris.data, iris.target
# ダミー変数を追加
x_all = np.insert(x_vals, 0, 1.0, axis=1)
print_vec("ダミー変数追加",x_all)
# 目的変数を one hot ベクトル化
ohe = OneHotEncoder(sparse=False,categories='auto')
y_ohe = np.c_[y_vals]
y_vals_ohe = ohe.fit_transform(y_ohe)
print_vec("目的変数", y_vals_ohe)
#テストデータと検証データに分割(8:2)
x_train, x_test, y_train, y_test,y_train_ohe, y_test_ohe =
model_selection.train_test_split(x_all, y_vals, y_vals_ohe,test_size=0.2)
print_vec("x_train",x_train)
print_vec("y_train",y_train)
print_vec("x_test",x_test)
print_vec("y_test",y_test)
print_vec("y_train_ohe",y_train_ohe)
print_vec("y_test_ohe",y_test_ohe)
## 出力層の活性化関数
# ソフトマックス関数
def softmax(x):
if x.ndim == 2:
x = x.T
x = x - np.max(x, axis=0)
y = np.exp(x) / np.sum(np.exp(x), axis=0)
return y.T
x = x - np.max(x) # オーバーフロー対策
return np.exp(x) / np.sum(np.exp(x))
# クロスエントロピー
def cross_entropy(yt, yp):
return -np.mean(np.sum(yt * np.log(yp), axis=1))
# # ソフトマックスとクロスエントロピーの複合関数
# def softmax_with_loss(d, x):
# y = softmax(x)
# return cross_entropy_error(d, y)
# 予測値の計算を行う関数
def pred(x, W):
return softmax(x @ W)
# モデル評価関数
def evaluate(x_test, y_test, y_test_ohe, W):
# 予測値の計算(確率値)
yp_test_ohe = pred(x_test, W)
# 確率値から予測クラス(0, 1, 2)を導出
yp_test = np.argmax(yp_test_ohe, axis=1)
# 損失関数値の計算
loss = cross_entropy(y_test_ohe, yp_test_ohe)
# 精度の算出
score = accuracy_score(y_test, yp_test)
return loss, score
# 初期化処理
# 学習対象の選択
x, yt = x_train, y_train_ohe
# 標本数
M = x.shape[0]
# 入力次元数
D = x.shape[1]
# 分類先クラス数
N = yt.shape[1]
# 繰り返し回数
iters = 10000
# 学習率
alpha = 0.01
# 重み行列の初期設定(すべて 1)
W = np.ones((D, N))
# 評価結果記録用
history = np.zeros((0, 3))
# メイン処理
for k in range(iters):
# 予測値の計算
yp = pred(x, W)
# 誤差の計算
yd = yp - yt
# 重みの更新
W = W - alpha * (x.T @ yd) / M
if (k % 10 == 0):
loss, score = evaluate(x_test, y_test, y_test_ohe, W)
history = np.vstack((history,
np.array([k, loss, score])))
print("epoch = %d loss = %f score = %f"
% (k, loss, score))
#損失関数値と精度の確認
print('初期状態: 損失関数:%f 精度:%f'
% (history[0,1], history[0,2]))
print('最終状態: 損失関数:%f 精度:%f'
% (history[-1,1], history[-1,2]))

More Related Content

PDF
XOOPS Cube Conference 2012 Developer Workshop 3
PPTX
機械学習
ODP
第三回R勉強会
ODP
第2回R勉強会1
PPTX
HTMLの要素の選び方
PDF
Boost.B-tree introduction
PPTX
[機械学習]文章のクラス分類
PDF
D3.jsによるDOM操作
XOOPS Cube Conference 2012 Developer Workshop 3
機械学習
第三回R勉強会
第2回R勉強会1
HTMLの要素の選び方
Boost.B-tree introduction
[機械学習]文章のクラス分類
D3.jsによるDOM操作

What's hot (10)

PDF
Deep Learningと他の分類器をRで比べてみよう in Japan.R 2014
PPTX
再帰Cte を使って遊ぼう
PDF
Aaなゲームをjsで
PDF
Aedlabo program 20150125
DOCX
Ⅰ. Rの基礎 2017
PDF
Factor型の注意点
PDF
距離まとめられませんでした
PPTX
WindowsストアーアプリでSharpDXを動かしてみる
PDF
Haskell勉強会 14.1〜14.3 の説明資料
PDF
「ビジネス活用事例で学ぶ データサイエンス入門」輪読会#5資料
Deep Learningと他の分類器をRで比べてみよう in Japan.R 2014
再帰Cte を使って遊ぼう
Aaなゲームをjsで
Aedlabo program 20150125
Ⅰ. Rの基礎 2017
Factor型の注意点
距離まとめられませんでした
WindowsストアーアプリでSharpDXを動かしてみる
Haskell勉強会 14.1〜14.3 の説明資料
「ビジネス活用事例で学ぶ データサイエンス入門」輪読会#5資料
Ad

Similar to End challenge Part1 (10)

PDF
初心者講習会資料(Osaka.R#5)
PDF
PythonによるDeep Learningの実装
PDF
Aaなゲームをjsで
PPTX
【LT版】Elixir入門「第7回:Python/KerasをElixirから繋いでアレコレする」
PDF
20170923 excelユーザーのためのr入門
PDF
KETpic できれいな図を書こう
PDF
初心者講習会資料(Osaka.r#6)
PDF
初心者講習会資料(Osaka.R#7)
PDF
Rプログラミング03 「データ分析編」デモ
初心者講習会資料(Osaka.R#5)
PythonによるDeep Learningの実装
Aaなゲームをjsで
【LT版】Elixir入門「第7回:Python/KerasをElixirから繋いでアレコレする」
20170923 excelユーザーのためのr入門
KETpic できれいな図を書こう
初心者講習会資料(Osaka.r#6)
初心者講習会資料(Osaka.R#7)
Rプログラミング03 「データ分析編」デモ
Ad

End challenge Part1

  • 1. import numpy as np from sklearn import datasets, model_selection from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import accuracy_score def print_vec(text, vec): print("*** " + text + " ***") print(vec) #print("shape: " + str(x.shape)) print("") # データセットのロード # iris.data = [(がく片の長さ , がく片の幅 , 花びらの長さ , 花びらの幅)] iris = datasets.load_iris() print_vec("データセットの形状",iris.data.shape) print_vec("花の種類",iris.target_names) #説明変数と目的変数に分割 x_vals, y_vals = iris.data, iris.target # ダミー変数を追加 x_all = np.insert(x_vals, 0, 1.0, axis=1) print_vec("ダミー変数追加",x_all) # 目的変数を one hot ベクトル化 ohe = OneHotEncoder(sparse=False,categories='auto') y_ohe = np.c_[y_vals] y_vals_ohe = ohe.fit_transform(y_ohe) print_vec("目的変数", y_vals_ohe) #テストデータと検証データに分割(8:2) x_train, x_test, y_train, y_test,y_train_ohe, y_test_ohe = model_selection.train_test_split(x_all, y_vals, y_vals_ohe,test_size=0.2) print_vec("x_train",x_train) print_vec("y_train",y_train) print_vec("x_test",x_test) print_vec("y_test",y_test) print_vec("y_train_ohe",y_train_ohe) print_vec("y_test_ohe",y_test_ohe) ## 出力層の活性化関数 # ソフトマックス関数 def softmax(x): if x.ndim == 2: x = x.T x = x - np.max(x, axis=0) y = np.exp(x) / np.sum(np.exp(x), axis=0) return y.T x = x - np.max(x) # オーバーフロー対策 return np.exp(x) / np.sum(np.exp(x))
  • 2. # クロスエントロピー def cross_entropy(yt, yp): return -np.mean(np.sum(yt * np.log(yp), axis=1)) # # ソフトマックスとクロスエントロピーの複合関数 # def softmax_with_loss(d, x): # y = softmax(x) # return cross_entropy_error(d, y) # 予測値の計算を行う関数 def pred(x, W): return softmax(x @ W) # モデル評価関数 def evaluate(x_test, y_test, y_test_ohe, W): # 予測値の計算(確率値) yp_test_ohe = pred(x_test, W) # 確率値から予測クラス(0, 1, 2)を導出 yp_test = np.argmax(yp_test_ohe, axis=1) # 損失関数値の計算 loss = cross_entropy(y_test_ohe, yp_test_ohe) # 精度の算出 score = accuracy_score(y_test, yp_test) return loss, score # 初期化処理 # 学習対象の選択 x, yt = x_train, y_train_ohe # 標本数 M = x.shape[0] # 入力次元数 D = x.shape[1] # 分類先クラス数 N = yt.shape[1] # 繰り返し回数 iters = 10000 # 学習率 alpha = 0.01 # 重み行列の初期設定(すべて 1) W = np.ones((D, N)) # 評価結果記録用
  • 3. history = np.zeros((0, 3)) # メイン処理 for k in range(iters): # 予測値の計算 yp = pred(x, W) # 誤差の計算 yd = yp - yt # 重みの更新 W = W - alpha * (x.T @ yd) / M if (k % 10 == 0): loss, score = evaluate(x_test, y_test, y_test_ohe, W) history = np.vstack((history, np.array([k, loss, score]))) print("epoch = %d loss = %f score = %f" % (k, loss, score)) #損失関数値と精度の確認 print('初期状態: 損失関数:%f 精度:%f' % (history[0,1], history[0,2])) print('最終状態: 損失関数:%f 精度:%f' % (history[-1,1], history[-1,2]))