線形回帰

Introduction to TensorFlow in Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

線形回帰とは?

この画像は、住宅の広さ(平方フィート)の自然対数と価格(ドル)の自然対数の散布図を示しています。

Introduction to TensorFlow in Python

線形回帰とは?

この画像は、住宅の広さの自然対数と価格の自然対数の散布図に当てはめた回帰直線を示しています。

Introduction to TensorFlow in Python

線形回帰モデル

  • 線形回帰モデルは線形関係を仮定します:
    • $price = intercept + size*slope + error$
  • これは単回帰の例です。
    • 特徴量は size のみ。
  • 重回帰は特徴量が複数あります。
    • 例: size と location
Introduction to TensorFlow in Python

TensorFlowでの線形回帰

# Define the targets and features
price = np.array(housing['price'], np.float32)
size = np.array(housing['sqft_living'], np.float32)

# Define the intercept and slope
intercept = tf.Variable(0.1, np.float32)
slope = tf.Variable(0.1, np.float32)
# Define a linear regression model
def linear_regression(intercept, slope, features = size):
    return intercept + features*slope
# Compute the predicted values and loss
def loss_function(intercept, slope, targets = price, features = size):
    predictions = linear_regression(intercept, slope)
    return tf.keras.losses.mse(targets, predictions)
Introduction to TensorFlow in Python

TensorFlowでの線形回帰

# Define an optimization operation
opt = tf.keras.optimizers.Adam()
# Minimize the loss function and print the loss
for j in range(1000):
    opt.minimize(lambda: loss_function(intercept, slope),\
    var_list=[intercept, slope])
    print(loss_function(intercept, slope))
tf.Tensor(10.909373, shape=(), dtype=float32)
...
tf.Tensor(0.15479447, shape=(), dtype=float32)
# Print the trained parameters
print(intercept.numpy(), slope.numpy())
Introduction to TensorFlow in Python

Let's practice!

Introduction to TensorFlow in Python

Preparing Video For Download...