{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\tHiroshi TAKEMOTO\n", "\t(take.pwave@gmail.com)\n", "\t\n", "\t

Sageでグラフを再現してみよう:データ解析のための統計モデリング入門第5章

\n", "\t

\n", "\t\tこの企画は、雑誌や教科書にでているグラフをSageで再現し、\n", "\t\tグラフの意味を理解すると共にSageの使い方をマスターすることを目的としています。\n", "\t

\n", "\t

\n", "\t\t前回に続き、データ解析のための統計モデリング入門\n", "\t\t(以下、久保本と書きます)\n", "\t\tの第5章の例題をSageを使って再現してみます。\n", "\t

\n", "\t

\n", "\t\t私が統計を嫌いになったのは、χ二乗検定が原因です。\n", "\t\tどうしてそうなるのかも説明されないまま検定をすることに納得がいかず拒否していたのを覚えています。\t\n", "\t\t\t\t\n", "\t

\n", "\t

\n", "\t\t久保本はそれをすぱっと解決してくれました。今回の目標はずばり図5.4です(久保本から引用)。\n", "\t\t\n", "\t

\n", "\t

\n", "\t\t数式処理システムSageのノートブックは、計算結果を表示するだけではなく、実際に動かすことができるのが大きな特徴です。\n", "\t\tこの機会にSageを分析に活用してみてはいかがでしょう。\n", "\t

\n", "\n", "\n", "\n", "\t

前準備

\n", "\t

\n", "\t\t最初に必要なライブラリーやパッケージをロードしておきます。\n", "\t

\n", "" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# RとPandasのデータフレームを相互に変換する関数を読み込む\n", "# Rの必要なライブラリ\n", "r('library(ggplot2)')\n", "r('library(jsonlite)')\n", "\n", "# python用のパッケージ\n", "import pandas as pd\n", "import numpy as np\n", "import matplotlib.pyplot as plt \n", "import seaborn as sns\n", "# statsmodelsを使ってglmを計算します\n", "import statsmodels.formula.api as smf\n", "import statsmodels.api as sm\n", "from scipy.stats.stats import pearsonr\n", "%matplotlib inline\n", "\n", "# jupyter用のdisplayメソッド\n", "from IPython.display import display, Latex, HTML, Math, JSON\n", "# sageユーティリティ\n", "load('script/sage_util.py')\n", "# Rユーティリティ\n", "load('script/RUtil.py')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\t

尤度比検定がすごい

\n", "\t

\n", "\t\tどんな統計モデルにも使える尤度比検定が、5章のテーマです。ターゲットの統計モデル(xモデル)と一定値を使った意味の無いモデル\n", "\t\t:帰無仮説の尤度比を使って帰無仮説棄却の可否を判断します。\n", "\t\t(久保本では「無に帰される」から帰無仮説と説明があり昔の人はよい名前を付けるなぁと感動!)\n", "\t

\n", "\t

\n", "\t\t今回は、3章の例題で一定モデルとxモデルを比較します。対数尤度は、以下の様になり、\n", "$$\n", "\t\\frac{L^*_1}{L^*_2} = \\frac{一定モデルの最大尤度}{xモデルの最大尤度}\n", "$$\t\n", "\t\tこれの対数に-2を掛けた値(逸脱度の差)を使って検定をします。\n", "$$\n", "\t\\Delta D_{1,2} = -2 \\times ( log L^*_1 - log L^*_2)\n", "$$\t\t\t\n", "\t

\n", "\t

\n", "\t\t逸脱度の差は、以下の計算で4.5とでました。\n", "\t

\n", "" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 3章のデータをもう一度読み込む\n", "d = pd.read_csv('http://hosho.ees.hokudai.ac.jp/~kubo/stat/iwanamibook/fig/poisson/data3a.csv')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 一定モデル(k=1)でのglm回帰を実行\n", "fit1 = smf.glm('y ~ 1', data=d, family=sm.families.Poisson(link=sm.families.links.log)).fit()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# xモデル\n", "fit2 = smf.glm('y ~ x', data=d, family=sm.families.Poisson(link=sm.families.links.log)).fit()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "逸脱度の差$\\Delta D_{1,2}$が4.5ぐらいと求まる。" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4.5139410788519854" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 逸脱度(-2logL)\n", "-2*(fit1.llf - fit2.llf)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "\n", "\n", " \n", "\n", "\n", " \n", "\n", "\n", " \n", "\n", "\n", " \n", "\n", "\n", " \n", "\n", "\n", " \n", "\n", "\n", " \n", "\n", "\n", " \n", "\n", "
Model: GLM AIC: 477.2864
Link Function: log BIC: -366.4049
Dependent Variable: y Log-Likelihood: -237.64
Date: 2016-07-17 06:17 LL-Null: -237.64
No. Observations: 100 Deviance: 89.507
Df Model: 0 Pearson chi2: 87.1
Df Residuals: 99 Scale: 1.0000
Method: IRLS
\n", "\n", "\n", " \n", "\n", "\n", " \n", "\n", "
Coef. Std.Err. z P>|z| [0.025 0.975]
Intercept 2.0580 0.0357 57.5862 0.0000 1.9879 2.1280
" ], "text/plain": [ "\n", "\"\"\"\n", " Results: Generalized linear model\n", "==============================================================\n", "Model: GLM AIC: 477.2864 \n", "Link Function: log BIC: -366.4049\n", "Dependent Variable: y Log-Likelihood: -237.64 \n", "Date: 2016-07-17 06:17 LL-Null: -237.64 \n", "No. Observations: 100 Deviance: 89.507 \n", "Df Model: 0 Pearson chi2: 87.1 \n", "Df Residuals: 99 Scale: 1.0000 \n", "Method: IRLS \n", "---------------------------------------------------------------\n", " Coef. Std.Err. z P>|z| [0.025 0.975]\n", "---------------------------------------------------------------\n", "Intercept 2.0580 0.0357 57.5862 0.0000 1.9879 2.1280\n", "==============================================================\n", "\n", "\"\"\"" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 一定モデル(fit1)の切片beta_2の推定値2.058となり、exp(2.058)がd.yの平均とほぼ一致していることを確認\n", "fit1.summary2()" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7.83029355218137 7.83\n" ] } ], "source": [ "print exp(2.058), d.y.mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\t

帰無仮説を棄却させる手順

\n", "\t

\n", "\t\t第一種の過誤の検討に専念して、以下の手順で帰無仮説を棄却します。\n", "\t\t

    \n", "\t\t\t
  1. 帰無仮説(今回は一定モデル)が正しいものと仮定する
  2. \n", "\t\t\t
  3. 観測データに帰無モデルをあてはめ、$\\hat{\\beta_1}=2.058$を得て、これが真のモデルとする
  4. \n", "\t\t\t
  5. 上記の真のモデルからサンプルデータを生成し、その度に一定モデルをあてはめ、$\\Delta D_{1,2}$を求め、その分布を求める
  6. \n", "\t\t\t
  7. 求まった分布から一定モデル(帰無モデル)とxモデルの逸脱度の差$\\Delta D_{1,2} \\geq 4.5$となる確率Pを評価する
  8. \n", "\t\t
\n", "\t

\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\t

サンプルの生成

\n", "\t

\n", "\t\tSageには、ポアソン分布を生成する関数が無いので、Rのrpois関数を使ってlambda_targetで指定されたλのサンプルを\n", "\t\tsample_size個生成する関数genSampleを以下の様に定義します。\n", "\t

\n", "" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Rの乱数の種をセット\n", "r('set.seed(101)')\n", "# sageobjを使って変換する方が速いのでgenSample関数を使用する\n", "def genSample(lambda_target, sample_size):\n", " return np.array(sageobj(r('rpois(%d, %f)'%(sample_size, lambda_target))))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\t

パラメトリックブートストラップ法

\n", "\t

\n", "\t\tパラメトリックブートストラップ法をSageで試してみます。4章のバイアスの計算と異なり、\n", "\t\t一定モデルを真のモデルとしてサンプルデータを生成し、一定モデルとxモデルにGLMを使って\n", "\t\t回帰分析を行い、対数尤度llfから逸脱度Dの差を求めます。\n", "\t\tこれをn_bootstrap回繰り返し、その分布を求めます。\n", "\t

\n", "" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# パラメトリックブートストラップ法\n", "def pb(d, n_bootstrap):\n", " N = len(d)\n", " y_mean = d.y.mean()\n", " def sampling(d, y_mean, N):\n", " # 帰無仮説を真のモデルとしてサンプルデータを生成\n", " d['rnd'] = genSample(y_mean, N)\n", " fit1 = smf.glm('rnd ~ 1', data=d, family=sm.families.Poisson(link=sm.families.links.log)).fit()\n", " fit2 = smf.glm('rnd ~ x', data=d, family=sm.families.Poisson(link=sm.families.links.log)).fit() \n", " return -2*(fit1.llf - fit2.llf)\n", " return [ sampling(d, y_mean, N) for i in range(n_bootstrap)]\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# 逸脱度の差を1000サンプル生成\n", "dd12 = pb(d, 1000)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\t

サンプルの結果

\n", "\t

\n", "\t\tブートストラップ法で求まった結果にdescribe(Rのsummaryに相当)を使って分布の概要を把握し、\n", "\t\tggplotのヒストグラムでその分布を表示してみます。\n", "\t

\n", "" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
x
count1000.000000
mean0.988756
std1.451894
min0.000001
25%0.079798
50%0.412794
75%1.236868
max12.078559
\n", "
" ], "text/plain": [ " x\n", "count 1000.000000\n", "mean 0.988756\n", "std 1.451894\n", "min 0.000001\n", "25% 0.079798\n", "50% 0.412794\n", "75% 1.236868\n", "max 12.078559" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dd12Df = pd.DataFrame({'x' : dd12})\n", "dd12Df.describe()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYUAAAEBCAYAAACXArmGAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAAPYQAAD2EBqD+naQAAHDlJREFUeJzt3X9MnfXd//HXdUDgFPnZwlpqa+9UhcjNbkQ6MtcviWIk\nEwpJk9XZShAtIlU3HTbuD7NJVmVVo6ytmUHst99aiFk0c1JpzFLcauyseKDdbY16T+0PteXHaS29\n6SmUc67vH0s/25H+4PzAQy+fj8SwXp9zXX2/FnpeXNd1OMeybdsWAACSXLEeAAAwc1AKAACDUgAA\nGJQCAMCgFAAABqUAADAoBQCAccmUgm3bGhkZEb9WAQDTJz7WA3zT0NDJc24fHT2p//iP+fr88y+V\nnJzyLU81vVwuS5mZyTp2bFSBgHNKz6m5JOdmc2ouybnZpporK2tqz5uXzJmCZVlBX53E5bJkWZZc\nLmdlc2ouybnZnJpLcm62aOe6ZEoBADD9KAUAgDHj7imcT//efklS7c9/o/j4hLCOMT8jTk8/8VgU\npwIAZ7lkSmHs9JgkKemK/6PLEmeFd5BT70dxIgBwHi4fAQAMSgEAYFAKAACDUgAAGJQCAMCgFAAA\nBqUAADAoBQCAQSkAAAxKAQBgUAoAAINSAAAYlAIAwKAUAAAGpQAAMCgFAIBBKQAADEoBAGBQCgAA\ng1IAABiUAgDAoBQAAAalAAAwQi4Fl8slt9utWbNmma8///nPJUk9PT0qKSlRWlqaCgoK1NnZGbTv\nhg0blJeXp/T0dJWWlqqvry86KQAAUREf6g6WZemTTz7RggULgrYfPXpU1dXV2rRpk26//Xa9/fbb\nqqqqUl5enoqKitTV1aXm5ma9+eabKigo0O9+9ztVVlbq008/ldvtjlogAED4Qj5TsG1btm1P2t7R\n0aHc3FzV1tYqISFBZWVlqqqqUnt7uySpra1NdXV1Ki4uVmJiotauXSvLstTV1RV5CgBAVIR1T+GR\nRx7RlVdeqYyMDN17770aHR2Vx+NRUVFR0OOKiorU29srSZPWLctSYWG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/fbb7SNH\njsR6rJCd/XcUHx9vx8fHmz+f9fbbb9uFhYV2UlKSnZeXZ7/22msxnDY0F8r2m9/8xo6Li7Pdbrf5\n72zGUPB5CgAAg3sKAACDUgAAGJQCAMCgFAAABqUAADAoBQCAQSkAAAxKAQBgUAoAAINSAAAYlAIA\nwPj/bKs5D55rHC8AAAAASUVORK5CYII=\n", "text/plain": [ "Graphics object consisting of 1 graphics primitive" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "histogram(dd12, figsize=4, bins=20)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\t

仮説の検証

\n", "

\n", " 逸脱度の差$\\Delta D_{1,2} \\ge 4.5$となる確率Pをp値と呼びます。\n", "

\n", "\t

\n", "\t\t一定もでるとxモデルの逸脱度の差(4.5)以上のデータの個数は、41個でp値は、41/1000=0.041となり、95%となるxの値は\n", "\t\t4.02と求まります。\n", "\t

\n", "\t

\n", "\t\tp値(0.041)が有意水準5%(0.05)よりも小さいため、帰無仮説(一定モデル)は棄却され、xモデルが採択されました。\n", "\t

\n", "" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "41" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 4.5以上のデータの個数は\n", "len(dd12Df[dd12Df.x >= 4.5])" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "x 4.022639\n", "dtype: float64" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 95%となるxの値を求める\n", "dd12Df.quantile(0.95)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\t

χ自乗分布を使かう方法

\n", "

\n", " 逸脱度の差$\\Delta D_{1,2}$の確率分布は、自由度1の$\\chi ^2$分布で近似できる場合があります。\n", " anovaにtest=\"Chisq\"を渡してp値を計算します。\n", "

\n", "\t

\n", "\t\t残念ながら、statsmodelsにはglmに対するanovaがないため、Rにデータを渡して、計算しました。\n", "\t\tp値は、0.034となり、同様に帰無仮説は棄却されました。(Rを使っているので、久保本と同じ結果になるのは当然です。)\n", "\t

\n", "\n", "\n", "$\\chi ^2$分布の他に、anovaに渡す確率分布には以下のものがあります。\n", " - 平均の差を検定量とする場合、$t$分布\n", " - 分散比検定量とする場合、$F$分布\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Rにdを渡して計算\n", "PandaDf2RDf(d, \"d\")" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "Analysis of Deviance Table\n", "\n", "Model 1: y ~ 1\n", "Model 2: y ~ x\n", " Resid. Df Resid. Dev Df Deviance Pr(>Chi) \n", "1 99 89.507 \n", "2 98 84.993 1 4.5139 0.03362 *\n", "---\n", "Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# ANOVA(ANalysis Of VAriance)を使って逸脱度を調べる、Chisq(χ)でχ二乗分布近似を指定。\n", "r('fit1 <- glm(y ~ 1, data=d, family=poisson)')\n", "r('fit2 <- glm(y ~ x, data=d, family=poisson)')\n", "r('anova(fit1, fit2, test = \"Chisq\")')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "SageMath 7.2", "language": "", "name": "sagemath" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.10" } }, "nbformat": 4, "nbformat_minor": 0 }