始める無料で始める

`numpy` を使った最小二乗法

以下の式は、イントロダクションで扱った微分計算の結果です。この演習では、その計算が正しいものとして信頼し、これらの式を numpy を使ってコードで実装します。

$$ a_{1} = \frac{ covariance(x, y) }{ variance(x) } $$ $$ a_{0} = mean(y) - a_{1} mean(x) $$

この演習はコースの一部です

Pythonで学ぶ線形モデリング入門

コースを見る

演習の手順

  • 事前に読み込まれたデータから、2 つの変数 x, y の平均と偏差を計算します。
  • np.sum() を使って最小二乗法の式を完成させ、a0a1 の最適値を計算します。
  • model() を使って、その最適な傾き a1 と切片 a0 からモデル値 y_model を作成します。
  • 事前定義された compute_rss_and_plot_fit() を使って、この最適モデルがデータに適合していることを可視的に確認します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# prepare the means and deviations of the two variables
x_mean = np.____(x)
y_mean = np.____(y)
x_dev = x - ____
y_dev = y - ____

# Complete least-squares formulae to find the optimal a0, a1
a1 = np.sum(____ * ____) / np.sum( np.square(____) )
a0 = ____ - (a1 * ____)

# Use the those optimal model parameters a0, a1 to build a model
y_model = model(x, ____, ____)

# plot to verify that the resulting y_model best fits the data y
fig, rss = compute_rss_and_plot_fit(a0, a1)
コードを編集して実行