d <- read.csv(file = 'https://stats.dip.jp/01_ds/data/gender.csv')

library(DT)
datatable(d, caption = '性別データ')
d$性別 <- ifelse(d$性別 == '男性', 1, 0)
datatable(d)
fit <- glm(性別~身長,data=d,family='binomial')
summary(fit)
## 
## Call:
## glm(formula = 性別 ~ 身長, family = "binomial", data = d)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -105.1286    18.8522  -5.576 2.45e-08 ***
## 身長           0.6092     0.1092   5.577 2.45e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 186.965  on 134  degrees of freedom
## Residual deviance:  41.452  on 133  degrees of freedom
## AIC: 45.452
## 
## Number of Fisher Scoring iterations: 7
a <- seq(150,200,1)  #130cm~200cm
b <- predict(fit,type='response',newdata=data.frame(身長=a))
matplot(x=d$身長,y=d$性別,pch=1,ylim=c(0,1.1),xlim=c(150,200),
        main='ロジスティック回帰分析',
        xlab='身長',
        ylab ='性別')
grid()
matlines(x=a,y=b,lty=1,col=rainbow(1),lwd = 2)
library(latex2exp)
text(x=174,y=0.4,adj=0,
     labels=TeX('$\\leftarrow \\hat{p}=\\frac{1}{1+\\exp\\{-(b_0 + b_1 x)\\}}$'))
legend('topleft',pch=c(1,NA),lty=c(NA,1),col=c(1,2),
       legend=c('男性(1),女性(0)','ロジスティック回帰モデル'))

library(plotly)
## 要求されたパッケージ ggplot2 をロード中です
## Warning: パッケージ 'ggplot2' はバージョン 4.4.1 の R の下で造られました
## 
## 次のパッケージを付け加えます: 'plotly'
## 以下のオブジェクトは 'package:ggplot2' からマスクされています:
## 
##     last_plot
## 以下のオブジェクトは 'package:latex2exp' からマスクされています:
## 
##     TeX
## 以下のオブジェクトは 'package:stats' からマスクされています:
## 
##     filter
## 以下のオブジェクトは 'package:graphics' からマスクされています:
## 
##     layout
plot_ly(type = 'scatter') |>
  add_trace(x = d$身長, y = d$性別,
            mode = 'markers', name = '男性(1),女性(0)') |>
  add_trace(x = a, y = b, 
            mode = 'lines',   name = 'ロジスティック回帰モデル') |> 
  layout(title = 'ロジスティック回帰分析', 
         xaxis = list(title = '平均身長'),
         yaxis = list(title = '性別'))
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
yp <- predict(fit, type = 'response', newdata = data.frame(身長 = 170))
sprintf('男性である確率:%2.1f%', yp * 100)
## [1] "男性である確率:17.2%"
import pandas as pd
import numpy as np
z = pd.read_csv('https://stats.dip.jp/01_ds/data/gender.csv')
xx = z['身長'].to_numpy().reshape(-1, 1)
yy = z['性別']
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(random_state = 1)
model.fit(xx, yy)
LogisticRegression(random_state=1)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
xp = np.arange(150, 200, 0.1).reshape(-1,1)
yp = model.predict_proba(xp)
import matplotlib.pyplot as plt
plt.title('ロジスティック回帰分析',fontdict={'family':'MS Gothic','fontsize':16})
plt.xlabel('平均身長[cm]',fontdict={'family':'MS Gothic','fontsize':16})
plt.ylabel('男性(1),女性(0)',fontdict={'family':'MS Gothic','fontsize':16})
plt.grid(linestyle = '--', color = (0.9, 0.9, 0.9, 0.25))
plt.plot(xx, yy, 'o', label = 'Data points')
plt.plot(xp, yp[:, 1], linestyle = 'solid', 
         label = '$/hat{y}_i=//frac{1}{1-//exp(b_0 + b_1 x_i)}$')
plt.legend
## <function legend at 0x000001A617188C20>
plt.legend(loc = 'lower left').get_frame().set_alpha(0.4)
plt.show()
## C:\Users\TIU sota kurihara\AppData\Local\Programs\R\R-4.4.0\library\reticulate\python\rpytools\call.py:6: UserWarning: Glyph 30007 (\N{CJK UNIFIED IDEOGRAPH-7537}) missing from current font.
##   return call_r_function(f, *args, **kwargs)
## C:\Users\TIU sota kurihara\AppData\Local\Programs\R\R-4.4.0\library\reticulate\python\rpytools\call.py:6: UserWarning: Glyph 24615 (\N{CJK UNIFIED IDEOGRAPH-6027}) missing from current font.
##   return call_r_function(f, *args, **kwargs)
## C:\Users\TIU sota kurihara\AppData\Local\Programs\R\R-4.4.0\library\reticulate\python\rpytools\call.py:6: UserWarning: Glyph 22899 (\N{CJK UNIFIED IDEOGRAPH-5973}) missing from current font.
##   return call_r_function(f, *args, **kwargs)

xp1 = [[170]]
yp1 = model.predict_proba(xp1)
print('性別:', yp1[0, 1].round(1) * 100, '%')
## 性別: 20.0 %
xp = np.arange(150, 200, 0.1)

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=z['身長'], y=z['性別'], 
                         mode = 'markers', name = '男性(1),女性(0)'))
fig.add_trace(go.Scatter(x=xp, y=yp[:, 1],
                         mode = 'lines', name = 'ロジスティック回帰モデル'))
fig.update_layout(title='ロジスティック回帰分析',
                   xaxis_title='平均身長[cm]',
                   yaxis_title='男性(1),女性(0)')  
fig.show()
library(reticulate)
## Warning: パッケージ 'reticulate' はバージョン 4.4.1 の R の下で造られました
library(DT)
datatable(py$z, caption = '身長と性別')