LoginSignup
3
3

More than 3 years have passed since last update.

逆行列法(Inverse Matrix Method)

Last updated at Posted at 2019-07-05

はじめに

これは筆者の勉強まとめページですので、指摘しまくってい頂けると幸いです

そもそも回帰とは

とあるデータに対してどのような値を取りうるか予測をすること。

逆行列法

逆行列法は $$ A・x = b$$ のような行列方程式に対して解を求めるような手法である。
一般的は $$ x = A^{-1}・b $$
のようにAの逆行列を適用することにより、解を求めるのだが、そもそもAの逆行列が必ず存在するとは限らない。
そこで、Aの転置行列の性質を用いることにより、以下のように解を算出することができる。$$
x = (^{t}A・A)^{-1}・^{t}A・b $$ のように解を算出することができる。
これを用いて実際に回帰問題を解いてみた。

# ライブラリのインポート

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

# セッションの設定

sess = tf.Session()

# 教師データの作成

x_vals = np.linspace(0, 10, 100)
y_vals = x_vals + np.random.normal(0, 1, 100)

# 行列の初期化 2x100の行列Aを作成 1x100の行列bを作成

x_vals_column = np.transpose(np.matrix(x_vals))
ones_column = np.transpose(np.repeat(1, 100))
A = np.column_stack((x_vals_column, ones_column))

b = np.transpose(np.matrix(y_vals))


# 定数のtensorを作成

A_tensor = tf.constant(A)
b_tensor = tf.constant(b)

# 逆行列法の適用

tA_A = tf.matmul(tf.transpose(A_tensor), A_tensor)
tA_A_inv = tf.matrix_inverse(tA_A)
product = tf.matmul(tA_A_inv, tf.transpose(A_tensor))
solution = tf.matmul(product, b_tensor)

solution_eval = sess.run(solution)

slope = solution_eval[0][0]
y_intercept = solution_eval[1][0]

print("slope = ", str(slope))
print("y_intercept = ", str(y_intercept))

best_fit = []
for i in x_vals:

    best_fit.append(slope * i + y_intercept)

plt.plot(x_vals, y_vals, "o", label = "Data")
plt.plot(x_vals, best_fit, "r-", label = "Best fit line", linewidth = 3)
plt.legend(loc = "upper left")
plt.show()

Unknown.png
実行すると、ランダムな点に対してフィットした直線が得られた。

3
3
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
3
3