開始使用免費開始

擬合線性模型

現在我們要擬合一個線性模型,因為它簡單且容易理解。模型擬合完成後,你可以看到哪些預測變數與目標之間呈現有意義的線性關聯,以及它們對目標的影響幅度。判斷預測變數是否具有顯著性,是根據係數的 p 值。這相當於用 t 檢定來統計檢驗該係數是否與 0 有顯著差異。p 值代表某個特徵的係數與 0 沒有差異的機率。一般而言,p 值小於 0.05 就代表該係數與 0 有顯著差異。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 使用 .fit() 方法擬合線性模型,並將結果存入 results 變數。
  • 使用 .summary() 函式列印結果摘要。
  • 列印結果中的 p 值(results.pvalues 屬性)。
  • 使用 results 物件的 .predict() 函式,分別對 train_featurestest_features 進行預測。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create the linear model and complete the least squares fit
model = sm.OLS(train_targets, train_features)
results = model.____  # fit the model
print(results.____)

# examine pvalues
# Features with p <= 0.05 are typically considered significantly different from 0
print(results.____)

# Make predictions from our model for train and test sets
train_predictions = results.predict(train_features)
test_predictions = ____
編輯並執行程式碼