#!/usr/bin/env python # coding: utf-8 # # ロジステック回帰 - pystan # In[1]: from __future__ import division import os import sys import glob import matplotlib.pyplot as plt import numpy as np import pandas as pd get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('precision', '4') #plt.style.use('ggplot') import seaborn as sns sns.set_style('white') sns.set_context('paper') np.random.seed(1234) import pystan import scipy.stats as stats import scipy.stats as stats # ## ロジステック回帰による女性・男性決定問題 # # - 身長,体重データを利用して女性・男性を決定する問題を扱う. # - データはpandasのデータフレームとして渡す(データの単位は不明….foot/poundでない) # In[2]: # observed data df = pd.read_csv('data/HtWt.csv') df.head() # In[3]: log_reg_code = """ data { int n; int male[n]; real weight[n]; real height[n]; } transformed data {} parameters { real a; real b; real c; } transformed parameters {} model { a ~ normal(0, 10); b ~ normal(0, 10); c ~ normal(0, 10); for(i in 1:n) { male[i] ~ bernoulli(inv_logit(a*weight[i] + b*height[i] + c)); } } generated quantities {} """ log_reg_dat = { 'n': len(df), 'male': df.male, 'height': df.height, 'weight': df.weight } fit = pystan.stan(model_code=log_reg_code, data=log_reg_dat, iter=2000, chains=1) # In[4]: print(fit) # In[5]: df_trace = pd.DataFrame(fit.extract(['c', 'b', 'a'])) pd.scatter_matrix(df_trace[:], diagonal='kde');