Rで分析する前に対象データを変換したい

目的

 Rのcaretパッケージを用いてデータ分析をする前に

 対象のデータセットをデータ変換して扱いやすくしたい!

 

参考リンク

 https://cran.r-project.org/web/packages/caret/caret.pdf

 

動作環境

 Windows7

 R 3.3.1

 RStudio 1.0.143

 

やりかた

library(caret)

# 変換処理前のDataset
Before = iris

# 変換式を求める
# BoxCox 歪度修正
# center 平均を0へ
# scale  標準偏差を1へ
# pca    主成分へ
trans = preProcess(Before, method = c("BoxCox", "center", "scale", "pca"))

# 変換処理後のDataset
After = predict(trans, Before)

 

Good Luck !!!

Tensorflowで人の顔を見分ける(5)

目的

 Tensorflowで人の顔を分類したい!

 

参考リンク

 TensorFlowでアニメゆるゆりの制作会社を識別する - kivantium活動日記

 

動作環境

 Windows7

 Python3.5.3 (過去ログご参考)

 

やりかた

 全体の流れ

  1.それぞれの人の顔の画像を複数集める

  2.画像から人の顔だけを切出す

  3.切出した顔をチェックして不要なものを削除

  4.学習用データと検証用データに分ける

  5.学習する

  6.学習結果をみる

  7.見分ける

 

 この投稿では7項

 7.見分ける

   好きな画像をTensorBoardで作成したネットワークにかけて分類する。

    ※参考リンクのプログラムを使わせて頂いた。ブログ主さんに感謝。

  1)Pythonで以下を実行。引数に分類したい画像を指定。

#! -*- coding: utf-8 -*-
import sys
import os
import numpy as np
import tensorflow as tf
import cv2

NUM_CLASSES = 2
IMAGE_SIZE = 28
IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3

#---------------------------------------------------------------
# 予測モデルの作成関数
#  引数    images_placeholder : 画像のplaceholder
#          keep_prob          : dropout率のplace_holder
#  返り値  y_conv             : 各クラスの確率のようなもの
#---------------------------------------------------------------
def inference(images_placeholder, keep_prob):

    # 重みを標準偏差0.1の正規分布で初期化する関数
    def weight_variable(shape):
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial)

    # バイアスを標準偏差0.1の正規分布で初期化する関数
    def bias_variable(shape):
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial)

    # 畳み込み層を作成する関数
    def conv2d(x, W):
        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

    # プーリング層を作成する関数
    def max_pool_2x2(x):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    # 入力画像の整形
    x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3])

    # 畳み込み層1の作成
    with tf.name_scope('conv1') as scope:
        W_conv1 = weight_variable([5, 5, 3, 32])
        b_conv1 = bias_variable([32])
        h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

    # プーリング層1の作成
    with tf.name_scope('pool1') as scope:
        h_pool1 = max_pool_2x2(h_conv1)
    
    # 畳み込み層2の作成
    with tf.name_scope('conv2') as scope:
        W_conv2 = weight_variable([5, 5, 32, 64])
        b_conv2 = bias_variable([64])
        h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

    # プーリング層2の作成
    with tf.name_scope('pool2') as scope:
        h_pool2 = max_pool_2x2(h_conv2)

    # 全結合層1の作成
    with tf.name_scope('fc1') as scope:
        W_fc1 = weight_variable([7*7*64, 1024])
        b_fc1 = bias_variable([1024])
        h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
        h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    # 全結合層2の作成
    with tf.name_scope('fc2') as scope:
        W_fc2 = weight_variable([1024, NUM_CLASSES])
        b_fc2 = bias_variable([NUM_CLASSES])

    # ソフトマックス関数による正規化
    with tf.name_scope('softmax') as scope:
        y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

    # 各ラベルの確率のようなものを返す
    return y_conv

#---------------------------------------------------------------
# メイン関数
#---------------------------------------------------------------
if __name__ == '__main__':

    TARGET_NAME = ['0番目の人', '1番目の人']                                  # 0から順番に識別する人の名前

    test_image = []                                                           # 識別する画像を入れる配列
    for i in range(1, len(sys.argv)):
        img = cv2.imread(sys.argv[i])                                         # 画像データ読込み
        img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE))                       # 画像データのリサイズ
        test_image.append(img.flatten().astype(np.float32)/255.0)             # 画像データを1列にし0~255を0~1のfloat値へ
    test_image = np.asarray(test_image)                                       # numpy形式に変換

    images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))  # 画像     を入れる仮のTensor
    labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))   # ラベル   を入れる仮のTensor
    keep_prob = tf.placeholder("float")                                       # dropout率を入れる仮のTensor

    logits = inference(images_placeholder, keep_prob)                         # inference()を呼出しモデルを作成
    sess = tf.InteractiveSession()

    saver = tf.train.Saver()                                                  # 保存結果の読出し準備
    sess.run(tf.global_variables_initializer())                               # 変数の初期化
    saver.restore(sess, os.getcwd() + "/model.ckpt")                          # 保存結果の読出し

    for i in range(len(test_image)):
        pr = logits.eval(feed_dict={images_placeholder: [test_image[i]], keep_prob: 1.0 })[0]  # 識別する画像の評価
        pred = np.argmax(pr)
        print("{0} : {1}, {2} : {3}".format(TARGET_NAME[0], pr[0], TARGET_NAME[1], pr[1]))     # NUM_CLASSESが3以上ならばここも拡張ください
        print(TARGET_NAME[pred])

 

Good Luck !!!

 

Tensorflowで人の顔を見分ける(4)

目的

 Tensorflowで人の顔を分類したい!

 

参考リンク

 TensorFlowでアニメゆるゆりの制作会社を識別する - kivantium活動日記

 

動作環境

 Windows7

 Python3.5.3 (過去ログご参考)

 Google Chrome

 

やりかた

 全体の流れ

  1.それぞれの人の顔の画像を複数集める

  2.画像から人の顔だけを切出す

  3.切出した顔をチェックして不要なものを削除

  4.学習用データと検証用データに分ける

  5.学習する

  6.学習結果をみる

  7.見分ける

 

 この投稿では6項

 6.学習結果をみる

  TensorBoardにて学習結果やネットワーク構造をみる

  1)コマンドプロンプトから以下を実行

    > tensorboard  --logdir  <FLAGS.train_dirで指定したフォルダ>

  2)コマンドプロンプトをそのままに Google Chrome を立ち上げる

  3)URLに http://localhost:6006 を指定

  4)SCALARSタブで、学習結果についての学習ステップの推移をみる

  5)GRAPHSタブで、ネットワーク図をみる

  6)見終わったらコマンドプロンプトから Ctrl+C で終了

 

Good Luck !!!

Tensorflowで人の顔を見分ける(3)

目的

 Tensorflowで人の顔を分類したい!

 

参考リンク

 TensorFlowでアニメゆるゆりの制作会社を識別する - kivantium活動日記

 

動作環境

 Windows7

 Python3.5.3 (過去ログご参考)

 

やりかた

 全体の流れ

  1.それぞれの人の顔の画像を複数集める

  2.画像から人の顔だけを切出す

  3.切出した顔をチェックして不要なものを削除

  4.学習用データと検証用データに分ける

  5.学習する

  6.学習結果をみる

  7.見分ける

 

 この投稿では5項

  5.学習する

   参考リンクのプログラムを使わせて頂いた。ブログ主さんに感謝。

   1)Pythonで以下を実行

# -*- coding: utf-8 -*-
import os
import sys
import cv2
import numpy as np
import tensorflow as tf
import tensorflow.python.platform

NUM_CLASSES = 2
IMAGE_SIZE = 28
IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('train', 'train.txt', '')  # 学習用データファイル名
tf.app.flags.DEFINE_string('test', 'test.txt', '')    # テスト用データファイル名
tf.app.flags.DEFINE_string('train_dir', '.', '')      # TensorBoard表示用データのフォルダ
tf.app.flags.DEFINE_integer('max_steps', 200, '')     # 学習ステップ数
tf.app.flags.DEFINE_integer('batch_size', 10, '')     # 1回に学習する画像数(train/batch_sizeが割切れること)
tf.app.flags.DEFINE_float('learning_rate', 1e-4, '')  # 学習係数

#---------------------------------------------------------------
# 予測モデルの作成関数
#  引数    images_placeholder : 画像のplaceholder
#          keep_prob          : dropout率のplace_holder
#  返り値  y_conv             : 各クラスの確率のようなもの
#---------------------------------------------------------------
def inference(images_placeholder, keep_prob):

    # 重みを標準偏差0.1の正規分布で初期化する関数
    def weight_variable(shape):
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial)

    # バイアスを標準偏差0.1の正規分布で初期化する関数
    def bias_variable(shape):
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial)

    # 畳み込み層を作成する関数
    def conv2d(x, W):
        return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

    # プーリング層を作成する関数
    def max_pool_2x2(x):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    # 入力画像の整形
    x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3])

    # 畳み込み層1の作成
    with tf.name_scope('conv1') as scope:
        W_conv1 = weight_variable([5, 5, 3, 32])
        b_conv1 = bias_variable([32])
        h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

    # プーリング層1の作成
    with tf.name_scope('pool1') as scope:
        h_pool1 = max_pool_2x2(h_conv1)

    # 畳み込み層2の作成
    with tf.name_scope('conv2') as scope:
        W_conv2 = weight_variable([5, 5, 32, 64])
        b_conv2 = bias_variable([64])
        h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

    # プーリング層2の作成
    with tf.name_scope('pool2') as scope:
        h_pool2 = max_pool_2x2(h_conv2)

    # 全結合層1の作成
    with tf.name_scope('fc1') as scope:
        W_fc1 = weight_variable([7*7*64, 1024])
        b_fc1 = bias_variable([1024])
        h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
        h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    # 全結合層2の作成
    with tf.name_scope('fc2') as scope:
        W_fc2 = weight_variable([1024, NUM_CLASSES])
        b_fc2 = bias_variable([NUM_CLASSES])

    # ソフトマックス関数による正規化
    with tf.name_scope('softmax') as scope:
        y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

    # 各ラベルの確率のようなものを返す
    return y_conv

#---------------------------------------------------------------
# ロスを計算する関数
#  引数    logits        : ロジット        のtensor, float - [batch_size, NUM_CLASSES]
#          labels        : ラベル          のtensor, int32 - [batch_size, NUM_CLASSES]
#  返り値  cross_entropy : 交差エントロピーのtensor, float
#---------------------------------------------------------------
def loss(logits, labels):
    cross_entropy = -tf.reduce_sum(labels*tf.log(logits))
    tf.summary.scalar("cross_entropy", cross_entropy)
    return cross_entropy

#---------------------------------------------------------------
# 学習を定義する関数
#  引数    loss          : 損失のtensor, loss()の結果
#          learning_rate : 学習係数
#  返り値  train_step    : 学習結果
#---------------------------------------------------------------
def training(loss, learning_rate):
    train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
    return train_step

#---------------------------------------------------------------
# 正解率を計算する関数
#  引数    logits   : inference()の結果
#          labels   : ラベルのtensor, int32 - [batch_size, NUM_CLASSES]
#  返り値  accuracy : 正解率(float)
#---------------------------------------------------------------
def accuracy(logits, labels):
    correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    tf.summary.scalar("accuracy", accuracy)
    return accuracy

#---------------------------------------------------------------
# メイン関数
#---------------------------------------------------------------
if __name__ == '__main__':

    # 学習用データの読込み
    f = open(FLAGS.train, 'r')
    train_image = []                                               # 学習用画像を入れる配列
    train_label = []                                               # 学習用ラベルを入れる配列
    for line in f:
        line = line.rstrip()                                       # 改行を除く
        l = line.split()                                           # スペースを区切り文字にリスト化
        img = cv2.imread(l[0])                                     # 画像データ読込み
        img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE))            # 画像データのリサイズ
        train_image.append(img.flatten().astype(np.float32)/255.0) # 画像データを1列にし0~255を0~1のfloat値へ
        tmp = np.zeros(NUM_CLASSES)                                # クラス数個のゼロを持つ配列
        tmp[int(l[1])] = 1                                         # 正解の配列番号に1を
        train_label.append(tmp)
    train_image = np.asarray(train_image)                          # numpy形式に変換
    train_label = np.asarray(train_label)                          # numpy形式に変換
    f.close()

    # テストデータの読込み
    f = open(FLAGS.test, 'r')
    test_image = []
    test_label = []
    for line in f:
        line = line.rstrip()
        l = line.split()
        img = cv2.imread(l[0])
        img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE))
        test_image.append(img.flatten().astype(np.float32)/255.0)
        tmp = np.zeros(NUM_CLASSES)
        tmp[int(l[1])] = 1
        test_label.append(tmp)
    test_image = np.asarray(test_image)
    test_label = np.asarray(test_label)
    f.close()

    with tf.Graph().as_default():
        images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))  # 画像     を入れる仮のTensor
        labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))   # ラベル   を入れる仮のTensor
        keep_prob = tf.placeholder("float")                                       # dropout率を入れる仮のTensor

        logits = inference(images_placeholder, keep_prob)                         # inference()を呼出しモデルを作成
        loss_value = loss(logits, labels_placeholder)                             # loss()     を呼出し損失を計算
        train_op = training(loss_value, FLAGS.learning_rate)                      # training() を呼出し学習
        acc = accuracy(logits, labels_placeholder)                                # accuracy() を呼出し精度の計算

        saver = tf.train.Saver()                                                  # 保存の準備
        sess = tf.Session()                                                       # Sessionの作成
        sess.run(tf.global_variables_initializer())                               # 変数の初期化
        summary_op = tf.summary.merge_all()                                       # TensorBoardで表示する値の設定
        summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)       # TensorBoardで表示する値の設定

        # 学習
        for step in range(FLAGS.max_steps):                                       # ステップ回数分学習
            for i in range(int(len(train_image)/FLAGS.batch_size)):               # 1回にbatch_size分の画像に対して学習
                batch = FLAGS.batch_size*i
                sess.run(train_op, feed_dict={
                    images_placeholder : train_image[batch:batch+FLAGS.batch_size],
                    labels_placeholder : train_label[batch:batch+FLAGS.batch_size],
                    keep_prob          : 0.5})

            # 1ステップ終わるたび精度を計算
            train_accuracy = sess.run(acc, feed_dict={
                images_placeholder : train_image,
                labels_placeholder : train_label,
                keep_prob          : 1.0})
            print("step {0}, training accuracy {1}".format(step, train_accuracy))

            # 1ステップ終わるたびTensorBoardに表示する値を追加
            summary_str = sess.run(summary_op, feed_dict={
                images_placeholder : train_image,
                labels_placeholder : train_label,
                keep_prob          : 1.0})
            summary_writer.add_summary(summary_str, step)

    # 学習が終了したらテストデータに対する精度を表示
    print("test accuracy {0}".format(sess.run(acc, feed_dict={
        images_placeholder: test_image,
        labels_placeholder: test_label,
        keep_prob: 1.0})))

    # 最終的なモデルを保存
    cwd = os.getcwd()
    save_path = saver.save(sess, cwd + "/model.ckpt")

 

Good Luck !!!

Tensorflowで人の顔を見分ける(2)

目的

 Tensorflowで人の顔を分類したい!

 

参考リンク

 TensorFlowでアニメゆるゆりの制作会社を識別する - kivantium活動日記

 

動作環境

 Windows7

 Python3.5.3 (過去ログご参考)

 

やりかた

 全体の流れ

  1.それぞれの人の顔の画像を複数集める

  2.画像から人の顔だけを切出す

  3.切出した顔をチェックして不要なものを削除

  4.学習用データと検証用データに分ける

  5.学習する

  6.学習結果をみる

  7.見分ける

 

 この投稿では4項

  4.学習用データと検証用データに分ける

     ※ランダムにデータを学習用(7割)と検証用(3割)に分ける

     学習用データは train.txt へ

     検証用データは test.txt へ

     各行に、画像データの相対パス、スペース、分類結果を持つ

     分類結果は0から番号付け(0なら1人目、1なら2人目)

   1)Pythonで以下を実行

# -*- coding: utf-8 -*
import sys
import os
import random

wari  = 0.7
train = open('train.txt', 'w')
test  = open('test.txt', 'w')

files = os.listdir('1人目の画像フォルダ')
for file in files:
  imgfile = '1人目の画像フォルダ' + file
  f = random.random()
  if f > wari:
    test.write(imgfile)
    test.write(" 0\n")
  else:
    train.write(imgfile)
    train.write(" 0\n")

files = os.listdir('2人目の画像フォルダ')
for file in files:
  imgfile = '2人目の画像フォルダ' + file
  f = random.random()
  if f > wari:
    test.write(imgfile)
    test.write(" 1\n")
  else:
    train.write(imgfile)
    train.write(" 1\n")

train.close()
test.close()

 

Good Luck !!!

 

Tensorflowで人の顔を見分ける(1)

目的

 Tensorflowで人の顔を分類したい!

 

参考リンク

 TensorFlowでアニメゆるゆりの制作会社を識別する - kivantium活動日記

 

動作環境

 Windows7

 Python3.5.3 (過去ログご参考)

 

やりかた

 全体の流れ

  1.それぞれの人の顔の画像を複数集める

  2.画像から人の顔だけを切出す

  3.切出した顔をチェックして不要なものを削除

  4.学習用データと検証用データに分ける

  5.学習する

  6.学習結果をみる

  7.見分ける

 

 この投稿では1項~3項まで

  1.それぞれの人の顔の画像を複数集める

   1)デジカメなどで画像を収集し

   2)区分したい人ごとに別々のフォルダへ保存

  2.区分したい人ごとのフォルダの画像から人の顔だけを切出す

   1)切出した画像を保存するため保存先のフォルダをあらかじめ作っておく

   2)OpenCVの機能を使って人の顔を判定する

     Pythonで以下を実行

# -*- coding: utf-8 -*
import sys
import os
import cv2

count = 0
face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml')
files = os.listdir('元画像フォルダ')

for file in files:
  imgfile = '元画像フォルダ' + file
  print(imgfile)
  frame = cv2.imread(imgfile)
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  faces = face_cascade.detectMultiScale(gray, 1.3, 5)
  for (x,y,w,h) in faces:
    count += 1
    f = cv2.resize(gray[y:y+h, x:x+w], (200, 200))
    cv2.imwrite('保存先フォルダ/%s.jpg' % str(count), f)

  3.切出した顔をチェックして不要なものを削除

   1)保存先フォルダを目視チェック

   2)人の顔をうまく判定できなかった画像などの不要な画像を削除

 

Good Luck !!!

 

PythonでTenforflowが使える環境を構築する

目的
 WindowsパソコンでTensorflowのディープラーニングが遊べる環境がほしい!

 

参考リンク
 tensorflow-master-win-cmake-py [Jenkins]

 

動作環境
 Windows7
 Python 2.7.13 :: Anaconda 4.3.1 (64-bit)

 

やりかた

 1.Python3.5の環境を作る

    コマンドプロンプトから以下を実行

    > conda create -n "環境名" python=3.5

    > activate "環境名"

 2.参考リンクからTensorflowのビルドをダウンロードする

    tensorflow-1.1.0rc2-cp35-cp35m-win_amd64.whl

 3.作成した環境でTensorflowをインストールする

    > pip install -U --ignore-installed --upgrade 絶対パス\tensorflow-1.1.0rc2-cp35-cp35m-

    win_amd64.whl

    > python -c "import tensorflow;"

 4.その他使いそうなものもインストールする

    > conda install numpy

    > conda install matplotlib

    > conda install opencv

 

Good Luck !!!