データセット配列による回帰
次の例では、データセット配列を使用して線形およびステップワイズ回帰解析を行う方法を示します。
標本データを読み込みます。
load imports-85
データセット配列に予測子と応答変数を格納します。
ds = dataset(X(:,7),X(:,8),X(:,9),X(:,15),'Varnames',... {'curb_weight','engine_size','bore','price'});
線形回帰モデルを当てはめます。
車両総重量、エンジンのサイズ、およびボアの観点から、自動車価格を説明する線形回帰モデルを当てはめます。
fitlm(ds,'price~curb_weight+engine_size+bore')
ans = Linear regression model: price ~ 1 + curb_weight + engine_size + bore Estimated Coefficients: Estimate SE tStat pValue __________ _________ _______ __________ (Intercept) 64.095 3.703 17.309 2.0481e-41 curb_weight -0.0086681 0.0011025 -7.8623 2.42e-13 engine_size -0.015806 0.013255 -1.1925 0.23452 bore -2.6998 1.3489 -2.0015 0.046711 Number of observations: 201, Error degrees of freedom: 197 Root Mean Squared Error: 3.95 R-squared: 0.674, Adjusted R-Squared: 0.669 F-statistic vs. constant model: 136, p-value = 1.14e-47
コマンド fitlm(ds)
でも同じ結果が得られます。fitlm
の既定の設定では、予測子変数がデータセット配列 ds
の最後の列にあると認識されます。
データセット配列を再度作成して、解析を繰り返します。
今回は応答変数をデータセット配列の最初の列に格納します。
ds = dataset(X(:,15),X(:,7),X(:,8),X(:,9),'Varnames',... {'price','curb_weight','engine_size','bore'});
応答変数が ds
の最初の列に格納されたら、位置を定義します。たとえば、fitlm
の既定の設定では、bore
が応答変数と見なされます。モデルの応答変数は次のいずれかの方法で定義できます。
fitlm(ds,'ResponseVar','price');
または
fitlm(ds,'ResponseVar',logical([1 0 0 0]));
ステップワイズ回帰を実行します。
stepwiselm(ds,'quadratic','lower','price~1',... 'ResponseVar','price')
1. Removing bore^2, FStat = 0.01282, pValue = 0.90997 2. Removing engine_size^2, FStat = 0.078043, pValue = 0.78027 3. Removing curb_weight:bore, FStat = 0.70558, pValue = 0.40195
ans = Linear regression model: price ~ 1 + curb_weight*engine_size + engine_size*bore + curb_weight^2 Estimated Coefficients: Estimate SE tStat pValue ___________ __________ _______ __________ (Intercept) 131.13 14.273 9.1873 6.2319e-17 curb_weight -0.043315 0.0085114 -5.0891 8.4682e-07 engine_size -0.17102 0.13844 -1.2354 0.21819 bore -12.244 4.999 -2.4493 0.015202 curb_weight:engine_size -6.3411e-05 2.6577e-05 -2.386 0.017996 engine_size:bore 0.092554 0.037263 2.4838 0.013847 curb_weight^2 8.0836e-06 1.9983e-06 4.0451 7.5432e-05 Number of observations: 201, Error degrees of freedom: 194 Root Mean Squared Error: 3.59 R-squared: 0.735, Adjusted R-Squared: 0.726 F-statistic vs. constant model: 89.5, p-value = 3.58e-53
初期モデルは 2 次式で、考慮されている最低のモデルが定数です。ここで、stepwiselm
は後退消去法を実行し、モデルの項を決定します。最終的なモデルは price ~ 1 + curb_weight*engine_size + engine_size*bore + curb_weight^2
で、次に相当します。
ここで、 は価格、 は車両総重量、 はエンジンのサイズ、 はボア、 はモデル内で対応する項の係数、 は誤差項です。最終的なモデルには主要な 3 種類の影響、すなわち車両総重量とエンジンのサイズの交互作用の影響、エンジンのサイズとボアの交互作用の影響、車両総重量の 2 次項が含まれています。
参考
LinearModel
| fitlm
| stepwiselm