LoginSignup
4
2

More than 5 years have passed since last update.

計測器の画像にラベリングして学習し、画像から計測値を予測する

Last updated at Posted at 2017-12-01

はじめに

以下のURLで紹介している方法でラベリングをした画像を学習する手順を以下に記します。

機械学習のための画像ラベリングを支援するWebアプリケーションを作ってみた

環境

  • MacBook Air
  • Python3系
  • SciKit-learn

使ったもの

  • 100円均一のお店で買った重量計
  • 長女(ラベリング作業)

ソースコード

以下のスクリプトを作成します。

train.py
# ライブラリ読込
import cv2
import sqlite3
import numpy as np
import pandas as pd

from sklearn import model_selection
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPRegressor

# ラベルデータ読込
dbname = "param.db"
table = "param"
sql = "select * from {} ORDER BY id".format(table)

conn = sqlite3.connect(dbname)

df = pd.read_sql(sql, conn)
df.index = df.pop("id")

conn.close()

# 画像データ読込
images = []

for i, row in df.iterrows():

    idx = i

    filename = "img/{:03}.png".format(idx)
    img = cv2.imread(filename)
    img = img[row.top:row.bottom,row.left:row.right]
    img = cv2.resize(img, (100,100))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, img = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY)

    images.append(img.flatten().astype(np.float32) / 255.0)

df_img = pd.DataFrame(images)

df = pd.concat([df, df_img], axis=1)

# 学習用データ作成
cols = df.columns.tolist()
cols = cols[4:]

df_train = df[cols]
df_train.shape

X = df_train[cols[1:]].as_matrix().astype("float")
y = df_train["val"].as_matrix().astype("int").flatten()

# テストデータの割合設定
test_size = 0.05

# 教師データを学習データと検証データに分割
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=test_size, random_state=42)

# 正規化
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

mlp = MLPRegressor(batch_size=20, max_iter=1000, random_state=42)

model = mlp

# 学習データを2倍にしてみる(不要)
#X_train = np.r_[X_train, X_train]
#y_train = np.r_[y_train, y_train]

# 学習と予測
model.fit(X_train, y_train)
print(model.score(X_test,y_test))

作成したら、以下のとおり実行。

$ python train.py
0.76047251454038367

できた(^-^)/

でも、精度が悪すぎるのでまだまだ工夫が必要ですね(-_-;)

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2