<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Go's BLOG</title>
    <description>머신러닝, 딥러닝, 통계에 대한 개인적인 정리 자료.</description>
    <link>https://godongyoung.github.io/</link>
    <atom:link href="https://godongyoung.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Fri, 22 Nov 2019 07:38:31 +0000</pubDate>
    <lastBuildDate>Fri, 22 Nov 2019 07:38:31 +0000</lastBuildDate>
    <generator>Jekyll v3.8.5</generator>
    
      <item>
        <title>[Code implementation] Bayesian Gaussian mixture</title>
        <description>&lt;p&gt;베이지안 방법론을 통해 gaussian mixture를 푸는 코드이다. Frequentist의 접근법처럼 역시나 group indicator를 latent로 두어, 이에 대한 prior가 또 들어간다. group indicator는 multi-category를 가진 categorical variable이기에,  multi-category에 대해 conjugate한 Dirichlet distribution이 prior로 사용된다. 또한 추정해야할 모수가 group indicator, 각 분포의 mu, sigma로 여러개가 있어, MCMC를 통해 한번에 sampling하기 힘들다. 따라서 parameter가 많은 경우 자주 활용되는 Gibbs sampler를 이용하여, 각각의 parameter에 대해 conditional distribution에서 sampling을 한다.&lt;/p&gt;

&lt;p&gt;베이지안 방법론으로 적합을 할 시, 각 parameter들에 대한 estimation이 주어진 MCMC sample들에 기반하여 쉽게 이뤄질 수 있기에, 기존 frequentist의 접근에선 수식적으로 까다로웠던 많은 부분들이 해결된다. 그러나 적절하지 못한 prior를 지정해줄 경우, 모델이 좋은 추정을 하지 못할 가능성이 존재한다.&lt;/p&gt;

&lt;h1 id=&quot;library&quot;&gt;Library&lt;/h1&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;repr.plot.width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;repr.plot.height&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;library&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MCMCpack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#for dirichlet&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set.seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1013&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ls&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;setwd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'C:/Users/admin/내파일/대학원1학기/베이즈/HW2'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;read.table&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'Pset2data.txt'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;header&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#Y=data$Gene2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;$&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gene1&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nclass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;Normal Mixture&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69405816-fefa2e00-0d43-11ea-8a70-8a07f8e0cb8e.png&quot; alt=&quot;output_3_0&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;function&quot;&gt;Function&lt;/h1&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;gibbs_sampler&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1e3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;no_library&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;FALSE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#K=2; n_iter=2e3; Y=data$Gene1;no_library=TRUE&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# create variable for saving each trace-----------------------------------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_trace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_trace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_trace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_trace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;llikelihood_trace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  
  
  &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# initialize_value-----------------------------------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ceiling&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;runif&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#rdirichlet(1,alpha = rep(1/K,K))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_save&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#rinvgamma(K,3,100)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#iterate using Gibbs Sampling-----------------------------------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;table&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'z_lv,pi_lv,mu_lv,sig2_lv is : '&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'\n'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#pi step------------    &lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#lv for latest_value&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;-1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; 
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;-1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;-1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#sampling pi, and save (accept prob for Gibbs is 1)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#pi_trace[,t] = rdirichlet(1,nk+1)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#when you cannot use rdirichlet---------------------------------------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;no_library&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;TRUE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stopifnot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rbeta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape1&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;+1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;+1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#when you cannot use rdirichlet---------------------------------------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rdirichlet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;+1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#mu step----------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;condi_mean&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;condi_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;+1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stopifnot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;condi_sig2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;condi_sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;+1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; 
    
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#sampling mu, and save (accept prob for Gibbs is 1)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;condi_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;condi_sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#zstep------------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nrow&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;-1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat_prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;colSums&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;each&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nrow&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#normalize to sum1&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#i=11&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;TRUE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#z_trace[i,t] = which.max(rmultinom(1, 1, cat_prob[,i]))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#sig2 step----------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#sampling sig2, and save (accept prob for Gibbs is 1)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;no_library&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;TRUE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rgamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;100+1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2+3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rinvgamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;100+1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2+3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;table&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;llikelihood&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#k=2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;llikelihood&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;llikelihood&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#(Y-mu_lv[k])^2/sig2_lv[k]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
        &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])))&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_lv&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
          &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;-1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
          &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;-1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2e4&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;-4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;-100&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_lv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;llikelihood_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;llikelihood&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#print data -----------------------------------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%%&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#check first 10 steps or every 500 steps&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'for'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;', z_lv,pi_lv,mu_lv,sig2_lv is : '&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'\n'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;llikelihood_trace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;names&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'z_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'pi_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'mu_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'sig2_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'llikelihood_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;return&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;simulte--convergence-check&quot;&gt;Simulte &amp;amp; Convergence check&lt;/h1&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2e3&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set.seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1014&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#iterage multiple chain to compare result &lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gibbs_sampler&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;$&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gene1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gibbs_sampler&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;$&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gene1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gibbs_sampler&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iter&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;$&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gene1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;z_lv,pi_lv,mu_lv,sig2_lv is :  40 32 0.5 0.5 -191.0087 -27.92372 0.3 0.3 
for 2 , z_lv,pi_lv,mu_lv,sig2_lv is :  38 34 0.56 0.44 0.22 0.59 0.2165637 0.1509482 
for 3 , z_lv,pi_lv,mu_lv,sig2_lv is :  43 29 0.44 0.56 0.02 0.83 0.2510533 0.1417167 
for 4 , z_lv,pi_lv,mu_lv,sig2_lv is :  57 15 0.6 0.4 0.05 1.01 0.3747806 0.1155301 
for 5 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.81 0.19 0.15 1.89 0.3290877 0.06525928 
for 6 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.83 0.17 -0.04 2.48 0.345712 0.07573328 
for 7 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.88 0.12 0.07 2.4 0.2992068 0.07914449 
for 8 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.8 0.2 0.2 2.41 0.3677189 0.09115946 
for 9 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.86 0.14 -0.06 2.33 0.3403325 0.09380707 
for 10 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.85 0.15 0.05 2.52 0.4521353 0.0782955 
for 500 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.92 0.08 0.19 2.5 0.3426829 0.07064485 
for 1000 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.84 0.16 0.08 2.45 0.3653833 0.07525163 
for 1500 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.81 0.19 -0.01 2.51 0.255525 0.09068538 
for 2000 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.88 0.12 -0.01 2.51 0.300147 0.07983018 
z_lv,pi_lv,mu_lv,sig2_lv is :  35 37 0.5 0.5 182.5481 115.7144 0.3 0.3 
for 2 , z_lv,pi_lv,mu_lv,sig2_lv is :  30 42 0.47 0.53 0.39 0.33 0.1380176 0.2655488 
for 3 , z_lv,pi_lv,mu_lv,sig2_lv is :  22 50 0.49 0.51 0.53 0.29 0.1321068 0.2340113 
for 4 , z_lv,pi_lv,mu_lv,sig2_lv is :  27 45 0.25 0.75 0.06 0.56 0.1543063 0.2010244 
for 5 , z_lv,pi_lv,mu_lv,sig2_lv is :  28 44 0.35 0.65 -0.03 0.69 0.1593382 0.205812 
for 6 , z_lv,pi_lv,mu_lv,sig2_lv is :  41 31 0.46 0.54 0.02 0.55 0.2156582 0.1554942 
for 7 , z_lv,pi_lv,mu_lv,sig2_lv is :  44 28 0.48 0.52 -0.13 0.93 0.2514632 0.143165 
for 8 , z_lv,pi_lv,mu_lv,sig2_lv is :  60 12 0.68 0.32 -0.03 1.18 0.261554 0.08524478 
for 9 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.79 0.21 -0.01 2.24 0.3305866 0.07985622 
for 10 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.84 0.16 0.01 2.31 0.3925597 0.07986116 
for 500 , z_lv,pi_lv,mu_lv,sig2_lv is :  63 9 0.88 0.12 0.04 2.63 0.3045323 0.07649907 
for 1000 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.88 0.12 0.06 2.42 0.3116635 0.069078 
for 1500 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.89 0.11 0.11 2.51 0.3665746 0.09550593 
for 2000 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.84 0.16 0.12 2.39 0.3540361 0.07251946 
z_lv,pi_lv,mu_lv,sig2_lv is :  36 36 0.5 0.5 -5.090603 -59.35514 0.3 0.3 
for 2 , z_lv,pi_lv,mu_lv,sig2_lv is :  38 34 0.48 0.52 0.31 0.52 0.1765433 0.1678907 
for 3 , z_lv,pi_lv,mu_lv,sig2_lv is :  53 19 0.52 0.48 0.03 0.76 0.3007423 0.09123187 
for 4 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.8 0.2 0.03 1.5 0.336586 0.06957606 
for 5 , z_lv,pi_lv,mu_lv,sig2_lv is :  63 9 0.83 0.17 0.17 2.42 0.3289166 0.08441534 
for 6 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.87 0.13 0.03 2.62 0.3206282 0.06735946 
for 7 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.77 0.23 0.12 2.53 0.3357813 0.07837687 
for 8 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.88 0.12 0.13 2.22 0.3373437 0.084334 
for 9 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.82 0.18 0.04 2.6 0.2830813 0.08200646 
for 10 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.78 0.22 0.03 2.67 0.3110761 0.07652402 
for 500 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.9 0.1 0.04 2.45 0.3481991 0.07615492 
for 1000 , z_lv,pi_lv,mu_lv,sig2_lv is :  62 10 0.92 0.08 0.07 2.56 0.3003156 0.07968798 
for 1500 , z_lv,pi_lv,mu_lv,sig2_lv is :  61 11 0.85 0.15 0.07 2.48 0.3360475 0.101472 
for 2000 , z_lv,pi_lv,mu_lv,sig2_lv is :  63 9 0.88 0.12 0.13 2.54 0.3583726 0.05720203 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'z_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'pi_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'mu_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'sig2_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'llikelihood_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace_mcmc1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mcmc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#summary(trace_mcmc1)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace_mcmc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace_mcmc2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mcmc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace_mcmc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace_mcmc3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mcmc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trace_mcmc3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69405817-fefa2e00-0d43-11ea-9e5b-3c309e85df48.png&quot; alt=&quot;output_8_0&quot; /&gt;
&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69405818-ff92c480-0d43-11ea-88c6-ee9fb8a803b8.png&quot; alt=&quot;output_8_1&quot; /&gt;
&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69405819-ff92c480-0d43-11ea-8987-48d21b86e5b0.png&quot; alt=&quot;output_8_2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;수렴을 확인하기 위해 chain을 여러번 돌린다. 각 group indicator (여기선 2개의 group을 주었으니 1,2)는 임의적인 것이라, 순서가 바뀔 수 있다. 수렴을 확인하기 위한 다양한 방법이 있지만, 그중에서 multiple chain간의 with in variance와 between variance를 비교하는 Gelman Rubin statistics를 이용하였다. 보통 1.1이하의 값을 띄면 수렴했다고 판단한다.&lt;/p&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# convergence check with Gelman Rubin statistics&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_m1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mcmc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_m2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mcmc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_m3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mcmc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_niter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#combinedchains = mcmc.list(trace_mcmc1, trace_mcmc2,trace_mcmc3)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combinedchains&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mcmc.list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_m1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_m2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_m3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combinedchains&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gelman.diag&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combinedchains&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gelman.plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combinedchains&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Potential scale reduction factors:

     Point est. Upper C.I.
[1,]          1          1
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69405820-ff92c480-0d43-11ea-8d44-5bb7227cb774.png&quot; alt=&quot;output_9_1&quot; /&gt;
&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69405821-002b5b00-0d44-11ea-8585-efc99abfb3c4.png&quot; alt=&quot;output_9_2&quot; /&gt;&lt;/p&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;### generate samples using posterior inference&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;one_tmp&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tmp3&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_pi&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;colMeans&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;one_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'pi_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;colMeans&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;one_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'mu_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_sig2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;colMeans&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;one_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'sig2_trace'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_tmp&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;par&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mfrow&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nclass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nclass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69405823-002b5b00-0d44-11ea-8e87-3c5a53e8f077.png&quot; alt=&quot;output_10_0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;덧붙여 EM algorithm으로 동일한 데이터에 대해 적합해보았다.&lt;/p&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;###data check with traditional K-mixture-----------------------------&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K_mixture&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;$&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gene1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#init value&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#c(mu1,mu2,mu3)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# common variance&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  
  &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;repeat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;term&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# saving value of each distn in each column&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;## E-step&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;term&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# common variance&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;term&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rowSums&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;term&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;## M-step&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#update the parameters which maximize the Q-function&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      
      &lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      
      
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;byrow&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# sum for all i,k (common variance)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;## Convergence criteria&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#,logL))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1e-7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'converge!\n'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_pi&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_sig2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_tmp&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;par&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mfrow&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nclass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nclass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;return&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;mixture_res&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K_mixture&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;$&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Gene1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mixture_res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#c(pi,mu,sig2)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[1]  0.5000000  0.5000000 -0.1572504  4.3961548  2.0000000
[1] 0.8904799 0.1095201 0.1807714 2.3333463 0.3589446
[1] 0.85349044 0.14650956 0.06586353 2.45927732 0.09452766
[1] 0.84722265 0.15277735 0.05209006 2.43746643 0.07434040
[1] 0.84722223 0.15277777 0.05208921 2.43746456 0.07433937
converge!
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69405824-002b5b00-0d44-11ea-9a45-c9c41cae47fa.png&quot; alt=&quot;output_12_2&quot; /&gt;&lt;/p&gt;

</description>
        <pubDate>Tue, 22 Oct 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/10/22/Gaussian-Mixture-Bayesian-method.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/10/22/Gaussian-Mixture-Bayesian-method.html</guid>
        
        <category>Gaussian mixture</category>
        
        <category>Bayesian</category>
        
        <category>implementation</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[Code implementation] Gaussian mixture</title>
        <description>&lt;p&gt;데이터가 주어졌을때, 해당 데이터가 미지의 정규분포들의 혼합된 분포에서 만들어졌다는 가정하에, 해당 분포의 혼합 비율과 각 분포들의 parameter(즉, mu와 sigma), 그리고 어떤 데이터가 어느 정규분포에 속할지를 풀어내는 방법론이다.&lt;/p&gt;

&lt;p&gt;가장 대표적으로는 EM algorithm으로 적합을 한다. 이때, group indicator는 latent variable로써, 일종의 missing data problem으로 볼 수도 있다. 따라서 주어진 데이터들로 구해지는 observed likelihood에 기반하여 missing data(여기서는 group indicator)의 conditional expectation을 maximize하는 parameter들을 찾게 된다.&lt;/p&gt;

&lt;h1 id=&quot;data-generating&quot;&gt;Data generating&lt;/h1&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;rm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ls&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;options&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;repr.plot.width&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;repr.plot.height&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set.seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vector&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rmultinom&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n3&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# pi, mu, sig2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;density&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;main&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;Normal Mixture (unknown mixing proportions&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xlab&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;y&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69406285-11c13280-0d45-11ea-8055-e39a8db5e831.png&quot; alt=&quot;output_2_0&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;em-itertaion-start&quot;&gt;EM Itertaion start&lt;/h1&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#init value&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#init value&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;30&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#c(mu1,mu2,mu3)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# common variance&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;


&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;repeat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;term&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kc&quot;&gt;NA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# saving value of each distn in each column&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;## E-step&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;term&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# common variance&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;term&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rowSums&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;term&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;## M-step&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#update the parameters which maximize the Q-function&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    
    &lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
    

  &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ncol&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;byrow&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu_mat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# sum for all i,k (common variance)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;## Convergence criteria&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;^&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#,logL))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  
  &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1e-7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'converge!\n'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#true_eta&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'estimated paramter:'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'\n True parameter:'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_eta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;'\n'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;


&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[1]   0.50000   0.50000 -15.56966  11.44557   2.00000
[1]  0.0006600105  0.9993399895 -1.9043484852  5.4641191864  6.0853710365
[1]  0.001271911  0.998728089 -0.957922404  5.467428396  6.068737972
[1]  0.002645395  0.997354605 -0.781882072  5.475809985  6.017866002
[1]  0.005456573  0.994543427 -0.725702903  5.493189764  5.911302780
[1]  0.01103187  0.98896813 -0.67838249  5.52772084  5.70096930
[1]  0.02154037  0.97845963 -0.60592134  5.59277818  5.31134601
[1]  0.03974788  0.96025212 -0.49287727  5.70563357  4.65470960
[1]  0.06651677  0.93348323 -0.33950502  5.87245547  3.72513681
[1]  0.09343209  0.90656791 -0.16216272  6.03860678  2.86440850
[1] 0.10871129 0.89128871 0.01281094 6.12356374 2.50306621
[1] 0.1159491 0.8840509 0.1447868 6.1562836 2.4168499
[1] 0.1198564 0.8801436 0.2268347 6.1717975 2.3928645
[1] 0.1221463 0.8778537 0.2761977 6.1804368 2.3832596
[1] 0.1235372 0.8764628 0.3061812 6.1855807 2.3783766
[1] 0.1243968 0.8756032 0.3246337 6.1887308 2.3756040
[1] 0.1249330 0.8750670 0.3361018 6.1906867 2.3739498
[1] 0.1252693 0.8747307 0.3432760 6.1919101 2.3729383
[1] 0.1254809 0.8745191 0.3477826 6.1926787 2.3723114
[1] 0.1256143 0.8743857 0.3506212 6.1931628 2.3719198
[1] 0.1256986 0.8743014 0.3524121 6.1934683 2.3716740
[1] 0.1257518 0.8742482 0.3535431 6.1936613 2.3715193
[1] 0.1257855 0.8742145 0.3542579 6.1937832 2.3714217
[1] 0.1258067 0.8741933 0.3547099 6.1938603 2.3713601
[1] 0.1258202 0.8741798 0.3549957 6.1939091 2.3713212
converge!
estimated paramter: 0.13 0.87 0.35 6.19 2.37 
 True parameter: 0.1 0.3 0.6 0 4 7 1 
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;여기서 group indicator(1,2,3)의 부여는 임의적인 것이기에, 순서는 다를 수 있다. 실제 mixture분포의 true 비율인 0.1, 0.3, 0.6을 0.13, 0.35, 0.87로, true 평균인 0,4,7을 0.35, 2.37, 6.19로 잡아내고 있음을 볼 수 있다&lt;/p&gt;

&lt;div class=&quot;language-R highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_pi&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_mu&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;

&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_sig2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sig2&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_tmp&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
  &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_tmp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sd&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;w&quot;&gt; &lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;posterior_mean_sig2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;par&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mfrow&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nclass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_sim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nclass&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;m&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;w&quot;&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/69406286-11c13280-0d45-11ea-8ec7-3b53f3a2f234.png&quot; alt=&quot;output_4_0&quot; /&gt;&lt;/p&gt;

</description>
        <pubDate>Tue, 15 Oct 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/10/15/Gaussian-Mixture-EM-algorithm.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/10/15/Gaussian-Mixture-EM-algorithm.html</guid>
        
        <category>Gaussian mixture</category>
        
        <category>EM algorithm</category>
        
        <category>implementation</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[데이터분석 정리]HDBSCAN 이해하기 (with python)</title>
        <description>&lt;p&gt;density based clusering 방법론중 가장 대표적인 방법이 바로 DBSCAN이다. 그러나 DBSCAN은 local density에 대한 정보를 반영해줄 수 없고, 또한 데이터들의 계층적 구조를 반영한 clustering이 불가능하다. 이를 개선한 알고리즘이 HDBSCAN이다. 다음은 파이선의 hdbscan 패키지에서의 설명글을 바탕으로 hdbscan의 적합방법과 특성에 대해 정리한 글이다.&lt;/p&gt;

&lt;p&gt;toy example에 대해 직접 hdbscan을 적합하며, 데이터에 어떤식으로 적합이 이뤄지는지를 따라나가보자.&lt;/p&gt;

&lt;h2 id=&quot;준비-단계&quot;&gt;준비 단계&lt;/h2&gt;

&lt;p&gt;먼저 필요한 패키지들을 import 해보자.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;seaborn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;sklearn.datasets&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;matplotlib&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inline&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set_context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'poster'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set_style&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'white'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;set_color_codes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'alpha'&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'s'&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;80&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'linewidths'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rcParams&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;figure.figsize&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;!pip install hdbscan&quot;&quot;&quot;&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;hdbscan&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;다음으로 적합을 할 toy 데이터를 만들어보자. 여기에선 기존의 샘플 데이터에서 약간 손을 봤다.  우리는 아래의 데이터를 클러스터링 해볼것이다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;moons&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;make_moons&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;blobs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;make_blobs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.75&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cluster_std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;blobs2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;make_blobs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cluster_std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;moons&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blobs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blobs2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'b'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085113-b2e69580-9773-11e9-8fdf-9e9b7b4aec4b.png&quot; alt=&quot;output_5_0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;반원형 데이터들은 &lt;strong&gt;매우 오밀 조밀&lt;/strong&gt;하고, 왼쪽위와 오른족 아래의 원들은 그보다는 &lt;strong&gt;밀도가 낮은 타원&lt;/strong&gt;이다. 그리고 오른쪽위와 왼족아래는 그것보다 &lt;strong&gt;더더욱 밀도가 낮은 타원형태&lt;/strong&gt;이다.(분산이 4배)  이러한 데이터는 dense가 각기 달라, 만약 반원의 기준에 맞추게 되면 타원데이터들은 모두 noise로 처리가 되거나 이상한 클러스터에 속하게 될것이다.&lt;/p&gt;

&lt;p&gt;그럼 이 데이터에 hdbscan을 적합하고, 해당 결과물을 가지고 직접 따라가보자.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hdbscan&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;HDBSCAN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_cluster_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gen_min_span_tree&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;이제-hdbscan에-대해-알아보자&quot;&gt;이제, HDBSCAN에 대해 알아보자!&lt;/h2&gt;

&lt;p&gt;HDBSCAN이 어케 작동하는지를 다음의 스텝을 따라 확인해볼것이다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;Transform the space according to the density/sparsity.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Build the minimum spanning tree of the distance weighted graph.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Construct a cluster hierarchy of connected components.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Condense the cluster hierarchy based on minimum cluster size.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Extract the stable clusters from the condensed tree.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;transform-the-space-according-to-the-densitysparsity&quot;&gt;Transform the space according to the density/sparsity.&lt;/h2&gt;
&lt;p&gt;우선 첫째로 하고픈건, distance를 좀더 robust하게 만드는것이다. 왜그렇게 하냐? 계층적 클러스터링의 대표적인 알고리즘 single linkage은 작은 distance에 특히 민감하게 반응하는데, 이때 noisy한 데이터로 생긴 distance로 hierachy가 심하게 변동되기 때문이다.&lt;/p&gt;

&lt;p&gt;고로 우리가 사용할 &lt;strong&gt;transformed된 distance metric&lt;/strong&gt;은 다음과 같다. 이때 core_k(a)는 a의 k-th nearest neighbor까지의 거리이다. (robust한 distance를 만드는 방식은 LOF의 distance와 매우 유사하다!)&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;d_{mreach−k}(a,b)=max[{core_k(a),core_k(b),d(a,b)}]&lt;/script&gt;

&lt;p&gt;이를 &lt;strong&gt;mutual reachability&lt;/strong&gt;라고 부른다. 두점 a와 b의 거리를 잴때 &lt;strong&gt;{1. a의 이웃과의 거리, 2. b의 이웃과의 거리 3. a와 b자체의 거리}중 max값&lt;/strong&gt;을 고르는 것이다. 이로써 dense한 지점의 데이터는 core_k가 매우 작기에 d(a,b)를 바로 사용하고, dense가 낮은 지점의 경우 우연히 한점이 바로 옆에 존재해도, core_k의 주변 정보를 사용하게 된다. 이는 distance의 robustness를 늘리고, 최종적으로는 더 효율적인 clustering을 가능하게 한다고 한다. &lt;a href=&quot;https://arxiv.org/pdf/1506.06422v2.pdf&quot;&gt;참조&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;build-the-minimum-spanning-tree-of-the-distance-weighted-graph&quot;&gt;Build the minimum spanning tree of the distance weighted graph.&lt;/h2&gt;

&lt;p&gt;이제 이 mutual reachability를 이용하여 각 데이터들간의 거리를 구할 수 있다. 이를 이용해서 각 데이터를 이은 graph를 그릴 것이다.&lt;/p&gt;

&lt;p&gt;데이터를 각 꼭지점으로 삼으며 잇되, 그 이은 선(edge)에 점수(mutual reachability)를 부여한다.  distance가 weight인 graph(길이가 길수록 weight도 커짐)로 만드는것이다. 사실 의미상 weight보단 그냥 점수, 혹은 인덱스 정도로 이해하면 된다.&lt;/p&gt;

&lt;p&gt;패키지상에선 minumum spanning tree라는 함수를 통해 이것의 graph의 결과를 보여줄 수 있다. 트리의 적합은 아직 추가되지 않은 점중 &lt;strong&gt;가장 가까운&lt;/strong&gt;(가장 점수가 낮은)edge를 &lt;strong&gt;하나씩만&lt;/strong&gt; 추가하며, 결과적으로 모든 점을 포괄할때까지 트리를 키워나간다. (이때 wegiht는 그냥 distance가 아닌 mutual reachabillity인것 상기, 거리는 어차피 고정이므로, 어느점에서 트리를 시작하던 최종 트리는 똑같음. unique)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;minimum_spanning_tree_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;edge_cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'viridis'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                      &lt;span class=&quot;n&quot;&gt;edge_alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                      &lt;span class=&quot;n&quot;&gt;node_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                      &lt;span class=&quot;n&quot;&gt;edge_linewidth&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085114-b2e69580-9773-11e9-9fb1-dc52dfaffaf4.png&quot; alt=&quot;output_11_1&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;construct-a-cluster-hierarchy-of-connected-components&quot;&gt;Construct a cluster hierarchy of connected components.&lt;/h2&gt;

&lt;p&gt;이제 이를 바탕으로 ‘계층’을 만드려한다. 구체적으로는 이 점수(혹은 weight)를 점차 낮추면서, 하나씩 graph를 끊는다.(mutual reachability distance가 0.9인 지점의 연결선을 끊고, 0.8끊고, 0.7 끊고…이런식!) 그후,만들어진 minimum spanning tree를 가장 가까운 거리부터 (우리가 아는 기존의 hierachy clustering처럼) 묶는다.&lt;/p&gt;

&lt;p&gt;이때 가장 가까운 애 하나만 있으면 그 component자체를 연결해주니, Single linkage라고 할 수 있다. (그러나 pure distance가 아니라 mutual reachability를 사용했으니, &lt;strong&gt;robust single linkage&lt;/strong&gt;라고 한다)&lt;/p&gt;

&lt;p&gt;아래의 그림을 보면 mutual reachability(y축)에 따라 생성된 hierachy를 볼 수 있다.
(주의! 아직까지는 robust single linkage를 이용한 hierachy clustering의 방법까지만 설명했다. HDBSCAN안나왓다.)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;single_linkage_tree_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cmap&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'viridis'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;colorbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085115-b37f2c00-9773-11e9-8e8f-1fa453b33ecd.png&quot; alt=&quot;output_14_1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;보통의 single linkage cluster는 여기에서 눈대중으로 괜찮아보이는 cut level을 정한다. (즉, distance를 정한다. 예를 들어 mutual reachability=0.3에서 평행선 쭉 그어서 cluster만들기)&lt;/p&gt;

&lt;p&gt;그러나 우리는 variabel density cluster를 만들고 싶다. 어떤 클러스터에서는 distance=0.3이 큰 거리이지만 또다른 dense를 가진 클러스터에선 그다지 크지 않은 거리일 수도 있기에!
여기에서 HDBSCAN의 알고리즘이사용된다.&lt;/p&gt;

&lt;h2 id=&quot;condense-the-cluster-hierarchy-based-on-minimum-cluster-size&quot;&gt;Condense the cluster hierarchy based on minimum cluster size.&lt;/h2&gt;

&lt;p&gt;위의 그림에서 볼 수 있듯이, 또 쉽게 상상할 수 있듯이 threshold distance가 내려가면서 hierachy가 분할될때, 분할의 많은 경우가 데이터 1개, 2개가 떨어져나오는 경우들이 많아 지저분 하게 된다. (위 그림 기준으로는 dinstance 0.4이하로는 거의 다 데이터 한개가 떨어져 나오는 경우이다.) 이런 경우를 ‘2개의 클러스터로 나뉘어진것’으로 보지 않고, ‘한개의 클러스터가 데이터를 잃은 것’(이를 fell out으로 표현한다) 으로 치부한다. 마치 noise로 치부하는 느낌이다. (이때 필요한게 &lt;strong&gt;minimum size&lt;/strong&gt;로, HDBSCAN의 하이퍼파라미터이다)&lt;/p&gt;

&lt;p&gt;이렇게 쭉 내려가서, 최종적으론 &lt;strong&gt;minimum size이상의 크기를 가진 component들&lt;/strong&gt;이 남게 된다. 이를 똑같이 덴드로그램으로 그린것이 아래그림이다. (선의 너비는 그 component에 포함된 데이터의 수)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;condensed_tree_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085117-b37f2c00-9773-11e9-8664-9fb8cec51d42.png&quot; alt=&quot;output_17_1&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;extract-the-stable-clusters-from-the-condensed-tree&quot;&gt;Extract the stable clusters from the condensed tree.&lt;/h2&gt;
&lt;p&gt;그러나 다한게 아니다. 이건 robust single linkage에서 noise같은 split을 처리해준거지, local density를 반영한게 아니다.&lt;/p&gt;

&lt;p&gt;결국 저거가지고, 클러스터를 만들어야 한다. 그림의 하단부분을 보면, 비록 minimum size를 만족하긴 했지만 아주 끄트머리가서 분할된 애들이 있다. 이들은, (원래 같은 클러스터의 데이터인데) 우연히 그 data들이 5개,5개씩 아주 살짝 더 뭉쳐있어서 떨어진것으로 볼 수도 있다. 즉, 우리가 찾는 이상적인 클러스터는 위의 그림에서 &lt;strong&gt;오랫동안 지속되왔던 줄기들&lt;/strong&gt;이다. 이러한 직관을 수식으로 정리하여 cluster를 만들어준것이 HDBSCAN이다.&lt;/p&gt;

&lt;p&gt;위의 덴드로그램에서 y축을 마치 위에서 부터 시작해서 아래로 내려오는 시간축 처럼 보자. y축을 따라 내려오면서, 클러스터가 분할되어 &lt;strong&gt;새로운 클러스터가 생기고(birth)&lt;/strong&gt;, 그중 noise로 fell out 되는 데이터가 몇개씩 존재하다가, 결국 min_size이상의 &lt;strong&gt;2개의 클러스터로 분할(death)&lt;/strong&gt;된다. (물론 구분안되고 끝가지 갈수도 있다.) (여기서 noise로 fell out 되는 것은 기준distance를 만족시키지 못하지만 또 min_size를 만족하지 못한 데이터들이다. min_size를 만족하는 데이터 군들의 edge가 끊길 경우, 이는 클러스터의 분할로 본다)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;분할, 혹은 탄생의 시점을 재는 측도로써, (분할 혹은 탄생될 때의) distance가 아닌 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 사용하게 된다. 이때, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;는 mutual reachability distance의 역수이다.(즉 &lt;script type=&quot;math/tex&quot;&gt;\lambda=\frac{1}{distance}&lt;/script&gt;)&lt;/p&gt;

  &lt;p&gt;local dense를 더 잘 표현해주기 위해 작은 distance값엔 민감하게 반응하고 큰 값엔 둔감하게 반응하게 하기 위해 distance자체가 아닌 역수로 사용한듯 하다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;여기서, 우리가 찾고싶은 클러스터는 &lt;strong&gt;‘오래동안 살은’ 클러스터&lt;/strong&gt;이다. 이를 위해 각 cluster에 대해서, 그 클러스터가 탄생된 값을 $\lambda_{birth}$, 그 클러스터가 또다른 2개의 클러스터로 분할되는 시점을 $\lambda_{death}$라고 한다. 그리고 해당 클러스터내의 각 데이터에 대해서는, 그 데이터가 (만약 fell out 됬다면)  fell out되는 시점이 존재하는데 이를 $\lambda_{p}$라고 한다. (끝까지 남아있던애들은 당근 $\lambda_{p}=\lambda_{death}$)&lt;/p&gt;

&lt;p&gt;그럼 오래 살은 안정적인 클러스터들은, 데이터들이 오밀조질 연결되어 별로 떨어지지(fell out되지) 않다가, threshold를 너무나 줄여 &lt;strong&gt;억지로 떨어지는 클러스터들&lt;/strong&gt;일 것이다. 따라서 &lt;strong&gt;cluster의 안정성(stability)&lt;/strong&gt;를 다음과 같이 정의한다
&lt;script type=&quot;math/tex&quot;&gt;\sum_{p\in Cluster}(\lambda_p-\lambda_{birth})&lt;/script&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;이를 각각의 component에 대해서 모두 실행한다. (parents, child 가릴것 없이 아래서부터 위로 올라오며 모두 계산한다.)&lt;/li&gt;
  &lt;li&gt;아래에서 위로 올라가며 두개의 child cluster가 parents로 합쳐질때마다, 그 parents의 stability와 두 child cluster의 stability의 sum을 비교한다. &lt;strong&gt;child의 stability sum&lt;/strong&gt; 이 더 크면 2개의 child 를 클러스터로 유지하고, &lt;strong&gt;paranets의 stability&lt;/strong&gt;가 더 크면 parents를 클러스터로 인정한다.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;이를 아래에서 위로 전부다 훑게 되면, 최종적인 variable dense를 반영한 cluster들이 남게 된다!&lt;/p&gt;

&lt;p&gt;이를 그림으로 한것이 아래와 같다(동그라미쳐진 애들이 살아남은 클러스터)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;condensed_tree_&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;select_clusters&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;selection_palette&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085101-b11cd200-9773-11e9-868a-783821515947.png&quot; alt=&quot;output_20_1&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;결과물-및-각-데이터의-probability&quot;&gt;결과물 및 각 데이터의 probability&lt;/h2&gt;
&lt;p&gt;또한 부가기능으로 다음을 할 수 있다.
각 클러스터에 대해, 앞선 과정에서 구한 $\lambda_p$, 즉 클러스터에서 떨어져 나간 시점을 모아, (각 클러스터내에서) [0,1]에 오도록 scaling한다. 이 값이 큰 데이터들은 클러스터가 태어자마자마 fell out된 애들이므로, 이를 &lt;strong&gt;‘해당 클러스터에 속할 확률’&lt;/strong&gt;으로 해석할 수도 있다.(굳이. 좀더 있어보이려고)&lt;/p&gt;

&lt;p&gt;아래의 그림은 이를 활용하여, 각 점들을 클러스터별 색깔로 표시하되 &lt;strong&gt;속할확률이 작은 데이터들&lt;/strong&gt;은 그 색을 desaturate하여 회색에 가깝게 표현한 fancy한 그림이다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;desaturate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sat&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
                  &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probabilities_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085102-b1b56880-9773-11e9-9470-465ee39f63af.png&quot; alt=&quot;output_22_1&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;dbscan과-비교&quot;&gt;DBSCAN과 비교&lt;/h1&gt;

&lt;p&gt;그럼 hdbscan이 실제 기존의 dbscan과는 얼마나 성능차이가 날까? 이를 위해 같은 예시데이터에 대해, sklearn의 dbscan과 비교해보았다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;sklearn.cluster&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rcParams&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;figure.figsize&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085103-b1b56880-9773-11e9-91a0-151d5ab07ca4.png&quot; alt=&quot;output_26_1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;반달형보다는 오히려 타원의 밀집한 부분만을 잡아낸다. DBSCAN은 &lt;strong&gt;epsilon안의 (절대적인) 데이터수&lt;/strong&gt;로 따지니까 타원형태가 더 유리할것같다.&lt;/p&gt;

&lt;p&gt;이번엔, 하이퍼파라미터 eps를 좀더 조정해보자.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;sklearn.cluster&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085104-b1b56880-9773-11e9-9e10-7679b7097149.png&quot; alt=&quot;output_29_1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;모든 클러스터를 잡아내긴 하지만, 역시나 &lt;strong&gt;variable dense에 제대로 적응하지 못하고&lt;/strong&gt; 몇개의 데이터를 noise라고 잡아낸다. 이는 각 데이터가 다른 클러스터에 비해서는 멀리떨어져 있는데, 이를 &lt;strong&gt;절대적인 epsilon&lt;/strong&gt;으로 잡아내려하면서 생긴 문제라고 할 수 있다&lt;/p&gt;

&lt;h1 id=&quot;dbscan과-비교2&quot;&gt;DBSCAN과 비교2&lt;/h1&gt;

&lt;p&gt;좀더 극단적인 variable dense의 case로 다시한번 비교를 시도해보자&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#moons, _ = data.make_moons(n_samples=num, noise=0.1)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blobs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;make_blobs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;20.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;20.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cluster_std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;blobs2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;make_blobs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cluster_std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blobs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;blobs2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'b'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085105-b1b56880-9773-11e9-9d50-3019ba52e6b8.png&quot; alt=&quot;output_32_0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;가운데의 &lt;strong&gt;매우 sparse한 집단&lt;/strong&gt;과, 위아래로 &lt;strong&gt;매우 dense한 집단&lt;/strong&gt;이 2개 있는 데이터이다.&lt;/p&gt;

&lt;h2 id=&quot;dbscan의-경우&quot;&gt;DBSCAN의 경우&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;sklearn.cluster&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085106-b24dff00-9773-11e9-983b-56807729efdf.png&quot; alt=&quot;output_35_1&quot; /&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;sklearn.cluster&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;husl&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085107-b24dff00-9773-11e9-9465-bb9a126d144b.png&quot; alt=&quot;output_37_1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;같은 setting하에서, variable dense를 잘 못잡는다. 그럼 파타미터 튜닝을 해볼까?&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;sklearn.cluster&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;db&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DBSCAN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;husl&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085109-b24dff00-9773-11e9-833e-ed890ed3a657.png&quot; alt=&quot;output_40_1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;결과는 하나만 제시했지만, 여러값을 시도해보았을때 저게 최선이었다. 한눈에 봐도, variable dense를 잡지못하고 고정된 &lt;strong&gt;eps안에서 잡으려 하기에&lt;/strong&gt; 차이가 있음을 알 수 있다.&lt;/p&gt;

&lt;h2 id=&quot;hdbscan의-경우&quot;&gt;HDBSCAN의 경우&lt;/h2&gt;

&lt;p&gt;아래는 파라미터를 바꿔 시도해본 HDBSCAN이다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hdbscan&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;HDBSCAN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_cluster_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gen_min_span_tree&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;desaturate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sat&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
                  &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probabilities_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085110-b2e69580-9773-11e9-83c9-d10c3497fd24.png&quot; alt=&quot;output_43_1&quot; /&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hdbscan&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;HDBSCAN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_cluster_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gen_min_span_tree&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color_palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;husl&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sns&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;desaturate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;palette&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                  &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;col&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sat&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt;
                  &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusterer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probabilities_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster_colors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot_kwds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/60085112-b2e69580-9773-11e9-881e-ccebaefae859.png&quot; alt=&quot;output_44_1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;서로 다른 두 parameter의 경우에서, 모두 variabel dense를 잡아낸것을 볼 수 있다!&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;참조&lt;/p&gt;

&lt;p&gt;파이선 HDBSCAN 패키지 : &lt;a href=&quot;https://hdbscan.readthedocs.io/en/latest/how_hdbscan_works.html&quot;&gt;https://hdbscan.readthedocs.io/en/latest/how_hdbscan_works.html&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;참조 코드 원문 : https://nbviewer.jupyter.org/github/scikit-learn-contrib/hdbscan/blob/master/notebooks/How%20HDBSCAN%20Works.ipynb#How-HDBSCAN-Works&lt;/p&gt;

</description>
        <pubDate>Mon, 15 Jul 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/07/15/HDBSCAN-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-(with-python).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/07/15/HDBSCAN-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-(with-python).html</guid>
        
        <category>HDBSCAN</category>
        
        <category>DBSCAN</category>
        
        <category>clustering</category>
        
        <category>outlier detection</category>
        
        <category>python implementation</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[cheat sheet] Open API 활용방법 정리(with Python) </title>
        <description>
&lt;p&gt;버스 실시간 도착정보 데이터를  open API로 불러올 것이다.&lt;/p&gt;

&lt;p&gt;사용할 api의 주소 : https://www.data.go.kr/dataset/15000314/openapi.do&lt;/p&gt;

&lt;p&gt;API에서 제공하는 서비스 리스트&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;getArrInfoByRouteAllList - 경유노선 전체 정류소 도착예정정보를 조회한다&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;getArrInfoByRouteList - 한 정류소의 특정노선의 도착예정정보를 조회한다&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;getLowArrInfoByStIdList - 정류소ID로 저상버스 도착예정정보를 조회한다&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;getLowArrInfoByRouteList - 한 정류소의 특정노선의 저상버스 도착예정정보를 조회한다&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;자료-요청-방식-step-by-step&quot;&gt;자료 요청 방식 (step by step)&lt;/h2&gt;

&lt;p&gt;앞서 설명한대로, url을 호출하면 xml형태의 데이터를 반환해줍니다. 
입력해주어야 하는 요청파라미터는 서비스별로 정의되어 있으며(doc에 있음) 여기서는 &lt;strong&gt;‘특정 버스의 전체 정류장 정보’&lt;/strong&gt;를 불러올 것입니다. 
따라서 &lt;strong&gt;인증키&lt;/strong&gt;와 &lt;strong&gt;루트ID&lt;/strong&gt;가 필요합니다.&lt;/p&gt;

&lt;p&gt;따라서 예시는 다음과 같습니다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;예시 URL : http://ws.bus.go.kr/api/rest/arrive/getArrInfoByRouteAll?ServiceKey=인증키&amp;amp;busRouteId=100100118&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;필요한 모듈을 불러옵니다&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;pandas&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;bs4&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;BeautifulSoup&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;requests&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;time&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ol&gt;
  &lt;li&gt;요청파라미터로 넣어줄 값들을 설정합니다&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'put_your_service_key_here'&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;### 여기에 신청한 본인의 key를 넣어야 합니다!
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;busRouteId&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'100100118'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ol&gt;
  &lt;li&gt;doc에 적혀있는 end-point url과 나의 요청파라마터를 합해주어 최종적인 url을 만듭니다.&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;queryParams&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'ServiceKey='&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'&amp;amp;busRouteId='&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;busRouteId&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;url&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'http://ws.bus.go.kr/api/rest/arrive/getArrInfoByRouteAll?'&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;queryParams&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;http://ws.bus.go.kr/api/rest/arrive/getArrInfoByRouteAll?ServiceKey=put_your_service_key_here&amp;amp;busRouteId=100100118 3. 앞서 Import한 request의 get메소드를 이용하여 respond를 받습니다. (받아온 객체는 Response객체로, 활용을 위해선 추가의 처리를 필요로 합니다)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;req&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requests&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; 
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;class 'requests.models.Response'&amp;gt; 4. 이 response객체를 텍스트로 변환. 이제 다음과 같이 xml형태의 데이터를 string으로 확인할 수 있습니다.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;html&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt; 
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;html&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#이제 string객체로 바꼈다.
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;html&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#이렇게 내용물을 확인할 수 있다.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;class 'str'&amp;gt;
&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&amp;gt;&amp;lt;ServiceResult&amp;gt;&amp;lt;comMsgHeader/&amp;gt;&amp;lt;msgHeader&amp;gt;&amp;lt;headerCd&amp;gt;0&amp;lt;/headerCd&amp;gt;&amp;lt;headerMsg&amp;gt;정상적으로 처리되었습니다.&amp;lt;/heade
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ol&gt;
  &lt;li&gt;아직 xml형태를 가진 문서를 string으로 바꾼것이기 때문에, 이 중 사용할 데이터를 잘끄집에 내야합니다. 이때 xml의 구조를 알아서 알아서 잘 파악하는 html parser가 잇습니다. 여기서는 Beautifulsoup의 html parser를 이용합니다.&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;soup&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;BeautifulSoup&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;html&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'html.parser'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;ol&gt;
  &lt;li&gt;이제 xml형태를 인식할 수 있게 됬기에, 내가 원하는 attribute를 find_all함수를 이용하여 불러올수 있습니다&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;finded_values&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;soup&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;find_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'stnm'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;finded_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# .text를 통해 안의 내용물만을 불러옵니다
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;['선진운수종점', '구산동사거리', '한솔아파트입구선정중학교후문', '갈현동미미아파트', '선일여고입구']
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;이제-실제-예시-toy-code&quot;&gt;이제 실제 예시 (Toy code)&lt;/h2&gt;

&lt;p&gt;이번에는 다양한 parameter값을 넣어 데이터를 불러오고, xml을 파싱한후, 판다스 dataframe으로 만드는 전체 과정에 대해 코드를 짜봅니다.&lt;/p&gt;

&lt;p&gt;(&lt;strong&gt;앞선 api는 서울시교통정보과에서 만든 api (&lt;a href=&quot;https://www.data.go.kr/dataset/15000314/openapi.do&quot;&gt;주소&lt;/a&gt;)이고, 아래의 api는 &lt;a href=&quot;http://data.seoul.go.kr/dataList/datasetView.do?infId=OA-12913&amp;amp;srvType=S&amp;amp;serviceKind=1&amp;amp;currentPageNo=2&amp;amp;searchValue=&amp;amp;searchKey=null&quot;&gt;서울시열린데이터광장&lt;/a&gt;에서의 api이다. url의 연결방법이 매 사이트마다 조금 다르다는걸 유의하세요!&lt;/strong&gt;)&lt;/p&gt;

&lt;p&gt;여기서는 각 정류장의 정보를 startnumber~endnumber로 지정하여, 1~2000번째 정류장을 for문을 이용하여 불러보고, 이를 판다스 DataFrame으로 바꾸고 저장합니다&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;startnumber&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;endnumber&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;CommerceInfor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;endnumber&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'getting data from &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s to &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s'&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;startnumber&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;endnumber&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'http://openapi.seoul.go.kr:8088/put_your_service_key_here/xml/GetParkInfo/'&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;startnumber&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'/'&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;str&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;endnumber&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'/'&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;req&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requests&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;url&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;html&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;soup&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;BeautifulSoup&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;html&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;'html.parser'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  
  &lt;span class=&quot;n&quot;&gt;attr_to_find_list&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'parking_code'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'parking_name'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'addr'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'parking_type'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'que_status'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'capacity'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'cur_parking'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'pay_yn'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'rates'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'add_rates'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;each_attr&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attr_to_find_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;finded_attr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;soup&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;find_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;each_attr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;CommerceInfor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;each_attr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;CommerceInfor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;each_attr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;finded_attr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;CommerceInfor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;each_attr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CommerceInfor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;each_attr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;finded_attr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;startnumber&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;endnumber&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;
    
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'end!'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pd&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DataFrame&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CommerceInfor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;getting data from 1 to 1000
getting data from 1001 to 2000
end!
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;결과를 확인해 봅니다&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;df&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;head&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;parking_code&lt;/th&gt;
      &lt;th&gt;parking_name&lt;/th&gt;
      &lt;th&gt;addr&lt;/th&gt;
      &lt;th&gt;parking_type&lt;/th&gt;
      &lt;th&gt;que_status&lt;/th&gt;
      &lt;th&gt;capacity&lt;/th&gt;
      &lt;th&gt;cur_parking&lt;/th&gt;
      &lt;th&gt;pay_yn&lt;/th&gt;
      &lt;th&gt;rates&lt;/th&gt;
      &lt;th&gt;add_rates&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;1369476&lt;/td&gt;
      &lt;td&gt;탑골공원 버스전용주차장(시)&lt;/td&gt;
      &lt;td&gt;종로구 종로2가 38-4&lt;/td&gt;
      &lt;td&gt;NS&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;N&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;1369476&lt;/td&gt;
      &lt;td&gt;탑골공원 버스전용주차장(시)&lt;/td&gt;
      &lt;td&gt;종로구 종로2가 38-4&lt;/td&gt;
      &lt;td&gt;NS&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;N&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;1384878&lt;/td&gt;
      &lt;td&gt;교육청길(구)&lt;/td&gt;
      &lt;td&gt;강북구 미아동 137-19&lt;/td&gt;
      &lt;td&gt;NS&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;94&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;Y&lt;/td&gt;
      &lt;td&gt;200&lt;/td&gt;
      &lt;td&gt;200&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;1384878&lt;/td&gt;
      &lt;td&gt;교육청길(구)&lt;/td&gt;
      &lt;td&gt;강북구 미아동 137-19&lt;/td&gt;
      &lt;td&gt;NS&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;94&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;Y&lt;/td&gt;
      &lt;td&gt;200&lt;/td&gt;
      &lt;td&gt;200&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;1384878&lt;/td&gt;
      &lt;td&gt;교육청길(구)&lt;/td&gt;
      &lt;td&gt;강북구 미아동 137-19&lt;/td&gt;
      &lt;td&gt;NS&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;94&lt;/td&gt;
      &lt;td&gt;0&lt;/td&gt;
      &lt;td&gt;Y&lt;/td&gt;
      &lt;td&gt;200&lt;/td&gt;
      &lt;td&gt;200&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;잘 작동합니다! time을 이용하여 다음과 같이 자동으로 저장하는 등의 활용을 해볼 수 있습니다&lt;/p&gt;

&lt;p&gt;if time % 600==0:
  df.to_excel(‘auto_save’ + str(cnt) + ‘.xlsx’, sheet_name = ‘sheet1’)&lt;/p&gt;
</description>
        <pubDate>Sun, 02 Jun 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EC%BD%94%EB%94%A9cheat%20sheet/2019/06/02/Open-API-%ED%99%9C%EC%9A%A9%EB%B0%A9%EB%B2%95-%EC%A0%95%EB%A6%AC(with-Python).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EC%BD%94%EB%94%A9cheat%20sheet/2019/06/02/Open-API-%ED%99%9C%EC%9A%A9%EB%B0%A9%EB%B2%95-%EC%A0%95%EB%A6%AC(with-Python).html</guid>
        
        <category>cheating sheet</category>
        
        <category>open api</category>
        
        <category>REST</category>
        
        <category>python</category>
        
        
        <category>코딩cheat sheet</category>
        
      </item>
    
      <item>
        <title>[cheat sheet] Open API 활용방법 정리(간단 설명)</title>
        <description>
&lt;h2 id=&quot;서론&quot;&gt;서론&lt;/h2&gt;

&lt;p&gt;공공데이터 포털등 다양한 사이트에서 open API로 정보를 활용할 수 있도록 해놓았다. 다양한 데이터를 만져볼 수 있다는 점에서도 그렇고, 요새는 open api활용 경험이 프로그래머들에겐 기초교양같은 느낌이라, 다들 한번쯤은 접하는것 같다. 그러나 활용방법에, 간략한 설명을 써놓았지만 처음 접하는 사람은 알아보기 힘들다.(바로 나)&lt;/p&gt;

&lt;p&gt;내가 활용하면서 얻은 지식을 정리해보았다.&lt;/p&gt;

&lt;h2 id=&quot;본론&quot;&gt;본론&lt;/h2&gt;

&lt;p&gt;우선, Open API는 다양한 방식으로 활용권한을 부여하지만 가장 기본적이고 대중적으로 허가받은 유저에게 service키를 발급한다. 따라서 open api를 활용하기 위해선 보통 신청을 하고(간략하게 활용목적도 적는다.) 키(key)를 발급받는다.&lt;/p&gt;

&lt;p&gt;그럼 그 키를 어떻게 써먹는가? 이는 API의 유형이 따라 다르다. 대부분 SOAP혹은 REST 유형을 가지고 있다. SOAP가 REST에 대한 &lt;a href=&quot;http://blog.naver.com/PostView.nhn?blogId=islove8587&amp;amp;logNo=220431962636&quot;&gt;요약된 설명1&lt;/a&gt;, &lt;a href=&quot;https://www.slideshare.net/seunghochoi4/soap-restful&quot;&gt;설명2&lt;/a&gt;. 간단하게 설명하면 다음과 같다.&lt;/p&gt;

&lt;h4 id=&quot;soap-과-rest-비교&quot;&gt;SOAP 과 REST 비교&lt;/h4&gt;

&lt;h4 id=&quot;soap란&quot;&gt;SOAP란&lt;/h4&gt;

&lt;p&gt;SOAP는 HTTP, HTTPS, SMTP 등을 통해 &lt;strong&gt;XML 기반의 메시지&lt;/strong&gt;를 컴퓨터 네트워크 상에서 교환하는 프로토콜이다. XML로 만들어진 웹서비스의 데이터를, WSDL라는 이름의 웹표준형태로 정의하여 UDDI라는 일종의 전역적 저장소에 등록하여 이용가능도록 만든 것이다. (사용의 목적에 초점을 두었기에, 전문적 용어는 간단히 접하고 넘어가도 무방하다.) SOAP를 통해 교환데는 XML데이터는 SOAP Envelope, SOAP Header, SOAP Body로 구성된다.&lt;/p&gt;

&lt;p&gt;장점 : &lt;strong&gt;분산 컴퓨팅환경을 다루기 위해 설계&lt;/strong&gt;되어 있고, 다양한 &lt;strong&gt;표준규약에 익숙한 경우 많은 확장&lt;/strong&gt;을 할 수 있다는 장점이 있다.&lt;/p&gt;

&lt;p&gt;단점 : 복잡한 구조를 가지고 있어서 &lt;strong&gt;HTTP상에서 바로 전달되기 무겁&lt;/strong&gt;고, 인코딩/디코딩 과정등 &lt;strong&gt;처리(혹은 개발)하는데에 난이도가 높다&lt;/strong&gt;. 또한, 사용을 위해 &lt;strong&gt;별도의 개발환경(Tool)이 필요&lt;/strong&gt;하다.&lt;/p&gt;

&lt;h4 id=&quot;rest란&quot;&gt;REST란&lt;/h4&gt;

&lt;p&gt;REST는 HTTP 프로토콜로 데이터를 전달하는 프레임워크이다. 단순한 HTTP 요청과 그 결과를 단순한 XML등의 포맷으로 돌려주는 구조이다. UDDI를 통해 등록하고, 탐색하는 등의 과정을 거치는 SOAP기반 서비스와 다르게, REST는 중간 매개체 없이 리소스제공자가 직접 리소스 요청자에게 제공을 할 수 있어, 간단하다. REST원리를 따르는 시스템을 종종 RESTful이라는 용어로 지칭(거의 같은의미로 봐도 된다.)&lt;/p&gt;

&lt;p&gt;장점 : SOAP보다 처리(및 개발)가 &lt;strong&gt;쉽다&lt;/strong&gt;.  (RESTful웹서비스는 인터넷 서비스업체들이 응용개발자들에게 &lt;strong&gt;손쉬운 데이터제공을 목적&lt;/strong&gt;으로 시작되었다.)&lt;/p&gt;

&lt;p&gt;단점 : SOAP와 반대로 표준규격이 부족하여 함축적이지 않고 안정성이 덜하다.&lt;/p&gt;

&lt;p&gt;API를 처음 접하는 사람입장에서, SOAP는 다루기 어려운것이라고 이해하면 된다. 그렇기 때문에 요새는 거의 &lt;strong&gt;REST가 장악&lt;/strong&gt;했다고 보면 된다. (흔히 SOAP vs REST를 표준vs간결함 으로 표현한다. 파이썬이 뜨고 있듯, 웹상에서도 간결함이 특징인 REST가 뜨고 있다.)  따라서 API의 사용법 역시 REST에 기반한 API제공에 초점을 둔다. (대부분의 API가 REST형태일 것이다.)&lt;/p&gt;

&lt;h3 id=&quot;본격적인-api활용법&quot;&gt;본격적인 API활용법&lt;/h3&gt;

&lt;p&gt;api를 신청하던 그 페이지에 들어가 보면, 보통 참고문서, 혹은 활용매뉴얼 등의 이름으로 각 api마다 문서가 있다. 뭐라뭐라 길게 씌여 있는데, 이 중 우리에게 필요한것은 &lt;strong&gt;url end-point&lt;/strong&gt;와 그에 덧붙여질 &lt;strong&gt;요청파라미터&lt;/strong&gt;들이다. 문서를 보면 이렇게 씌여 있을 것이다.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;내용&lt;/th&gt;
      &lt;th&gt;행사정보를 날짜로 조회하는 기능입니다&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;형식(혹은 URL end-point)&lt;/td&gt;
      &lt;td&gt;http://api.visitkorea.or.kr/openapi/service/rest/KorService/searchFestival&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;여기서 형식의 url을 활용하는 것인데, 저것은 앞문장만 완성시켜 놓은것이다. 따라서 우리가 필요한 &lt;strong&gt;인자정보&lt;/strong&gt;들을 적어서 최종적인 url을 만들면 된다. 인자정보들은 말그대로 구체적인 요청을 내리기 위한 parameter들인데, 자신의 키값(필수)과 요청할 항목들(request parameter)을 명시해주는 것이다. 즉, 해당 예시에선 다음과 같이 url을 만들면 된다.&lt;/p&gt;

&lt;p&gt;http://api.visitkorea.or.kr/openapi/service/rest/KorService/searchFestival?ServiceKey=자신의키값&amp;amp;Request_Parameter_항목명1=값1&amp;amp;Request_Parameter_항목명2=값2&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;공공데이터 포털의 Url도 &lt;strong&gt;상세기능 뒤에는 ?을 사용&lt;/strong&gt;하여 기본인자 정보들을 적고, &lt;strong&gt;기본인자사이에는 &amp;amp;을 붙여 구분&lt;/strong&gt;지어준다. 그러나 제공하는 api마다 상세한 방식은 다를 수 있으니, doc을 꼭 읽어봐야 한다. (그냥 ‘/a/b/c’ 이렇게 붙이는 경우도 있다.)
(상세기능은 Festival등등 카테고리라고 보면 되고, 인자는 dateTerm, serviceKey등등)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;문서를 조금더 내려보면, url end-point를 설명한 후 추가로 적을 인자정보들을 소개하고 잇을 것이다. api마다의 요청 파라미터값은 api doc에 자세히 나와있으니 자신이 필요한 요청값을 서비스키값 뒤로 적절히 붙여 요청하면 된다. (사실 순서는 중요하지 않다. 항목명1값뒤에 키값이 와도 된다.)&lt;/p&gt;

&lt;p&gt;또한, Request Parameter 중 필수 항목은 꼭 들어가야하는 파라미터항목으로 없으면 에러가 난다. (‘필수’라고 적힌 부분이 있는지 api doc을 확인해보자.)&lt;/p&gt;

&lt;p&gt;기본적으로 REST방법은 이렇게 만들어진 최종 url을 입력하면, 즉 &lt;strong&gt;request&lt;/strong&gt;를 보내면 &lt;strong&gt;respond&lt;/strong&gt;를 준다. 이 respond는 xml형식일수도, json형식일수도 있다. (doc에서 명시해줄것이다.)&lt;/p&gt;

&lt;p&gt;이렇게 가장 간단하게는, 해당 &lt;strong&gt;url을 브라우저에 입력&lt;/strong&gt;하여 respond를 받는것이다. (그냥 구글크롬에다 해당 url치면 respond된 값이 크롬창에 뜨게 된다.  그러나 대부분의 경우 단일 정보를 보는것이 아니라 &lt;strong&gt;다양한 정보들을 수집&lt;/strong&gt;하고 싶을 것이다. 이 경우 url을 지정하면 해당 request를 보내고 respond를 받고, 그 반환된 데이터(xml이던 json이던 형태에 맞춰서)를 정리 및 저장하는 다양한 패키지들이 있다. (R에서는 RCurl, Python에서는 BeutifulSoup등이 있다.) 해당 패키지들을 이용하여 반환받은 데이터를 구조를 파악하고, 그중 원하는 데이터만을 정리 및 저장해주는 코드를 짜주면 open API활용 완성!&lt;/p&gt;

&lt;p&gt;R에서 정리 및 저장하는 코드는 링크로 달아놓았다.&lt;/p&gt;

&lt;p&gt;파이썬으로 정리 및 저장하는 코드는 다음에 해보겠다.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;R에서 코드짜는것 예시 : https://magician-of-c.tistory.com/36?category=250800&lt;/p&gt;

&lt;p&gt;완전 자세한 사진설명 + java 코드 : https://jeong-pro.tistory.com/143&lt;/p&gt;

&lt;p&gt;또다른 자세한 사진설명 + java 코드 : https://shlee0882.tistory.com/2&lt;/p&gt;

&lt;p&gt;SOAP과 REST에 대한 차이점 요약한 사이트 : http://blog.naver.com/PostView.nhn?blogId=islove8587&amp;amp;logNo=220431962636&lt;/p&gt;

</description>
        <pubDate>Wed, 22 May 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EC%BD%94%EB%94%A9cheat%20sheet/2019/05/22/Open-API-%ED%99%9C%EC%9A%A9%EB%B0%A9%EB%B2%95-%EC%A0%95%EB%A6%AC(%EA%B0%84%EB%8B%A8-%EC%84%A4%EB%AA%85).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EC%BD%94%EB%94%A9cheat%20sheet/2019/05/22/Open-API-%ED%99%9C%EC%9A%A9%EB%B0%A9%EB%B2%95-%EC%A0%95%EB%A6%AC(%EA%B0%84%EB%8B%A8-%EC%84%A4%EB%AA%85).html</guid>
        
        <category>cheating sheet</category>
        
        <category>open api</category>
        
        <category>REST</category>
        
        
        <category>코딩cheat sheet</category>
        
      </item>
    
      <item>
        <title>[interpretable machine learning] Individual Conditional Expectation 개인적 정리</title>
        <description>&lt;p&gt;해당 글은 앞선 정리글인 PDP에 이어지는 내용입니다. 더 나은 이해를 위해 &lt;a href=&quot;https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/04/13/Partial-Depedence-Plot.html&quot;&gt;PDP&lt;/a&gt;글을 한번 읽어보시기 바랍니다.&lt;/p&gt;

&lt;p&gt;앞선 글에서 black box 모델에서 변수의 영향을 근사적으로 파악하기 위한 방법을 PDP를 다뤘다. 이번엔 pdp의 단점들을 보완하기 위한 방법들에 대해 다뤄본다. 구체적으로 Individual Conditional Expectation (ICE)와 Centered ICE Plot이다.&lt;/p&gt;

&lt;h1 id=&quot;individual-conditional-expectation-ice&quot;&gt;Individual Conditional Expectation (ICE)&lt;/h1&gt;

&lt;p&gt;앞서 다룬 Partial dependency plot은 모든 train data에 대해 예측값을 평균 내어 관심변수의 영향력을 근사하였다. 그러나 이 평균, 즉 통합에서 오는 문제가 있다. 예를 들어 분포가 매우 skewed 되어 있는 경우, mean은 오히려 직관적이지 못한 대표값을 만들어낼 수 있다.&lt;/p&gt;

&lt;p&gt;‘통합’으로 인해 생기는 문제를 보완하기 위한것이 individual conditional expectation curves이므로, 해결책은 간단하다. 각각의 데이터에 대해서 관심변수 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt; 가 변화될때 어떻게 예측값이 변하는지를, &lt;strong&gt;모든 train데이터에 대해 보여주는 것&lt;/strong&gt;. 즉, PDP는 ICE의 각 line을 average취한 하나의 선이다.  식으로 표현하면 엄청 간단한데, 특정 데이터i에 대해서 ICE line은 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;f(X_s)^{(i)}=f(X_s,X_c^{(i)}), i=1,2,..,n&lt;/script&gt;

&lt;p&gt;여기서 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;값을 이리저리 넣는것.&lt;/p&gt;

&lt;p&gt;과정을 좀더 상세하게 설명해보자면 다음과 같다.&lt;/p&gt;

&lt;p&gt;크기 (n X q)의 데이터 matrix 에서, 다른 변수들 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;에 관련된 컬럼들은 그대로 두고, 관심변수 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;를 feature space에 lower bound에서부터 upper bound까지 값을 바꾼다. (각 &lt;script type=&quot;math/tex&quot;&gt;x_s&lt;/script&gt;의 값 하나당 (n X q)의 matrix가 만들어지는 셈) 이를 mean을 취하면 그게 pdp의 &lt;script type=&quot;math/tex&quot;&gt;f(X_s)&lt;/script&gt;, 이를 그냥 다 그림에 때려박으면 ICE의 &lt;script type=&quot;math/tex&quot;&gt;f(X_s)^{(i)}&lt;/script&gt;이다.&lt;/p&gt;

&lt;p&gt;그림으로 보면 바로 이해되는데, 다음과 같다. (아래의 선들을 average한게 PDP다)&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;545&quot; alt=&quot;ICE plot&quot; src=&quot;https://user-images.githubusercontent.com/31824102/55941019-4a137500-5c7c-11e9-8f3d-4f35c2d06712.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이를 보면 대부분의 데이터들에 대해 결과값 (predicted cancer probability)가 0.0~0.1 정도에 몰려 있음을 알 수 있다. 즉, 상당히 right skewed된 형태이다. 그러나 이를 mean을 취하면, 0.4를 넘는 몇몇의 극단값들에 의해 의미가 왜곡될 수 있다. (예를 들어 평균값이 0.2정도 나온다던지) 따라서 단순하게, 모든 train data에 대해 line을 그려본다. 이를 통해 PDP에선 발견하지 못했던 상세한 관계를 발견할수 있게 된다.&lt;/p&gt;

&lt;p&gt;&amp;lt; 단점 &amp;gt;&lt;/p&gt;

&lt;p&gt;그러나 여전히 같은 주의할점이 있다. (앞선 pdp와 같이,)실제 데이터 분포를 유의해야하고, 관심밖의 변수가 correlated되어 있을 경우 잘못된 결과가 나올 수 있다.&lt;/p&gt;

&lt;p&gt;그리고 추가적인 단점은 다음과 같다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;1차원밖에 못본다. 선을 여러개 그리는건 가능하지만, 면을 여러개 그리면 알아볼 수 없다. (사실상 50겹 크레이프)&lt;/li&gt;
  &lt;li&gt;데이터가 많으면, 당근 보기 힘들어진다. 그냥  검은도화지..&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;centered-ice-plot&quot;&gt;Centered ICE Plot&lt;/h1&gt;

&lt;p&gt;또다른 plot 방식이다. ICE가 너무 선들이 난잡해서, 그래서 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 따라 결국 예측값이 올라가는건지 아닌지 등 trend를 보기 힘들때가 있다. (위 그림에서 age 25~40정도가 그런 느낌이다.) 그래서 모든 ICE의 선을 (0,0)에서 시작하도록 만든것이 c-ICE plot 이다. 식은 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;f_{cent}(X_s)^{(i)}=f(X_s)^{(i)}-f(x^*,X_{c}^{(i)})=f(X_s,X_c^{(i)})-f(x^*,X_{c}^{(i)})&lt;/script&gt;

&lt;p&gt;예를 들어 위의 예시에서 보면 나이의 minimum값이 13인데, &lt;script type=&quot;math/tex&quot;&gt;x^*=13&lt;/script&gt;으로 해서 모든 i에 대해 &lt;script type=&quot;math/tex&quot;&gt;f_{cent}(13)^{(i)}=0&lt;/script&gt;이 되도록 하는 것이다. 이를 통해 평행선들의 고도차이를 없애주고 차이의 trend에 집중하게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;편의를 위해 minimum값으로 고정한다고 했지만 그냥 한점에서 만나면 되므로,&lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;의  maximum값등 암거나 &lt;script type=&quot;math/tex&quot;&gt;x^*&lt;/script&gt;가 될 수 있다. 그러나 (0,0)지나가는게 이쁘니까 minimum하자&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;그림으로 보면 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;548&quot; alt=&quot;ICE plot2&quot; src=&quot;https://user-images.githubusercontent.com/31824102/55941018-4a137500-5c7c-11e9-9564-abc782a3b9a3.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&amp;lt; 주의할점 &amp;gt;&lt;/p&gt;

&lt;p&gt;평행선들의 level을 모두 맞춰주고 그림을 그린것이기에, absolute prediction이 아닌, prediction의 trend에 관심이 있을때 활용해야한다는것이 주의하자.&lt;/p&gt;
</description>
        <pubDate>Mon, 29 Apr 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/04/29/Individual-Conditional-Expectation-(ICE).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/04/29/Individual-Conditional-Expectation-(ICE).html</guid>
        
        <category>black box</category>
        
        <category>Individual Conditional Expectation</category>
        
        <category>ICE</category>
        
        <category>Centered ICE</category>
        
        <category>interpretable machine learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[interpretable machine learning]Partial dependence plot 개인적 정리</title>
        <description>
&lt;h3 id=&quot;서론-모델의-해석에-관하여&quot;&gt;서론. 모델의 해석에 관하여&lt;/h3&gt;

&lt;p&gt;우리가 아는 모델은 2가지 관점, 즉 예측력과 해석력 측면에서 접근할 수 있다. 이 중, 예측력이 높은 복잡한 모델일 수록 해석력은 떨어진다고 할 수 있다. 대표적으로 딥러닝 모델들은 해당 변수가 어떻게 결과값에 영향을 주었는지 파악하고 활용하기가 상당히 힘들어진다. 이러한 특성에서 흔히 예측력이 높으나 해석이 힘들 모델을 &lt;strong&gt;black box&lt;/strong&gt;라고 부른다. 반면, 선형회귀 같이 전통적인 모델들은 예측성능은 비교적 떨어지지만, ‘&lt;strong&gt;변수 &lt;script type=&quot;math/tex&quot;&gt;X_1&lt;/script&gt;이 1 증가할때 결과값 &lt;script type=&quot;math/tex&quot;&gt;y&lt;/script&gt;가 몇 증가한다&lt;/strong&gt;’ 등 직관적인 해석이 가능하는 강점이 있다. 이에 따라 다양한 모델에(즉, 딥러닝이던 어떤 모델이던!) 범용적으로 적용이 가능하고 모델의 예측값과 input변수가 어떤 관계가 있었는지를 해석하려는 다양한 시도들이 있다. Partial dependence plot은 그중 대표적인 접근방법이다.&lt;/p&gt;

&lt;h2 id=&quot;partial-depedence-plot-pdp&quot;&gt;Partial Depedence Plot (PDP)&lt;/h2&gt;

&lt;h3 id=&quot;pdp란&quot;&gt;PDP란?&lt;/h3&gt;

&lt;p&gt;학습된 모델을 해석하는 방법중 하나. &lt;strong&gt;1개 혹은 2개의 변수&lt;/strong&gt;에 대해서 사용하여, 해당 변수가 target과 (학습된 모델하에서) 선형관계인지, 단조증가관계인지 등을 &lt;strong&gt;plot을 통해&lt;/strong&gt; 확인할 수 있다.&lt;/p&gt;

&lt;h3 id=&quot;수식과-함께-더-자세한-설명&quot;&gt;수식과 함께 더 자세한 설명&lt;/h3&gt;

&lt;p&gt;여러개의 피쳐들 &lt;script type=&quot;math/tex&quot;&gt;x_1,..,x_p&lt;/script&gt;중 우리가 effect를 보고 싶은 피쳐를 &lt;script type=&quot;math/tex&quot;&gt;x_s&lt;/script&gt;(selected), 그 외 선택되지 않은 피쳐를 &lt;script type=&quot;math/tex&quot;&gt;x_c&lt;/script&gt;(complement)라고 하자.&lt;/p&gt;

&lt;p&gt;즉 &lt;script type=&quot;math/tex&quot;&gt;X^T=(X_1,..,X_p)&lt;/script&gt;이고, &lt;script type=&quot;math/tex&quot;&gt;X=X_S\cup X_c&lt;/script&gt;일것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;왜 굳이 얘넬 나눌까? 지금 우리는 1개, 혹은 2개의 변수들에 대해 집중해서, 선택된 피쳐만의 함수로 만드는 중이다. 왜 1,2개의 변수에 집중할까? 변수를 1,2개로 집중할 경우 plot으로 그리기 수월해지고, 결과적으로 직관적으로 관계파악을 할 수 있게 된다. 선택된 변수 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;와 선택되지 않은 변수 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;간에 강한 상호작용이 없다면 이러한 접근은 충분히 좋은 근사를 보여줄 수 있다.&lt;/p&gt;

  &lt;p&gt;실제 분석에선 주로 feature importance를 통해 유의하게 나온 소수의 변수들이나 domain지식을 통해 중요할것이라 나온 변수들에 대해서 확인한다.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이때 모델이 학습한 관계는 &lt;script type=&quot;math/tex&quot;&gt;f(X)&lt;/script&gt;, 혹은 &lt;script type=&quot;math/tex&quot;&gt;f(X_s,X_c)&lt;/script&gt;라고 하면&lt;/p&gt;

&lt;p&gt;이중 우리의 관심 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 집중하는 방법은 여러가지가 있을 수 있지만, 그중 partial dependece가 취한 방법은 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;f_{X_s}(X_s)=E_{X_c}[f(X_s,X_c)]&lt;/script&gt;

&lt;p&gt;즉, 고정된 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 대해 모든 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;의 feature space 에서 &lt;script type=&quot;math/tex&quot;&gt;f(X_s,X_c)&lt;/script&gt;를 mean을 취하는 것이다.&lt;/p&gt;

&lt;p&gt;좀더 정확히 Expectation을 풀어써보면 다음과 같다. (단순히 expectation의 성질에 따라 식을 전개한것)&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;E_{X_c}[f(X_s,X_c)]=\int f(X_s,X_c)f_{X_c}(x_c)dx_c&lt;/script&gt;, 혹은 &lt;script type=&quot;math/tex&quot;&gt;E_{X_c}[f(X_s,X_c)]=\sum f(X_s,X_c)f_{X_c}(x_c)&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;(이때 &lt;script type=&quot;math/tex&quot;&gt;f(X_s,X_c)&lt;/script&gt;는 ‘예측값을 내뱉는 함수’이고, &lt;script type=&quot;math/tex&quot;&gt;f_{X_c}(x_c)&lt;/script&gt;는 해당 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;가 발현될 prob_density를 나타내는 pdf임을 주의하자)&lt;/p&gt;

&lt;p&gt;예를 들어, 몸무게와 키로 연봉을 예측하는 함수가 있다고 해보자. 즉 다음과 같다. ‘f(몸무게,키)=연봉’. 이때 몸무게만의 영향을 보기 위해, 모든 모집단 데이터에 대해 키의 분포를 알 고 있다면, (&lt;strong&gt;주어진 몸무게&lt;/strong&gt;, 키) 에 대한 모든 값들을 키의 pdf에 따라 평균 내는것. 만약 대한민국사람들의 키의 모집단 분포가 다음과 같고, 주어진 몸무게(예를들어 60)에서의 예측값이 다음과 같다면,&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;x&lt;/th&gt;
      &lt;th&gt;160&lt;/th&gt;
      &lt;th&gt;170&lt;/th&gt;
      &lt;th&gt;180&lt;/th&gt;
      &lt;th&gt;190&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;p(키=x)&lt;/td&gt;
      &lt;td&gt;4/8&lt;/td&gt;
      &lt;td&gt;2/8&lt;/td&gt;
      &lt;td&gt;1/8&lt;/td&gt;
      &lt;td&gt;1/8&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;f(주어진 몸무게60,키x)의 값 (연봉예측값)&lt;/td&gt;
      &lt;td&gt;150&lt;/td&gt;
      &lt;td&gt;200&lt;/td&gt;
      &lt;td&gt;300&lt;/td&gt;
      &lt;td&gt;250&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;f(몸무게60)=150*4/8+200*2/8+300*1/8+250*1/8=193.75&lt;/script&gt;가 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;해당 예시는 discrete한 변수들에 대해서의 예시이고, continuous에 대해선 당근 &lt;script type=&quot;math/tex&quot;&gt;\sum xf(x)&lt;/script&gt;가 아니라 &lt;script type=&quot;math/tex&quot;&gt;\int xf(x)dx&lt;/script&gt;가 된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;그러나 우리는 실제 데이터 &lt;script type=&quot;math/tex&quot;&gt;X_s,X_c&lt;/script&gt;들을 다 가지고 있지 않다. 또한 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;가 어떤 분포를 가지고 나타나는지, 즉 &lt;script type=&quot;math/tex&quot;&gt;f_{X_c}(x_c)&lt;/script&gt;도 알지 못한다. 그래서 실제로 우리가 &lt;script type=&quot;math/tex&quot;&gt;f(X_s)&lt;/script&gt;를 예측할때는 &lt;strong&gt;train data안에 있는 데이터들을 그대로 이용해서 &lt;script type=&quot;math/tex&quot;&gt;\hat {f_{X_c}}(x_c)&lt;/script&gt;을 구하고&lt;/strong&gt;, 이에 대해서 mean을 취해 partial effect를 구한다. 말이 어려운데, 결국 n개의 train data의 X_c를 각각 넣어보고 1/n으로 mean을 취하는 것이다. 이를 식으로 나타내보자.&lt;/p&gt;

&lt;p&gt;n개의 데이터가 있을 경우, 그들 데이터에 대해 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;값인 &lt;script type=&quot;math/tex&quot;&gt;x_{1c},..,x_{nc}&lt;/script&gt;가 있을 것이다. 이때, 추정된 partial dependence function은 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\hat f_{X_s}(X_s)=\frac{1}{n}\sum_i^nf(X_s,x_{ic})&lt;/script&gt;

&lt;p&gt;input으로 들어가는 &lt;script type=&quot;math/tex&quot;&gt;(X_s,x_{ic})&lt;/script&gt;는 함수가 만들어 졌으면(즉 모델이 적합되었으면) 어차피 우리가 암거나 넣을 수 있는 input자리이다. 정해진 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 대해서(예를들면 몸두게 60), 이 자리에 &lt;script type=&quot;math/tex&quot;&gt;(X_s,x_{1c}),..,(X_s,x_{nc})&lt;/script&gt;를 넣고 1/n한게 &lt;script type=&quot;math/tex&quot;&gt;\hat f_{X_s}(X_s)&lt;/script&gt;인것이다. 이를 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;가 존재할 수 있는 parameter space에 대해 (예를들면 몸무게 50kg~130kg)쭉 반복하면 최종적으로 &lt;script type=&quot;math/tex&quot;&gt;\hat f_{X_s}(X_s)&lt;/script&gt;를 추정하고, 그림을 그릴 수 있다. (앞서 언급했듯이 &lt;strong&gt;plot으로 확인&lt;/strong&gt;을 해보는 것이므로 &lt;script type=&quot;math/tex&quot;&gt;x_s&lt;/script&gt;는 주로 1개의 변수, 혹은 2개의 변수로 그 수가 정해진다. ) 이를 통해, &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;가 어떻게 변하는지에 따라 average prediction이 어떻게 변화하는지를 눈으로 확인할 수 있게 된다.&lt;/p&gt;

&lt;h3 id=&quot;사용법&quot;&gt;사용법&lt;/h3&gt;

&lt;p&gt;위의 알고리즘을 읽으면서 예상했다시피, 모든 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;의 feature space 에 대해 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;를 돌면서 예측을 해야하므로, 계산량이 엄청나다. 그래서 그런지 실제 구현도 그닥 예쁘게 되어 있는게 없다. (R은 랜포에만 있고, python은 xgb에만 있다.) python을 통해 그린 그림은 다음과 같다. (&lt;a href=&quot;https://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html&quot;&gt;사용법&lt;/a&gt;은 매우간단). 짜여진 효율적인 함수가 없으니, 필요할때 마다 내가 만들어 쓰자.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/55940980-3405b480-5c7c-11e9-97e3-4012a12620d3.png&quot; alt=&quot;sphx_glr_plot_partial_dependence_0011&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;앞서서 필요할때 만들어 쓰자고 했는데, 내가 필요해서 내가 만들어 썼다… X변수가 categorical인 경우와 continuous 인 경우 모두에 대해 작동할 수 있도록 함수를 짜보았다. (필요하신분 있으면 개인적으로 연락주세요)&lt;/p&gt;

  &lt;p&gt;사용 예시1. continuous에 대해 (왼쪽은 등고선그림, 오른쪽은 3D그림)&lt;/p&gt;

  &lt;p&gt;&lt;img width=&quot;680&quot; alt=&quot;PDP_self&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60665422-60a62280-9e9f-11e9-9456-0997d0d70276.PNG&quot; /&gt;&lt;/p&gt;

  &lt;p&gt;사용 예시2. categorical에 대해&lt;/p&gt;

  &lt;p&gt;&lt;img width=&quot;205&quot; alt=&quot;PDP_self2&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60665423-60a62280-9e9f-11e9-84db-1a528033fa0b.PNG&quot; /&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;이상적인-사용&quot;&gt;이상적인 사용&lt;/h3&gt;

&lt;p&gt;1,2개의 소수개의 변수에 대해서 관계를 확인하는 것이기에, 선택된 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;f(X)&lt;/script&gt;에서 &lt;strong&gt;dominate한 경우&lt;/strong&gt; 관계를 잘 approximate할 수 있다. (그렇기에 주로 &lt;strong&gt;중요할것이라 생각되는 변수에 대해서&lt;/strong&gt; 하게 된다) 혹은 &lt;script type=&quot;math/tex&quot;&gt;f(X)&lt;/script&gt;가 단순한 관계, 즉 low-order interaction을 가지고 있을때 판단하기 좋다. 즉, 단순히 nuisance feature &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;에 대해 simple mean을 취하는 것이기에, &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;와 &lt;strong&gt;강한 상관관계를 가지고 있지 않은 경우&lt;/strong&gt;에 이상적인 결과를 낼 수 있다.&lt;/p&gt;

&lt;h3 id=&quot;주의-할-점&quot;&gt;주의 할 점&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;전체의 train data에서 pdf &lt;script type=&quot;math/tex&quot;&gt;f(X_c)&lt;/script&gt;를 추정하고 그것에 대해 테스트한것이기에, 실제 데이터들이 어떻게 분포되었는지, 즉 &lt;strong&gt;feature distribution&lt;/strong&gt;에 대해선 고려를 하지 않았다. 예를들어 2차원 pdp로 키,몸무게~연봉을 보고자 할때 f(키=190,몸무게=21) 과 같이, 어린애의 몸무게도 test를 해보게 된다. (모델에 키=190,몸무게=21을 넣으면 예측값이 당근 반환되긴 할것이다. 그러나 이 예측값은 현실적으로 의미가 없고, 제대로 학습되엇을리도 없다. ) 즉, 실제 그 value들이 어떻게 분포되어있는지를 무시한것이고, 그림을 잘못해석 할 수있게 된다. 이를 위해 2차원 plot에서 &lt;strong&gt;실제 데이터의 분포&lt;/strong&gt;(혹은 rug)도 확인해야한다.&lt;/li&gt;
  &lt;li&gt;또한, &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;가 highly correlated되어 있다면, 잘못된 해석을 낳을 수 있다. 같은 예시에서 키=190인데 전체 몸무게의 distn으로 평가를 하여 몸무게=21의 확률도 현실보다 커지게 반영하는것. 이를 보완한것이 &lt;a href=&quot;https://christophm.github.io/interpretable-ml-book/ale.html#ale&quot;&gt;Accumulated Local Effect plots&lt;/a&gt; 이다.&lt;/li&gt;
  &lt;li&gt;이는 pdp보다는 mean(평균)의 문제이기도 한데, mean으로 인해 미처 보지못하는 효과가 있을 수도 있다. 예를 들어 데이터의 상위 50%는 positive한값, 하위 50%는 negative한 값이 나오면, 평균으로 나오는 &lt;script type=&quot;math/tex&quot;&gt;f(X_s)&lt;/script&gt;는 0에 가깝게 나와 효과가 없는것으로 보인다. 이처럼 ‘통합’으로 인해 생기는 문제를 보완하기 위한것이 &lt;a href=&quot;https://christophm.github.io/interpretable-ml-book/ice.html#ice&quot;&gt;individual conditional expectation curves&lt;/a&gt; 이다.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;덧&quot;&gt;덧.&lt;/h3&gt;

&lt;p&gt;아래의 내용은 이론적 측면에서의 주의점이다. 방법의 깊은 이해를 위해선 필요하지만 사용을 위해선 받아들이고만 넘어가도 좋은 부분이다.&lt;/p&gt;

&lt;p&gt;이때 PDP를 통해 나오는
&lt;script type=&quot;math/tex&quot;&gt;\hat f_{X_s}(X_s)&lt;/script&gt;
는 
&lt;script type=&quot;math/tex&quot;&gt;\tilde f_{X_s}(X_s)=E_{X_c| x_s}[f(X_s,X_c)|  x_s]&lt;/script&gt;
가 아님에 주의하자. (구분하기 위해 물결표를 위해 그렷다.) 미묘한 차이인데, &lt;script type=&quot;math/tex&quot;&gt;E_{X_c}[f(X_s,X_c)]=\sum f(X_s,X_c)f_{X_c}(x_c)&lt;/script&gt; 여기서 곱해지는 pdf가 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;만의 pdf &lt;script type=&quot;math/tex&quot;&gt;f_{X_c}(x_c)&lt;/script&gt;인지, 아님 주어진 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 대해 condition이 걸어진 conditional pdf 
&lt;script type=&quot;math/tex&quot;&gt;f(X_c| x_s)&lt;/script&gt;
인지의 차이이다.&lt;/p&gt;

&lt;p&gt;후자(Conditional pdf를 사용)의 경우 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;의 영향력을 무시한 (marginalize out한) &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;의 함수라고 할 수 있고, 전자(PDP)의 경우 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;의 effect를 (평균값으로라도) 고려해준  &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;의 함수라고 할 수 있다. 또한 후자의 경우,  &lt;script type=&quot;math/tex&quot;&gt;f(X)&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;와의 관계뿐 아니라 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;의 &lt;strong&gt;결합으로 생긴 관계도&lt;/strong&gt; 반영하게 되기 때문에, &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;가 결과값과 &lt;strong&gt;크게 관련이 없는 변수들일 경우에도 strong effect가 잡힐 수&lt;/strong&gt; 있다고 한다. (ESL370p) 혹은 &lt;a href=&quot;https://projecteuclid.org/download/pdf_1/euclid.aos/1013203451&quot;&gt;논문&lt;/a&gt; 자세한 이해를 위해 예시를 첨부한다.&lt;/p&gt;

&lt;p&gt;원문:  However, averaging over the conditional density , rather than the marginal density , causes &lt;script type=&quot;math/tex&quot;&gt;\tilde f_{X_s}(X_s)&lt;/script&gt; to reflect not only the dependence of &lt;script type=&quot;math/tex&quot;&gt;f(X)&lt;/script&gt; on the selected variable subset &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;, but in addition, apparent dependencies induced solely by the associations between &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;and the complement variables &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;.&lt;/p&gt;

&lt;p&gt;&amp;lt;예시 1&amp;gt;&lt;/p&gt;

&lt;p&gt;예를들어 실제 목적함수가 만약 선택된 변수 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;와 선택되지 않은 변수 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;가 서로 가법적(더하기)관계로 얽혀있었다고 해보자. 즉, &lt;script type=&quot;math/tex&quot;&gt;f(X)=h_1(X_s)+h_2(X_c)&lt;/script&gt;이다. 이경우 marginal pdf를 사용하는 PDP는 additive constant를 제외하고는, 실제 알고픈 함수 &lt;script type=&quot;math/tex&quot;&gt;h_1(X_s)&lt;/script&gt;를 복원할 수 있다.&lt;/p&gt;

&lt;p&gt;즉, &lt;script type=&quot;math/tex&quot;&gt;E_{X_c}[f(X)]=E_{X_c}[f(X_s,X_c)]=\int (h_1(X_s)+h_2(X_c))f_{X_c}(x_c)dx_c&lt;/script&gt;&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;=h_1(X_s)*\int f_{X_c}(x_c)dx_c+\int h_2(X_c)f_{X_c}(x_c)dx_c=h_1(X_s)+const&lt;/script&gt;

&lt;p&gt;위의 constant는 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;와 관계 없는 constant이기에, 모든 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 대해 동일하고, 따라서 특정 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;가 미치는 상대적 영향을 비교하는데에는 전혀 방해가 없다.&lt;/p&gt;

&lt;p&gt;반면, conditional pdf를 이용하는 방법의 경우, &lt;script type=&quot;math/tex&quot;&gt;h_1(X_s)&lt;/script&gt;를 복원하지 못한다.&lt;/p&gt;

&lt;p&gt;즉 
&lt;script type=&quot;math/tex&quot;&gt;E_{X_c| x_s}[f(X_s,X_c)| x_s]=\int (h_1(X_s)+h_2(X_c))f_{X_c| X_s}(x_c| X_s)dx_c&lt;/script&gt;&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;=h_1(X_s)+\int h_2(X_c)f_{X_c| X_s}(x_c| X_s)dx_c&lt;/script&gt;

&lt;p&gt;여기서 뒤의 항은 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 따라 값이 달라지는 값이고 즉 ,constant가 아니다. 이에 따라 각 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;마다 &lt;script type=&quot;math/tex&quot;&gt;h_1(X_s)&lt;/script&gt;를 복원하지 못하게 되고, &lt;strong&gt;뒤의 항때문에&lt;/strong&gt; 결과 해석에서 &lt;strong&gt;의도치 않은 영향을 해석하게 될수도&lt;/strong&gt; 있다.&lt;/p&gt;

&lt;p&gt;&amp;lt;예시 2&amp;gt;&lt;/p&gt;

&lt;p&gt;다음은 실제 목적함수가 만약 선택된 변수 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;와 선택되지 않은 변수 &lt;script type=&quot;math/tex&quot;&gt;X_c&lt;/script&gt;가 서로 승법적(곱하기)관계로 얽혀있었다고 해보자. 즉, &lt;script type=&quot;math/tex&quot;&gt;f(X)=h_1(X_s)*h_2(X_c)&lt;/script&gt;이다. 이경우 marginal pdf를 사용하는 PDP는 multiplicative constant를 제외하고는, 실제 알고픈 함수 &lt;script type=&quot;math/tex&quot;&gt;h_1(X_s)&lt;/script&gt;를 복원할 수 있다.&lt;/p&gt;

&lt;p&gt;즉 &lt;script type=&quot;math/tex&quot;&gt;E_{X_c}[f(X)]=E_{X_c}[f(X_s,X_c)]=\int (h_1(X_s)*h_2(X_c))f_{X_c}(x_c)dx_c&lt;/script&gt;&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;=h_1(X_s)*\int h_2(X_c)f_{X_c}(x_c)dx_c=h_1(X_s)*const&lt;/script&gt;

&lt;p&gt;이때도 역시 뒤의 constant는 모든 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;와 관계없이 동일하게 곱해지기 때문에, &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 따른 변화를 잡아낼 수 있다.&lt;/p&gt;

&lt;p&gt;반면, conditional pdf를 이용하는 방법의 경우, 이 예시에서도 &lt;script type=&quot;math/tex&quot;&gt;h_1(X_s)&lt;/script&gt;를 복원하지 못한다.&lt;/p&gt;

&lt;p&gt;즉
&lt;script type=&quot;math/tex&quot;&gt;E_{X_c| x_s}[f(X_s,X_c)| x_s]=\int (h_1(X_s)*h_2(X_c))f_{X_c| X_s}(x_c| X_s)dx_c&lt;/script&gt;&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;=h_1(X_s)*\int h_2(X_c)f_{X_c| X_s}(x_c| X_s)dx_c&lt;/script&gt;

&lt;p&gt;여기서 뒤의 항은 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;에 따라 값이 달라지는 값이고 즉 ,constant가 아니다. 이에 따라 각 &lt;script type=&quot;math/tex&quot;&gt;X_s&lt;/script&gt;마다 &lt;script type=&quot;math/tex&quot;&gt;h_1(X_s)&lt;/script&gt;를 복원하지 못하게 되고, &lt;strong&gt;뒤의 항때문에&lt;/strong&gt; 결과 해석에서 &lt;strong&gt;의도치 않은 영향을 해석하게 될수도&lt;/strong&gt; 있다.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;참조 :&lt;/p&gt;

&lt;p&gt;원논문 : &lt;a href=&quot;https://projecteuclid.org/download/pdf_1/euclid.aos/1013203451&quot;&gt;https://projecteuclid.org/download/pdf_1/euclid.aos/1013203451&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;정리 잘하신분 : &lt;a href=&quot;https://christophm.github.io/interpretable-ml-book/pdp.html#fn27&quot;&gt;https://christophm.github.io/interpretable-ml-book/pdp.html#fn27&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;sklearn에서 사용 : &lt;a href=&quot;https://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html&quot;&gt;https://scikit-learn.org/stable/auto_examples/ensemble/plot_partial_dependence.html&lt;/a&gt;&lt;/p&gt;
</description>
        <pubDate>Sat, 13 Apr 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/04/13/Partial-Depedence-Plot.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/04/13/Partial-Depedence-Plot.html</guid>
        
        <category>black box</category>
        
        <category>Partial dependency plot</category>
        
        <category>PDP</category>
        
        <category>interpretable machine learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[데이터분석 정리]Local Outlier Factor(LOF) 개인적 정리(with python)</title>
        <description>&lt;p&gt;원논문 : https://dl.acm.org/citation.cfm?id=335388&lt;/p&gt;

&lt;p&gt;LOF는 대표적인 outlier detection의 기법중 하나이다. LOF의 문제의식은, 문제의식은 기존의 방법들이 &lt;strong&gt;local정보에 대한 고려&lt;/strong&gt;가 없다는것이다. 데이터들간의 특성에 따라, 어떤 집단(혹은 군집)에선 매우 가까운 거리가, 어떤 집단에선 매우 먼 거리일 수 있다는 것이다. 자세한 설명은 아래의 그림과 함께 하겠다.&lt;/p&gt;

&lt;p&gt;Density based method는 &lt;strong&gt;density가 상이한 클러스터들&lt;/strong&gt;이 있을때 문제가 발생한다. 기존의 dense based 방법론들은 ‘dense’ 라는 개념을 정의하기 위해, 특정한 &lt;strong&gt;window size나 최소 갯수&lt;/strong&gt;등을 이용하였다. 예를들면 ‘거리가 c 이하인 window 내에 들어오는 데이터가 k개 이상인가?’로 dense를 지정하였다. 그러나 density가 상이한 경우, 기존의 방법론처럼 dense에 대한 절대적인 기준을 지정할수가 없어지기 때문이다. knn-distance method역시, 각 클러스터에 대해 outlier를 고르기 위한 적절한 knn-distance가 달라진다. 다음 그림을 보면 이해가 빠르다. 집단 &lt;script type=&quot;math/tex&quot;&gt;C_1&lt;/script&gt;과 집단 &lt;script type=&quot;math/tex&quot;&gt;C_2&lt;/script&gt;의 density가 다르기에, &lt;script type=&quot;math/tex&quot;&gt;o_1&lt;/script&gt;은 걸러내기 쉽지만 &lt;script type=&quot;math/tex&quot;&gt;o_2&lt;/script&gt;는 걸러내기가 어렵다. &lt;script type=&quot;math/tex&quot;&gt;C_1&lt;/script&gt;의 대부분 데이터들이 그정도는 떨어져 있었기 때문에, 일정 거리로 기준을 삼을 경우, &lt;script type=&quot;math/tex&quot;&gt;C_1&lt;/script&gt;혹은 &lt;script type=&quot;math/tex&quot;&gt;C_2&lt;/script&gt;에만 특화된 outlier detction을 하게 된다.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;211&quot; alt=&quot;lof1&quot; src=&quot;https://user-images.githubusercontent.com/31824102/54182467-eb27d800-44e4-11e9-98c0-c5142a46d930.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이러한 문제의식에서, &lt;strong&gt;local의 상대적인 dense&lt;/strong&gt;를 비교하여 outlier를 정하자는 lof가 나왔다. 큰 틀은, neighbor들의 dense를 고려하여 비교한다는 것이다. 이때 몇가지 새로운 정의들이 나온다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. k_distance(p)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;우선 &lt;strong&gt;k_distance(p)는&lt;/strong&gt;, 특정 데이터p에서의 k개 nearest neighbor까지의 거리이다. (3_distance(p)는 3번째로 가까운 데이터와의 거리) 이게 후에 상대적인 dense로써 작용할것이다.&lt;/p&gt;

&lt;p&gt;또, distance가 continuosu라면 3_distance내에 정확히 3개의 neighbor가 들어있겠지만, 거리가 1,2,3,3,3,3같이 discrete해서 겹치는 경우라면 3_distance내에 5개든 10개든 neighbor로 들어있을 수는 있다. 이를 따로 나타내주기 위해 k_distance(p)안에 들어온 데이터갯수를 &lt;script type=&quot;math/tex&quot;&gt;N_k(p)&lt;/script&gt;라고 부른다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. reachability distance(p,o)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;reach_dist(p,o)&lt;/strong&gt;는, p에 대해서 생각할때, &lt;strong&gt;주변 데이터 o의 k_distance를 고려한&lt;/strong&gt; 거리이다. 관심데이터p가 주변데이터o의 k_distance내에 들어와 있으면 o의 k_distance, 그것보다 밖에 있는 경우면 그냥 p와o의 거리를 잰다. 식으로 나타내면 다음과 같다.&lt;/p&gt;

&lt;p&gt;reach-distance(p,o)=max{k_distance(o),dist(p,o)}&lt;/p&gt;

&lt;p&gt;p와 o가 매우 붙어있더라도, o의 k_distance만큼은 거리를 뻥튀기해서 계산해주겠다는 개념이다. 이는 후에 이 reach_distance로 서로 dense를 비교할것이기 때문에, 너무작은 값을 갖지 않도록 하는 &lt;strong&gt;일종의 범퍼&lt;/strong&gt;이다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. local reachability density(p)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;이제 거의 다왔다. lrd(p)는, p주변의 k_neighbor들과의 reach_dist의 평균을 inverse취한 것이다. 식으로 나타내면 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;lrd_k(p)=[{\frac{\sum_{o\in N_k(p)}(reah\_dist(p,o))}{N_k(p)}}]^{-1}&lt;/script&gt;
이를 통해 주변의 dense를 고려한 p점에서의 ‘neighbor들과의 적당한 거리’를 나타낼 수 있다. 물론, lrd는 inverse이라는걸 알아만두자.&lt;/p&gt;

&lt;p&gt;그림을 통해 보면 쉽다. 그림 &lt;a href=&quot;https://jayhey.github.io/novelty%20detection/2017/11/10/Novelty_detection_LOF/&quot;&gt;원문&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;484&quot; alt=&quot;lof2&quot; src=&quot;https://user-images.githubusercontent.com/31824102/54182468-eb27d800-44e4-11e9-8c1d-3aee82c7f327.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;case1의 경우,  파랑점의 lrd는 초록점들과의 거리의 평균, 혹은 뻥튀기된, 초록점들의 k_distance들의 평균의 역수가 된다. 그러나 k_distance던 그냥 거리던 평균거리가 작을 것이므로, lrd의 값은 크게 된다.&lt;/p&gt;

&lt;p&gt;반면 case2의 경우, 평균거리는 상당히 클것이기에 lrd는 작은 값을 갖게 된다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Local Outlier Factor(p)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;드디어 마지막 단계이다. LOF(p)는, p의 &lt;script type=&quot;math/tex&quot;&gt;N_k(p)&lt;/script&gt;에 속하는 모든 다른점&lt;script type=&quot;math/tex&quot;&gt;o&lt;/script&gt;에 대해서 lrd의 비율을 구하고 이를 평균낸것이다. 수식으론 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;LOF_k(p)=\frac{\sum_{o\in N_k(p)}\frac{lrd(o)}{lrd(p)}}{N_k(p)}&lt;/script&gt;
쉽게 말해 주변의 점들 o와의 dense(lrd)를 비교하여 평균낸것이다. 사실 lrd(o)/lrd(p)는 이전의 정의가 역수임을 고려하면 &lt;strong&gt;‘p의 평균거리’/’o의 평균거리’를 구하고, 이를 평균낸것&lt;/strong&gt;으로 보면 된다. (편의상 ‘neighbor들과의, (reach_dist라는 버퍼를 씌운) 평균거리’를 그냥 ‘평균거리’라고 표현했다.)&lt;/p&gt;

&lt;p&gt;내 관심대상인 &lt;strong&gt;p의 ‘neighbor들과의 평균거리’&lt;/strong&gt;를 &lt;strong&gt;주변 neighbor들의 ‘평균거리’&lt;/strong&gt;와 비교하는 것이다. (사실 이게 더 직관적인거같은데 왜 굳이 역수를 썻는지 모르겠다)&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;515&quot; alt=&quot;lof3&quot; src=&quot;https://user-images.githubusercontent.com/31824102/54182471-eb27d800-44e4-11e9-990a-75474a4cce14.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;case1이나 case3같이 주변애들과 ‘평균거리’가 크게 차이나지 않는 점의 경우 lof는 1에 근사하게 나올 것이다. 그러나 case2 같이 주변애들(초록점)이 가진 평균거리에 비해 평균거리가 더 긴 데이터(파랑점)의 경우는 lof가 1보다 더 크게 나오기 쉽상일 것이다. &lt;strong&gt;즉&lt;/strong&gt;, lof&lt;script type=&quot;math/tex&quot;&gt;\approx&lt;/script&gt;1이면 정상데이터, lof&lt;script type=&quot;math/tex&quot;&gt;\gg&lt;/script&gt;1이면 outlier인 셈이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;이렇게 상대적으로 비교하기 위해서, 버퍼인 reach_dist의 정의가 필요했던듯하다. 데이터가 &lt;strong&gt;엄청나게 dense한지점에 있는 경우&lt;/strong&gt; 미세한 차이로 ratio가 &lt;strong&gt;엄청 sensitive해질 수&lt;/strong&gt; 있으니, 버퍼를 씌워줘서 robust하게 만들었다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이를 통해 local한 기준에서 평가를 하기에, 다음 그림과 같이 밀집한 지역에서는 더 빡빡한 기준으로 outlier를 잡고, 엉성한 지역에서는 더 엉성한 기준으로 outlier를 잡아낼 수 있게 된다. 문제점은 1.k를 몇으로 할지인 고질적인 문제. 그러나 경험적으로 &lt;strong&gt;k=20&lt;/strong&gt;정도로 하는것이 좋다고한다. 그리고 &lt;strong&gt;2. threshold를 얼마로 잡아야할지를&lt;/strong&gt; 알기 힘들다는 점이다. (파이썬에선 contamination이라는 옵션으로 train data중 몇%가 outlier인지를 우리가 지정해준다. auto는 0.2)&lt;/p&gt;

&lt;p&gt;다음은 서로다른 dense를 가진 집단에 대해 LOF를 나타낸 toy example이다. 우상단의 집단와 좌하단의 집단들간의 dense가 다름을 볼 수 있다. 그러나 서로 다른 dense에도 불구하고, 상대적으로 집단에서 벗어나있는 데이터는 대략적으로 lof가 1.1이상을 띄고 있음을 볼 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;379&quot; alt=&quot;lof4&quot; src=&quot;https://user-images.githubusercontent.com/31824102/54182454-e8c57e00-44e4-11e9-8b00-fb3f2f7fb765.PNG&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;코드-상세&quot;&gt;코드 상세&lt;/h3&gt;

&lt;p&gt;아래는 sklearn의 예시에서 좀더 가시성을 확보하기 위해 손 본 코드입니다.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://scikit-learn.org/stable/auto_examples/neighbors/plot_lof_outlier_detection.html&quot;&gt;원문&lt;/a&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;sklearn.neighbors&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LocalOutlierFactor&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figure&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dpi&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;80&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;facecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'w'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'k'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate train data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_inliers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#정규분포에서 100*2만들고
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_inliers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_inliers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_inliers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#각각 2,2 혹은 -2,-2만큼 평행이동한거를 vstack. 즉 cluster 2개
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Generate some outliers
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_outliers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;low&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;high&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_inliers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_outliers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#-4,4에서 뽑은 outlier와 inlier를 vstack
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_outliers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_outliers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ground_truth&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ground_truth&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_outliers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# fit the model for outlier detection (default)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;clf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LocalOutlierFactor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_neighbors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;contamination&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# use fit_predict to compute the predicted labels of the training samples
# (when LOF is used for outlier detection, the estimator has no predict,
# decision_function and score_samples methods).
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clf&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit_predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#1,-1로 나온다.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_errors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ground_truth&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clf&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;negative_outlier_factor_&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;#fig, ax = plt.subplots()
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Local Outlier Factor (LOF)&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'b'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Data points'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# plot circles with radius proportional to the outlier scores
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_scores&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_scores&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_scores&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#오홍 minmax scaling으로 radius를 정햇네
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;edgecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'r'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;facecolors&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'none'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Outlier scores'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nan&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;txt&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isnan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;txt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;continue&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;annotate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;txt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;legend&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loc&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'upper left'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;&lt;img width=&quot;379&quot; alt=&quot;lof4&quot; src=&quot;https://user-images.githubusercontent.com/31824102/54182454-e8c57e00-44e4-11e9-8b00-fb3f2f7fb765.PNG&quot; /&gt;&lt;/p&gt;
</description>
        <pubDate>Mon, 11 Mar 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/03/11/Local-Outlier-Factor(LOF).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/03/11/Local-Outlier-Factor(LOF).html</guid>
        
        <category>Local Outlier Factor</category>
        
        <category>LOF</category>
        
        <category>outlier detection</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[통계기초 정리] 개인적인 통계 방법론 복습 (4. Chisquare 검정)</title>
        <description>&lt;p&gt;기초 지식이지만 모든 고급분석의 근반이 되기에, 기초를 탄탄히 하고자 한번의 수업수강과 한번의 청강, 한번의 도강(…)까지 했다. 그치만 매번 공부하고 공부해도 까먹는 통계 기초. 늘 책찾고 헤매는 것이 힘들어서 한번에 정리해보았다.&lt;/p&gt;

&lt;h3 id=&quot;chisquare-test&quot;&gt;Chisquare test&lt;/h3&gt;

&lt;p&gt;chisq test는 적합도검정과 독립성 검정으로 설명.&lt;/p&gt;

&lt;h3 id=&quot;적합도-검정&quot;&gt;적합도 검정&lt;/h3&gt;

&lt;p&gt;multinomial dist를 이용해서, 우리에게 분석 전에 주어진 확률들이 타당한지를 보는 검정. categorical data에 대해서 이뤄지고, 아직까지도 요긴하게 쓰이는 기특한 통계검정 방법 중 하나.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; multinomial dist&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;X\sim bin(n,p)&lt;/script&gt;로 쓰는 binomial dist에 대해 상기. n번 던져서 경우의 수가 2가지인(T,F) 관심 사건이 몇번 일어나는지 보는 분포.&lt;br /&gt;
&lt;script type=&quot;math/tex&quot;&gt;f(x)=_nC_x p^x(1-p)^{n-x}&lt;/script&gt;
multinomial은 그거의 확장일뿐. 즉, 관찰하는 사건의 가능한 가짓수가 2가지가 아닌 k가지. 1~6의 6가지 결과가 나올 수 있는 주사위가 가장 대표적.&lt;/p&gt;

&lt;p&gt;pdf 역시 binom과 비슷하다. 앞의 분수형태는, binom에서와 비슷하게 각 시행이 독립이기 때문에, 각 category가 &lt;script type=&quot;math/tex&quot;&gt;x_1,..,x_k&lt;/script&gt;개가 이리저리 순서를 바꿔 발현된 사상들이 모두 확률이 같기에 더해준거. 즉,  &lt;script type=&quot;math/tex&quot;&gt;x_1,..,x_k&lt;/script&gt;개를 줄세운 가짓수.
&lt;script type=&quot;math/tex&quot;&gt;\Pr[X_1=x_1,..,X_k=x_k]=\frac{n!}{x_1!*..*x_k!} p_1^{x_1}..p_k^{x_k}&lt;/script&gt;
그러난 가짓수가 T,F 2가지인 경우 r.v가 1개인것처럼, 마지막 1개는 r.v.가 아니다 (&lt;script type=&quot;math/tex&quot;&gt;x_k=n-\sum_i^{k-1}x_i, p_k=1-\sum_i^{k-1}p_i&lt;/script&gt;)&lt;/p&gt;

&lt;p&gt;이때의 각각의 &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_k&lt;/script&gt;의 기댓값은 얼말까? 조금 새각해보면 간단하다. multinomial데이터라도, 사실 i번째 사건이 일어났냐(T), 안일어났냐(F)로 binomial로 치환할 수 있다. 물론 그 경우에 각 사건에 대응하는 확률은 (당연히) 바뀌지 않는다.&lt;/p&gt;

&lt;p&gt;즉,if &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_k\sim M[n,p_1,..,p_k]&lt;/script&gt; then &lt;script type=&quot;math/tex&quot;&gt;X_i\sim bin(n,p_i)&lt;/script&gt;,&lt;/p&gt;

&lt;p&gt;$\therefore E(X_i)=np_i$&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 검정통계량&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;앞서나온 multimonial의 특수한 성질로 인해 다음이 성립힌다. (proof 생략. 무지 어렵다고한다.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1)&lt;/strong&gt; &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_k\sim M[n,p_1,..,p_k]&lt;/script&gt;이고, &lt;strong&gt;2)&lt;/strong&gt; n이 충분히 크다면(&lt;script type=&quot;math/tex&quot;&gt;np_u\ge5, \forall i&lt;/script&gt;), 
&lt;script type=&quot;math/tex&quot;&gt;\sum_i^k\frac{(X_i-E(X_i))^2}{E(X_i)}\sim^A \chi^2(k-1)&lt;/script&gt;
(-1은 multinomial에서 처럼 자유로운 class의 갯수라고 보면 된다.)&lt;/p&gt;

&lt;p&gt;얼핏보면 표준정규 Z를 제곱해서 더한것과 비슷해볼 수 있지만, 완전히 다른놈이다. 우선 분모부터 S가 아님. 마치 편차를 평균으로써 scaling해준듯한 느낌으로 받아들이자.&lt;/p&gt;

&lt;p&gt;이게끝.&lt;/p&gt;

&lt;p&gt;각 category로 나뉜 실제 데이터가 있다고 해보자.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;432&quot; alt=&quot;goodness_of_fit2&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090552-b7b04700-977d-11e9-8624-9ab7b13c70d7.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;n이 충분히 큰경우(&lt;script type=&quot;math/tex&quot;&gt;np_u\ge5, \forall i&lt;/script&gt;)에, 이거로 우리의 확률들이 적절한지 보면 된다&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;H0: P_1=p_{10},..,P_k=p_{10}&lt;/script&gt;, (&lt;script type=&quot;math/tex&quot;&gt;p_{10},..,p_{k0}&lt;/script&gt;은 귀무가설하의 확률들)&lt;/p&gt;

&lt;p&gt;then under H0,&lt;/p&gt;

&lt;p&gt;$X_1,..,X_k\sim M[n,p_{10},..,p_{k0}]$&lt;/p&gt;

&lt;p&gt;test_statistic&lt;script type=&quot;math/tex&quot;&gt;=:X:=\sum_i^k\frac{(X_i-E(X_i))^2}{E(X_i)}\sim^A \chi^2(k-1)&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;chisq분포기에 by nature단측 검정이 되고, 검정통계량 X가 임계값 &lt;script type=&quot;math/tex&quot;&gt;\chi^2_{\alpha,k-1}&lt;/script&gt;보다 크다면 rej H0.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;굳이 category가 명시되지 않았더라도, 예를들면 &lt;script type=&quot;math/tex&quot;&gt;N(\mu,\sigma^2)&lt;/script&gt;를 검정하고 플때 적당히 구간 잘라서 h0하의 확률과 비교를 해볼 수도 있다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;적합도-검정-parameter-unspecified&quot;&gt;적합도 검정 (parameter unspecified)&lt;/h3&gt;

&lt;p&gt;적합도 검정의 또 다른 쓰임새.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 언제쓰이나?&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;예를 들어 H0:&lt;script type=&quot;math/tex&quot;&gt;Y\sim Normal&lt;/script&gt;, 즉, 정규분폰지 아닌지를 보고플때. 이때 물론 parameter &lt;script type=&quot;math/tex&quot;&gt;\mu,\sigma^2&lt;/script&gt;는 모른다. 모르면 어케한다? 늘그래왔듯, 미지의 모수를 &lt;strong&gt;sample로 추정&lt;/strong&gt;한다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 검정통계량 &amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;애초에 위에서부터 증명없이 받아들여왔기에, 별로 추가될게 없다.&lt;/p&gt;

&lt;p&gt;H0:&lt;script type=&quot;math/tex&quot;&gt;Y\sim Normal&lt;/script&gt;이라면&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;unspecified parameter를 추정&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\hat\mu=\bar y,\hat \sigma^2=S_y^2&lt;/script&gt;, 그리고 적절한 구간 나누기. (&lt;script type=&quot;math/tex&quot;&gt;np_u\ge5, \forall i&lt;/script&gt;를 만족해야한다.)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;(위에서와 마찬가지로) 기대되는 빈도와 실제빈도의 차이를 가지고 검정통계량만듬
&lt;script type=&quot;math/tex&quot;&gt;X:=\sum_i^k\frac{(X_i-n\hat {p_i})^2}{n\hat {p_i}}\sim^A \chi^2(k-1-\boldsymbol2)&lt;/script&gt;
이때 자유도는, &lt;strong&gt;sample로 추정한 모수의 갯수만큼 차감&lt;/strong&gt;해준다. 이경우 N은 para가 2개이기에 -2.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;독립성-검정&quot;&gt;독립성 검정&lt;/h3&gt;

&lt;p&gt;이것도 기대빈도와 실제빈도를 가지고 만드는거기에, 생긴건 적합도 검정과 매우 비슷하다. 다만, 이번엔 2개의 Categorical Variable이 있는 경우이다.&lt;/p&gt;

&lt;p&gt;두개의 &lt;strong&gt;continuous r.v.가 서로 상관&lt;/strong&gt;되어 있는건 어케보냐? 가장 대표적인게 correlation!&lt;/p&gt;

&lt;p&gt;그럼 2개의 &lt;strong&gt;Categorical Variable&lt;/strong&gt;이 있을때, 그 2개의 variable이 서로 related되어 있는가?를 보고 싶은 경우. 바로 이 독립성검정!&lt;/p&gt;

&lt;p&gt;예를 들면, 소득분위에 따라 연체자가 되는 것(그 확률을 우리가 알고 있던 모르던)과, 성별에 따라 연체자가 되는것이 서로 관계가 있을지 없을지를 보는것이다. 즉, 남자의 경우의 소득분위에 따른 비율과 여자의 경우 소득분위에 따른 비율이 유의하게 다른지 안다른지를 보는것&lt;/p&gt;

&lt;p&gt;이를 위해 cotingency table이 필요&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;433&quot; alt=&quot;independence_test&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090551-b7b04700-977d-11e9-8daa-2b35a16fe8d5.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;각각의 경우에 대한 확률을 나타낸 contingency table. 근데 만약 독립이라면? &lt;script type=&quot;math/tex&quot;&gt;P_{11}=P_1*q_1&lt;/script&gt;이겟지! 이걸로 검정을 한다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 검정통계량&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;H0 : 2 var are indep &amp;lt;=&amp;gt; &lt;script type=&quot;math/tex&quot;&gt;P_{ij}=P_i*q_j&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;이를 가지고, H0하에서 &lt;script type=&quot;math/tex&quot;&gt;P_{ij}&lt;/script&gt;를 만들고, 이를 실제와 비교한다 (H0하가 아니라면, 그냥 &lt;script type=&quot;math/tex&quot;&gt;\hat P_{ij}= X_{ij}/n&lt;/script&gt;하고 끝날것.)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;근데 &lt;script type=&quot;math/tex&quot;&gt;P_i,q_j&lt;/script&gt;를 모른다면?=&amp;gt; 이것 역시, 추정 (unspecified paramter의 경우라고 보면 됨.)&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\hat P_i=\sum_j^c x_{ij}/n&lt;/script&gt;. 단순한 sample proportion이다.&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\hat q_j=\sum_i^r x_{ij}/n&lt;/script&gt;,&lt;/p&gt;

    &lt;script type=&quot;math/tex; mode=display&quot;&gt;\hat P_{ij}=\hat P_i*\hat q_j&lt;/script&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\hat E(X_{ij})=n*\hat P_{ij}&lt;/script&gt;, (&lt;script type=&quot;math/tex&quot;&gt;X_{ij}&lt;/script&gt;는 각 cell에 속한 데이터의 수.)
&lt;script type=&quot;math/tex&quot;&gt;\frac{\sum_i^r\sum_j^c(X_{ij}-\hat E(X_{ij})^2)}{\hat E(X_{ij}}=\frac{\sum_i^r\sum_j^c(X_{ij}-n\hat P_{i}\hat q_j)^2)}{n\hat P_{i}\hat q_j}\sim^A \chi^2(rc-((r-1)+(c-1)+1))&lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;왜 자유도가 &lt;script type=&quot;math/tex&quot;&gt;(rc-((r-1)+(c-1)+1)​&lt;/script&gt;? 각각 &lt;script type=&quot;math/tex&quot;&gt;P_i,q_j​&lt;/script&gt;를 예측했기에 r개, c개 인데, 확률의 특성으로 &lt;script type=&quot;math/tex&quot;&gt;\sum P_i=1,\sum q_j=1​&lt;/script&gt;을 알기에 각각 -1. 근데 그럼 한cell을 두번 뺀것이기에 다시 +1해줌.&lt;/p&gt;

&lt;p&gt;만약, &lt;script type=&quot;math/tex&quot;&gt;P_i, q_j&lt;/script&gt;를 우리가 이미 알고 있는 상태에서의 H0을 비교하는것이었다면 자유도는 이전 &lt;script type=&quot;math/tex&quot;&gt;k-1&lt;/script&gt;처럼 &lt;script type=&quot;math/tex&quot;&gt;rc-1&lt;/script&gt;이 된다. (우리는 지금 확률이 정당한지를 보는게 아니라 독립성을 확인하는 것이기에, 이미 알고 있는 확률을 넣어주는 경우는 거의 없다.)&lt;/p&gt;
</description>
        <pubDate>Wed, 06 Mar 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%ED%86%B5%EA%B3%84%EA%B8%B0%EC%B4%88/2019/03/06/%EA%B0%9C%EC%9D%B8%EC%A0%81%EC%9D%B8-%ED%86%B5%EA%B3%84-%EB%B0%A9%EB%B2%95%EB%A1%A0-%EB%B3%B5%EC%8A%B5-(4.-Chisquare-%EA%B2%80%EC%A0%95).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%ED%86%B5%EA%B3%84%EA%B8%B0%EC%B4%88/2019/03/06/%EA%B0%9C%EC%9D%B8%EC%A0%81%EC%9D%B8-%ED%86%B5%EA%B3%84-%EB%B0%A9%EB%B2%95%EB%A1%A0-%EB%B3%B5%EC%8A%B5-(4.-Chisquare-%EA%B2%80%EC%A0%95).html</guid>
        
        <category>basic statistics</category>
        
        <category>chisquare test</category>
        
        <category>goodness of fit test</category>
        
        <category>independence test</category>
        
        
        <category>통계기초</category>
        
      </item>
    
      <item>
        <title>[통계기초 정리] 개인적인 통계 방법론 복습 (3. 다양한 Anova검정)</title>
        <description>&lt;p&gt;기초 지식이지만 모든 고급분석의 근반이 되기에, 기초를 탄탄히 하고자 한번의 수업수강과 한번의 청강, 한번의 도강(…)까지 했다. 그치만 매번 공부하고 공부해도 까먹는 통계 기초. 늘 책찾고 헤매는 것이 힘들어서 한번에 정리해보았다.&lt;/p&gt;

&lt;h3 id=&quot;이번엔-anova&quot;&gt;이번엔 ANOVA&lt;/h3&gt;

&lt;p&gt;평균검정에서 &lt;strong&gt;그룹이 2개 이상이&lt;/strong&gt; 된 경우. (2개만이면 t-test나 대표본의 경우 N으로 가능했음). 예를 들면 방법a,방법b,방법c로 공부한 학생들의 성적이 다른가를 보기 위한 검정.&lt;/p&gt;

&lt;p&gt;Anova :=analysis of variance. 평균들의 &lt;strong&gt;변동성&lt;/strong&gt;을 이용해서 평균차가 있는지를 검정한다.&lt;/p&gt;

&lt;p&gt;왜 분산으로 비교? =&amp;gt;&lt;script type=&quot;math/tex&quot;&gt;\mu_1,..,\mu_k&lt;/script&gt;가 다른지를 보기 위해, 표본으로 구해진 표본평균값들을 각각 새로운 데이터로 보고, 그 데이터가 &lt;strong&gt;서로 얼마나 차이나는지&lt;/strong&gt;, 즉 분산을 보게 됨. 근데 표본평균들간의 분산은 그 데이터자체의 분산에 의존함. (알다시피 &lt;script type=&quot;math/tex&quot;&gt;V(\bar X)=\frac{\sigma^2}{n}&lt;/script&gt;)&lt;/p&gt;

&lt;p&gt;그래서 &lt;strong&gt;표본평균들간 분산&lt;/strong&gt;을 &lt;strong&gt;데이터자체의 분산&lt;/strong&gt;으로 scaling해준 개념. &lt;strong&gt;‘전체 분산에 비해 그룹간 분산이 유의미하게 큰지!’&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;왜 굳이 이렇게 접근하지는지? 물론, 검정통계량은 여러 문제의식을 바탕으로 여러가지로 만들 수 있다. 문제는 &lt;strong&gt;그 검정통계량의 분포를 도출해낼수 있냐는것&lt;/strong&gt;. (분포를 도출못하면 p-value등을 못구하고 통제된 의사결정을 못함.) Anova가 쓰이는 이유는 분산/분산을 활용하여 &lt;strong&gt;F-dist 도출&lt;/strong&gt;에 성공했기 때문이다. 고로 ‘왜 굳이 이렇게 접근하지는지? ‘에 대한 답은 ‘그렇게 접근하면 분포를 도출할 수 있었기때문 정도’&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;t-test와 비슷하게, 매우 많은 가정들이 필요하다.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;425&quot; alt=&quot;anova_table_data&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090556-b848dd80-977d-11e9-848c-3f7bc0701e80.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;조건들&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;{&lt;script type=&quot;math/tex&quot;&gt;y_{11},..,y_{1n_1}&lt;/script&gt;},..,{&lt;script type=&quot;math/tex&quot;&gt;y_k1,..,y_{kn_k}&lt;/script&gt;}인, k개 group의 총 kn개의 데이터가 있다고해보자. (오류! kn개는 그룹간 데이터 수가 같은 경우. kn개가 아니라 &lt;script type=&quot;math/tex&quot;&gt;n_1+..+n_j=n_{tot}&lt;/script&gt;개라고 햇어야 했는데, 그냥 ‘kn개의 데이터’처럼 고유명사로 언급하는데에만 썻으니 주의하고 넘어가면 읽는데 무리는 없는듯 하다.)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;모든 group들에 대해 &lt;strong&gt;iid N&lt;/strong&gt;가정 (eg) &lt;script type=&quot;math/tex&quot;&gt;y_{1i}\sim N(\mu_1,\sigma_1^2)&lt;/script&gt;)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;그 group들에 대해 모두 &lt;strong&gt;등분산&lt;/strong&gt; 가정. (즉, &lt;script type=&quot;math/tex&quot;&gt;N(\mu_k,\sigma^2)&lt;/script&gt;)&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;위 두가정으로 얼마나 비현실적인지 알 수 있다. N가정은 그렇다해도 k개의 group에 대해서 분산이 동일하다니..&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;각 group들 간에 indep. (이건 sampling의 문제. randomized sampling을 하자)&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;이제 통계량 도출&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;H0=\mu_1=..=\mu_k\boldsymbol{=:\mu}&lt;/script&gt;.&lt;/p&gt;

&lt;p&gt;앞서 말햇듯이 {&lt;script type=&quot;math/tex&quot;&gt;y_{11},..,y_{1n_1}&lt;/script&gt;},..,{&lt;script type=&quot;math/tex&quot;&gt;y_k1,..,y_{kn_k}&lt;/script&gt;}인, k개 group의 총 kn개의 데이터가 있다고해보자.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; step1.&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;첫째로, 각 group의 평균들을 비교하는 과정.&lt;/p&gt;

&lt;p&gt;평균이 같을것이라는 &lt;strong&gt;귀무가설하에&lt;/strong&gt;, 각 &lt;strong&gt;group의 mean&lt;/strong&gt;의 표본분포는 다음과 같다.&lt;/p&gt;

&lt;p&gt;then,  &lt;script type=&quot;math/tex&quot;&gt;\bar y_j\sim^{iid}N(\mu,\frac{\sigma^2}{n_j})&lt;/script&gt;, under H0.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\therefore\sum_j^k\frac{n_j(\bar y_k-\mu)^2}{\sigma^2}\sim\chi^2(k)&lt;/script&gt;, 그러나 &lt;script type=&quot;math/tex&quot;&gt;\mu&lt;/script&gt;를 모르기에 이를 데이터로 대체한다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\hat\mu=:\bar y_{..}:=\frac{\sum_{j}^k\sum_{i}^{n_j}y_{ij}}{n_{tot}}, (n_{tot}=\sum_j^kn_j)&lt;/script&gt;

&lt;p&gt;즉 kn개의 데이터의 overall mean. 추정량으로 모수를 하나 대체했으니, 자유도 1 감소. (사실 따지자면 cochran’s thm으로 분포의 df가 감소)&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\therefore\sum_j^k\frac{n_j(\bar y_j-\bar y_{..})^2}{\sigma^2}\sim\chi^2(k-1), underH_0&lt;/script&gt;

&lt;p&gt;또한, &lt;script type=&quot;math/tex&quot;&gt;E(\sum_j^k\frac{n_j(\bar y_k-\bar y_{..})^2}{k-1})=\sigma^2&lt;/script&gt;로도 표현가능. 이때 분자의 형태를 보면  마치 kn개의 데이터를 group의 effect만 받은것처럼 간주하여, 같은 group의 데이터에 group_mean으로 masking해준 데이터의 평균에 대한 deviation form으로 볼 수 있다. group을 treatment라고 표현하기도 하기에, 이를 &lt;strong&gt;SSTR&lt;/strong&gt;이라 부른다. 혹은 데이터의 미시적인 부분을 보지않고, group_mean간의 분산을 통한 통계량이기 때문에 &lt;strong&gt;Between group Sum of Square&lt;/strong&gt;라고 부르기도 한다. 즉, &lt;script type=&quot;math/tex&quot;&gt;\frac{SSTR}{\sigma^2}\sim\chi^2(k-1)&lt;/script&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;덧. group마다 데이터수가 n으로 같은 경우 &lt;script type=&quot;math/tex&quot;&gt;\bar y_j\sim N(\mu_j,\frac{\sigma^2}{n})&lt;/script&gt;으로 표현하고 &lt;script type=&quot;math/tex&quot;&gt;\bar y_{..}=\frac{\sum_j^k \bar y_j}{k}&lt;/script&gt;로 두어, 마치 sample group_mean을 데이터처럼 보고 접근하는 설명도 있지만, &lt;script type=&quot;math/tex&quot;&gt;\bar y_{..}=\frac{\sum_j^k \bar y_j}{k}&lt;/script&gt;로 풀리는 것은 모두 n개로 balanced data일때 풀리는 말. 원래 도출은 위의것이 맞다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; step2.&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;이번엔 그룹평균말고, &lt;strong&gt;데이터 자체의 분산&lt;/strong&gt;에 대한 과정.&lt;/p&gt;

&lt;p&gt;모든 group들이 iid N의 분포를 가지며, (평균은 다른지 안다른지 모르지만) 분산은 다 같다는 문제의 기본 setting에 의거하여 다음의 식이 가능.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{y_{ij}-\mu_j}{\sigma}\sim N(0,1)&lt;/script&gt;,  &lt;script type=&quot;math/tex&quot;&gt;\therefore \frac{(y_{ij}-\mu_j)^2}{\sigma^2}\sim \chi^2(1)&lt;/script&gt;,under H0. 이는 다음과 같이 표현할 수도 있다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\sum_i^{n_j} \frac{(y_{ij}-\mu_j)^2}{\sigma^2}\sim \chi^2(n_j)&lt;/script&gt;

&lt;p&gt;이는 각 group내에서도 통하지만, group간의 상관없이 분산이 같을거라는 등분산가정을 했기에 &lt;strong&gt;group에 상관없이 모두 합하는 것이 가능하다&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;그러나 이번에도 &lt;script type=&quot;math/tex&quot;&gt;\mu_j&lt;/script&gt;를 모르기에 이를 데이터로 대체한다. 그러나 이번엔 step1에서와 다르게, H0하에서 overall mean으로 추정한것이 아니다. 각각의 &lt;script type=&quot;math/tex&quot;&gt;\mu_j&lt;/script&gt;에 대해, sample group_mean으로 각각의 를 추정한다. (왜 굳이?라고 묻는다면, ‘H0과 비교하기 위해’라고 할 수도 있지만, 가장 큰 이유는 그래야 통계량분포가 나오기에.)&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\sum_i^{n_j} \frac{(y_{ij}-\bar y_{.j})^2}{\sigma^2}\sim \chi^2(n_j-1)&lt;/script&gt;

&lt;p&gt;또한 앞서 말했듯이, 이는 group에 상관없이 모두 통하는 말이다. 또한 &lt;strong&gt;group간의 indep&lt;/strong&gt;를 가정했기에, chisq의 가법성에 의해 다음이 성립한다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\therefore\sum_j^k\sum_i^{n_j} \frac{(y_{ij}-\bar y{..})^2}{\sigma^2}\sim \chi^2(n_1-1+..+n_j-1)=\chi^2(n_{tot}-k)&lt;/script&gt;

&lt;p&gt;또한, &lt;script type=&quot;math/tex&quot;&gt;E(\sum_j^k\sum_i^{n_j} \frac{(y_{ij}-\bar y{..})^2}{n_{tot}-k})=\sigma^2&lt;/script&gt;로도 표현가능. 이는 H0과는 관계 없이, group간의 분산이 모두 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;로 같다는 기본셋팅만 이용하였으므로, &lt;strong&gt;under H0가 ‘아니다’&lt;/strong&gt;. 또한 이때 분자를 보면 각 데이터가 각 group_mean에서 얼마나 멀어져있는지를 나타낸 deviation form(error)의 제곱합이다 .따라서 이를 &lt;strong&gt;SSE&lt;/strong&gt; 라고도 하고, Within group Sum of Square라고도 한다.  즉, &lt;script type=&quot;math/tex&quot;&gt;\frac{SSE}{\sigma^2}\sim\chi^2(n_{tot}-k)&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; step 3.&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;group간을 보는 step1, group내를 보는 step2를 했으니, 이번엔 &lt;strong&gt;전체의 관점에서&lt;/strong&gt; 각각의 데이터를 봐보자.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;y_{ij}\sim^{iid}N(\mu,\sigma^2)&lt;/script&gt;, &lt;strong&gt;under H0.&lt;/strong&gt; (Step3는 애초에 H0하에서 얘기가 시작되고 있다.)&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\therefore \frac{(y_{ij}-\mu)^2}{\sigma^2}\sim\chi^2(1)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;\sum_j^k\sum_i^{n_j}  \frac{(y_{ij}-\mu)^2}{\sigma^2}\sim\chi^2(n_{tot})&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;마찬가지로 &lt;script type=&quot;math/tex&quot;&gt;\mu&lt;/script&gt;를 모르기에 이를 데이터로 대체한다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\sum_j^k\sum_i^{n_j}  \frac{(y_{ij}-\bar y_{..})^2}{\sigma^2}\sim\chi^2(n_{tot}-1)&lt;/script&gt;

&lt;p&gt;이때 분자를 보면, 전체의 데이터가 전체 overall mean에서 얼마나 멀어져있는지를 나타내는 형태이기에, SSTO(Sum of Square Total)로 표현한다. 즉 &lt;script type=&quot;math/tex&quot;&gt;\frac{SSTR}{\sigma^2}\sim\chi^2(n_{tot}-1)&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; step4.&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;이제 거의 다왔다. step1,2,3을 잘 조합하기만 하면 된다. SSTO는 다음과 같이 분해될 수 있다.&lt;/p&gt;

&lt;p&gt;$SSTO=\sum_j^k\sum_i^{n_j}(y_{ij}-\bar y_{..})^2=\sum_j^k{n_j(\bar y_k-\bar y_{..})^2}+\sum_j^k\sum_i^{n_j} {(y_{ij}-\bar y{..})^2}$&lt;/p&gt;

&lt;p&gt;$\therefore SSTO=SSTR+SSE$&lt;/p&gt;

&lt;p&gt;그리고 여기서 Cochran’s thm이 쓰인다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&amp;lt; Cochran’s thm&amp;gt;&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Z_1,..,Z_k\sim N(0,1)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;Q:=\sum_{Z^2}\sim\chi^2(k)&lt;/script&gt;의 세팅에서,&lt;/p&gt;

  &lt;ul&gt;
    &lt;li&gt;
      &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Q=Q_1+..+Q_s&lt;/script&gt; 앞서 구한 Q가 s개의 다른 요소들로 분해가 가능하고,&lt;/p&gt;
    &lt;/li&gt;
    &lt;li&gt;
      &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;k=k_1+..+k_s&lt;/script&gt; 그 분해된 요소들간의 df도 똑같이 덧셈등식이 성립한다면&lt;/p&gt;

      &lt;p&gt;=&amp;gt; 1. &lt;script type=&quot;math/tex&quot;&gt;Q_1,,.,Q_s&lt;/script&gt; are inedp&lt;/p&gt;

      &lt;ol&gt;
        &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;Q_i\sim\chi^2(k_i)&lt;/script&gt;의 분포를 따른다&lt;/li&gt;
      &lt;/ol&gt;
    &lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;라는 성질이 밝혀져 있다고한다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{SSTO}{\sigma^2}=\frac{SSTR}{\sigma^2}+\frac{SSE}{\sigma^2}&lt;/script&gt;인데, 이때의 df도 &lt;script type=&quot;math/tex&quot;&gt;n_{tot}-1=(k-1)+(n_{tot}-k)&lt;/script&gt;로 같다! (SSTO가 chisq를 따른다는 전제이다. 즉, underH0이다.)&lt;/p&gt;

&lt;p&gt;=&amp;gt;   1. &lt;script type=&quot;math/tex&quot;&gt;\frac{SSTR}{\sigma^2},\frac{SSE}{\sigma^2}&lt;/script&gt; are indep&lt;/p&gt;

&lt;p&gt;​	2. &lt;script type=&quot;math/tex&quot;&gt;\frac{SSTR}{\sigma^2}\sim\chi^2(k-1)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;\frac{SSTR}{\sigma^2}\sim\chi^2(n_{tot}-1)&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;그러나 2번은 사실 앞서서 밝힌 사항들이고, 중요한건 그 둘이 &lt;strong&gt;indep&lt;/strong&gt;라는 것이다. 두개의 indep한 chisq분포. 이제 F-dist를 만들 수 있게된것!&lt;/p&gt;

&lt;p&gt;by Cochran’s thm,&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;F=\frac{(\frac{SSTR}{\sigma^2})/k-1}{(\frac{SSE}{\sigma^2})/(n_{tot}-k)}\sim F(k-1,n_{tot}-k), \boldsymbol{underH0}&lt;/script&gt;

&lt;p&gt;(SSTO가 chisq를 따른다는 셋팅하에서 전개되는 얘기이기에, under H0라는걸 명심히자.)&lt;/p&gt;

&lt;p&gt;또한, 각 SS를 df로 나눠준걸 mean~의 형태로 부르는데, 그 경우 다음처럼 표현할수도 있다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;F=\frac{(\frac{SSTR}{\sigma^2})/k-1}{(\frac{SSE}{\sigma^2})/(n_{tot}-k)}=\frac{({SSTR})/k-1}{({SSE})/(n_{tot}-k)}=\frac{MSTR}{MSE}\sim F(k-1,n_{tot}-k), \boldsymbol{underH0}&lt;/script&gt;

&lt;p&gt;이를 정리한 표와 함께 마무리.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;433&quot; alt=&quot;anova_table&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090558-b8e17400-977d-11e9-9865-74f1267c725e.PNG&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;randomized-complete-block-design-rcbd&quot;&gt;Randomized (complete) block design. (RCBD)&lt;/h2&gt;

&lt;p&gt;Blocking factor가 있는 경우, one way anova의 분산이 더 커진다. (검정을 진행할수는 있다. 그러나 많은 경우 통계량의 분산이 커져서 결과적으론 검정력이 떨어진다.) 따라서 이때는 block의 영향 역시 고려한 RCBD에서의 anova를 사용한다. 그러나 rcbd는 각 level간에 data수가 다른 경우에 대해서는 검정이 엄청까다롭다고 한다. 고로 학부생이 배우는건 data수가 모두 n으로 같은 경우에 대해서.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;465&quot; alt=&quot;anova_table_rcbd_data&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090555-b848dd80-977d-11e9-8329-ea758d969521.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 새로운 notation 새로 선언_1&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;rcbd와 바로 뒤에 나올 two-way anova로의 확장을 위해서, 기존의 one-way anova를 조금 다른 방식으로 표현해보자. 이전 one-way AONVA의 기존 세팅은 이렇게 표현되었었다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;y_{ji}\sim N(\mu_j,\sigma^2)&lt;/script&gt;

&lt;p&gt;이렇게 표현되었던 것을 각 treatment(혹은 group)별 effect라는 것을 따로 떼줘서 다음과 같이 표현할 수도 있다.(여기선 group를 i로, block을 j로 표현한다. 사실 차이는 없음)&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;y_{ij}=M+\tau_i+\epsilon_{ij}, \epsilon_{ij}\sim N(0,\sigma^2)&lt;/script&gt;

&lt;p&gt;여기서, &lt;script type=&quot;math/tex&quot;&gt;M&lt;/script&gt;은 &lt;strong&gt;overall effect&lt;/strong&gt;로, &lt;script type=&quot;math/tex&quot;&gt;M:=\frac{1}{k}\sum{\mu_k}&lt;/script&gt; 이렇게 정의된다. 즉, 그룹 평균들의 simple avg로, 자연스레 &lt;script type=&quot;math/tex&quot;&gt;\tau_i(=\mu_i-M)&lt;/script&gt;는 편차항으로, &lt;script type=&quot;math/tex&quot;&gt;\sum_i^k \tau_i=0&lt;/script&gt;이 된다.&lt;/p&gt;

&lt;p&gt;이때 &lt;script type=&quot;math/tex&quot;&gt;\tau_i&lt;/script&gt;는 그 treatment들이 갖는, overall effect와 다른 성질로, &lt;strong&gt;treatmeant effect&lt;/strong&gt;라고 한다.&lt;/p&gt;

&lt;p&gt;또한, 기존의 평균이 같다는 H0은 group_mean간의 편차가 0이라는것으로 바꿔표현할 수 있다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;H0:\tau_1=..=\tau_k=0&lt;/script&gt;

&lt;blockquote&gt;
  &lt;p&gt;overall effect를 group_mean의 평균으로 추정하고 있다! 이는 앞서 했던 one-way anv에서 데이터가 n으로 동등한 경우. rcbd에선 &lt;strong&gt;unbalanced는 다루고 있지 않다&lt;/strong&gt;는것 상기.&lt;/p&gt;

  &lt;p&gt;또, gropu effect를 가법적으로 처리하고 있음을 볼 수 잇다. 이는 우리가 설정한 &lt;strong&gt;모델&lt;/strong&gt;로, group effect가 &lt;strong&gt;선형적으로만 작용할것이라는 다소 강한 assumption&lt;/strong&gt;이 들가 있는셈. (e.g &lt;script type=&quot;math/tex&quot;&gt;M*\tau_i&lt;/script&gt;였을 수도 있는데!) 이는 선형회귀와의 연관성을 보여준다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;여기까지는 one_way anv를 notation만 다르게 해서 나타낸 것이다. treatment들이 갖는 특성을 trt effect로 굳이 새로 notation한것.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 새로운 notation 새로 선언_2&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;근데 만약 treatment의 차이가 또다른 factor에 의한 차이도 섞여 있다면? (예를들어, 신약a,b,c의 테스트를 해보는데 인종1,2,3에 따라 신약의 효과가 다른경우.) 즉, 데이터에서 &lt;strong&gt;block effect도&lt;/strong&gt; 같은애들끼리 분류해주어, 다음과 같이 표현할 수 있다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;y_{ij}=M+\tau_i+\beta_j+\epsilon_{ij}, \epsilon_{ij}\sim N(0,\sigma^2)&lt;/script&gt;

&lt;p&gt;이전 형태의 확장이라고 보면 된다. 이때 &lt;script type=&quot;math/tex&quot;&gt;\sum_i^k\tau_i=0, \sum_j^b\beta_j=0&lt;/script&gt;이다. (이럼 편차의 의미가 사라지지만, 확장의 의미라 생각하고 받아들이자. sum=0이라는 점에서 여전히 편차의 느낌은 가지고 있다.)&lt;/p&gt;

&lt;p&gt;이 상태에서 똑간은 귀무가설 &lt;script type=&quot;math/tex&quot;&gt;H0:\tau_1=..=\tau_k=0&lt;/script&gt;을 검정하는 것.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 도출 시작&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;결론부터 말하자면, 앞선 &lt;strong&gt;one-way ANOVA&lt;/strong&gt;에선 &lt;strong&gt;SSTO=SSTR+SSE&lt;/strong&gt;임을 보였고, SSTR을 이용한 분산과 SSE를 이용한 분산을 통해 F 분포를 만들었다.&lt;/p&gt;

&lt;p&gt;block design에선 기존의 &lt;strong&gt;SSE로 치부&lt;/strong&gt;되었던 error가 &lt;strong&gt;block effect+error로 분해&lt;/strong&gt;되어,  &lt;strong&gt;SSTO=SSTR+(SSB+SSE)&lt;/strong&gt;가 된다. 즉, (만약 block effect가 실존했다면) 더 &lt;strong&gt;pure한 error만을 잡아내게 된다(!!!)&lt;/strong&gt;. 또한, SSTR,SSB,SSE를 이용하여 분산을 추정하고, 비교할 것이다.&lt;/p&gt;

&lt;p&gt;앞의 randomized block design에서, 각 trt별로, 각 block별로, 혹은 전체 평균을 data내에서 구할 수있다.&lt;/p&gt;

&lt;p&gt;즉, &lt;script type=&quot;math/tex&quot;&gt;\bar y{_i.}=\frac{\sum_i^ky_{ij}}{k}&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;\bar y_{.j}=\frac{\sum_j^by_{ij}}{b}&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;\bar y_{..}=\frac{\sum_i^k\sum_j^by_{ij}}{bk}&lt;/script&gt;. 또한, 우리의 선형가정에 따르면, &lt;script type=&quot;math/tex&quot;&gt;E(\bar y_{i.})=M+\tau_i,E(\bar y_{.j})=M+\beta_j, E(y_{..})=M&lt;/script&gt;이다.&lt;/p&gt;

&lt;p&gt;이때 one-way와 마찬가지로, &lt;strong&gt;group_mean에대해서 분산을 비교&lt;/strong&gt;해볼 수 있다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;treat별로 mean취한 &lt;script type=&quot;math/tex&quot;&gt;\bar y_{i.}&lt;/script&gt;의 변동 : &lt;strong&gt;under H0&lt;/strong&gt;, &lt;script type=&quot;math/tex&quot;&gt;\sum_i^k\frac{(\bar y_{i.}-\bar y_{..})^2}\sim\chi^2(k-1)&lt;/script&gt;&lt;/p&gt;

    &lt;p&gt;분모의 b를 위로 올리면 &lt;script type=&quot;math/tex&quot;&gt;\sum_i^k\frac{b(\bar y_{i.}-\bar y_{..})^2}=\frac{SSTR}{\sigma^2}\sim\chi^2(k-1)&lt;/script&gt;, under H0. (&lt;script type=&quot;math/tex&quot;&gt;M&lt;/script&gt;을 &lt;script type=&quot;math/tex&quot;&gt;\bar y_{..}&lt;/script&gt;로 대체했기 때문에 자유도-1) (여기서 H0는 &lt;script type=&quot;math/tex&quot;&gt;\tau_1=...=\tau_k=0&lt;/script&gt;, 즉 trt effect가 없다)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;이번엔 block별로 mean취한  &lt;script type=&quot;math/tex&quot;&gt;\bar y_{.j}&lt;/script&gt;의 변동 : &lt;strong&gt;under H0&lt;/strong&gt;, &lt;script type=&quot;math/tex&quot;&gt;\sum_j^b\frac{(\bar y_{.j}-\bar y_{..})^2}\sim\chi^2(b-1)&lt;/script&gt;&lt;/p&gt;

    &lt;p&gt;분모의 k를 위로 올리면 &lt;script type=&quot;math/tex&quot;&gt;\sum_j^b\frac{k(\bar y_{.j}-\bar y_{..})^2}=\frac{SSB}{\sigma^2}\sim\chi^2(b-1)&lt;/script&gt;, under H0. (여기서 H0는 &lt;script type=&quot;math/tex&quot;&gt;\beta_1=...=\beta_b=0&lt;/script&gt;,즉 block eff가 없다.)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;이번엔 그룹안에서의 데이터별, 즉 &lt;script type=&quot;math/tex&quot;&gt;y_{ij}&lt;/script&gt;의 변동. iid N에 등분산인 기본 set하에서라면, &lt;strong&gt;under H0가 ‘아니어도’&lt;/strong&gt; 항상 만족.&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{(y_{ij}-\mu_{ij})^2}{\sigma^2}\sim\chi^2(1)&lt;/script&gt;. one-way때와 마찬가지로 H0에 상관없이 전개되는 내용이기에, 각 level(즉, trt와 block의 combination)에 대해서 구해지고 있는것에 주의. 그리고 우리의 선형 가정에 따르면, &lt;script type=&quot;math/tex&quot;&gt;\frac{(y_{ij}-(M+\tau_i+\beta_j))^2}{\sigma^2}\sim\chi^2(1)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;\therefore\sum_i^k\sum_j^b\frac{(y_{ij}-(M+\tau_i+\beta_j))^2}{\sigma^2}\sim\chi^2(bk)&lt;/script&gt;&lt;/p&gt;

    &lt;p&gt;마지막으로 앞의 setting에 따라 각각 (&lt;script type=&quot;math/tex&quot;&gt;\hat M=\bar y_{..}, \hat\tau_i=\bar y_{i.}-\bar y_{..}, \hat\beta_j=\bar y_{.j}-\bar y_{..}&lt;/script&gt;)로 대체하면, &lt;script type=&quot;math/tex&quot;&gt;\sum \tau=0\sum\beta=0&lt;/script&gt;의 제약에 따라 &lt;script type=&quot;math/tex&quot;&gt;(1+k-1+b-1)=k+b-1&lt;/script&gt;개의 자유도를 잃은 셈이 된다.&lt;/p&gt;

    &lt;script type=&quot;math/tex; mode=display&quot;&gt;\therefore\sum_i^k\sum_j^b\frac{(y_{ij}-(\hat M+\hat\tau_i+\hat\beta_j))^2}{\sigma^2}\sim\chi^2(bk-(k+b-1))=\chi^2((b-1)(k-1))&lt;/script&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;마지막은 전체의 관점에서 각각의 데이터를 봐보자.&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{\sum\sum y_{ij}-\bar y_{..}}{\sigma^2}\sim\chi^2(bk-1)&lt;/script&gt;, under H0&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;이제 다왔다. SSTO를 block effect가 있다고 생각하고 decompose를 하면, one-way와 마찬가지로 cross product term이 사라지고 다음으로 분해된다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;SSTO=\sum\sum (y_{ij}-\bar y_P{..})^2=\sum\sum[(\bar y_{i.}-\bar y_{..}+(\bar y_{.j}-\bar y_{..})+(y_{ij}-(\bar y_{i.}+\bar y_{.j}-\bar y_{..}))]^2&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;=A^2+B^2+c^2=SSTR+SSB+SSE&lt;/script&gt;

&lt;p&gt;이때의 df역시 &lt;script type=&quot;math/tex&quot;&gt;bk-1=(k-1)+(b-1)+(bk-k-b+1)&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;즉, 다시 Cochran’s thm에 의해 SSTR, SSB, SSE가 indep이고,&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;F^*_{tr}=\frac{MSTR}{MSE}\sim F(k-1,(b-1)(k-1))&lt;/script&gt;, under H0. 이는 compound되어 있던 block effect 드러내고 trt가 유의한지를 가려내는 통계량. 덧붙여 block effect가 유의한지를 보는 &lt;script type=&quot;math/tex&quot;&gt;F^*_{b}=\frac{MSb}{MSE}\sim F(b-1,(b-1)(k-1))&lt;/script&gt;,under H0도 가능은 하지만, 주관심 대상이 아니기에 별로 하진 않는다.&lt;/p&gt;

&lt;p&gt;결국 one-way와 거의다 비슷하다. group_mean을 볼 대상이 한개가 아닌 두개였다뿐, group_mean을 2개의 factor(하나는 비록 block이지만)에 대해서 ss형태로 만들고 모두 분해하고, &lt;strong&gt;cochran’s thm&lt;/strong&gt;에 의해 indep를 밝힌후 &lt;strong&gt;F-dst&lt;/strong&gt;로 그 유의함을 검정하는 것이다.&lt;/p&gt;

&lt;p&gt;이를 그림으로 나타내면 아래와 같다.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;435&quot; alt=&quot;anova_table_rcbd&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090559-b8e17400-977d-11e9-9002-aea9bdb2e675.PNG&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;마지막-two-way-anova&quot;&gt;마지막 two way Anova&lt;/h2&gt;

&lt;p&gt;1trt와 1block이었던 block design과는 좀 다르다. &lt;strong&gt;보고싶은 factor가 2개&lt;/strong&gt;로, 이 경우 &lt;strong&gt;1)&lt;/strong&gt; factor1로 인한 차이가 유의한지, &lt;strong&gt;2)&lt;/strong&gt; factor2로 인한 차이가 유의한지, &lt;strong&gt;3)&lt;/strong&gt; factor1,factor2간에 &lt;strong&gt;상호작용&lt;/strong&gt;이 있는지를 검증할 수 있다.&lt;/p&gt;

&lt;p&gt;역시나 one-way때는 unbalanced에 대해서도 검정이 성립했지만, two-way에선 &lt;strong&gt;balanced에서만 검정식의 도출이 가능&lt;/strong&gt;하다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;block과 2way의 차이는? block로 intereaction eff가 있을수 잇지 않나? 그경우 그냥 2way라고 부르나, 어제 blck쓰고 언제 2way 쓰지?&lt;/p&gt;

  &lt;p&gt;앗 rcbd가 two-way anova without interaction이라고도 불린댄다..ㄷㄷ 그냥 분석자가 그렇다고 생각할때 쓰는듯? &lt;a href=&quot;http://www2.stat.duke.edu/~banks/111-lectures.dir/lect21.pdf&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;

  &lt;p&gt;또한, &lt;strong&gt;rcbd는 각 cell에 1개씩의 data가 있는 경우&lt;/strong&gt;, 즉 block을 나눈후 그 block내에서 factor만을 randomization한것에서도 &lt;strong&gt;작동할 수 있지&lt;/strong&gt;만, two-way anova는 아래의 그림처럼 cell에 여러개의 data가 필요하다!(데이터가 1개씩이라면  SSE의 df가 0이 되버려 분포가 성립이 안됀다.) 만약 rcbd를 했는데 intereaction이 예상된다면 two-way anova로 바꿔야하고, 이경우 cell에 data가 2개 이상있어야 한다.&lt;/p&gt;

  &lt;p&gt;이게 젤 좋은 참고인듯 &lt;a href=&quot;https://web.ma.utexas.edu/users/mks/384E/rcbd.pdf&quot;&gt;참고&lt;/a&gt;(1~2페이지)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;img width=&quot;443&quot; alt=&quot;two_way_anova&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090553-b7b04700-977d-11e9-8915-7ab925f206e4.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 언제쓰이나?&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;예를 들어 광고’전략’ {taste, price, discount}의 가짓수에 따른 매출의 평균이 다른지를 보고, 동시에 광고’매체’ {email, newspaper}의 가짓수에 따른 매출의 평균이 다른지를 보고 싶을 수 있다. (2factor). 그런데, 매체 e-mail을 통했을때  전략{taste,price,discoutn}의 형태가 다를 수 있다. (email을 자주보는 사람들과 신문을 자주보는 사람의 성향이 다를수 있으니까!) 고로, 두가지 factor간에 ‘상호작용’이 있는지도, 검정의 대상으로 삼고 싶은 경우. 이경우 2way anova가 사용된다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; notation&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;trt A의 가짓수가 1~a개, trt B의 가짓수가 1~b개, 각 가짓수의 combination마다 데이터가 1~n개 있다고 해보자.&lt;/p&gt;

&lt;p&gt;i번째 trt A의 mean&lt;script type=&quot;math/tex&quot;&gt;:=\bar y_{i..}=\frac{\sum_j^b \sum_k^n y_{ijk}}{bn}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;b번째 trt B의 mean&lt;script type=&quot;math/tex&quot;&gt;:=\bar y_{.j.}=\frac{\sum_i^a \sum_k^n y_{ijk}}{an}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;i,j번째 trt A과 trt B의 조합의 mean&lt;script type=&quot;math/tex&quot;&gt;:=\bar y_{ij.}=\frac{ \sum_k^n y_{ijk}}{n}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;overall mean&lt;script type=&quot;math/tex&quot;&gt;:=\bar y_{...}=\frac{\sum_i^a\sum_j^b \sum_k^n y_{ijk}}{abn}&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; Model&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;우리가 가정하는 관계식은 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;y_{ijk}=\mu_{ij}+\epsilon_{ijk}=M+\tau_{i}+\beta_j++\boldsymbol{\tau\beta_{ij}}+\epsilon_{ijk}&lt;/script&gt;
ij번째의 trt A과 trt B의 조합에 따른 &lt;strong&gt;interaction term&lt;/strong&gt; &lt;script type=&quot;math/tex&quot;&gt;\tau\beta_{ij}&lt;/script&gt;가 새로 생겼다. (우리가 가정하는 모델이 이렇다는것. 후에 저게 0인지를 검정.)&lt;/p&gt;

&lt;p&gt;또한 이들은 모두 편차항의 형태이므로 다음이 성립.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\sum_i^a\tau_i=\sum_j^b\beta_j=\sum_i^a\tau\beta_{ij}=\sum_j^b\tau\beta_{ij}=0&lt;/script&gt;

&lt;p&gt;&lt;strong&gt;&amp;lt; 도출&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;trt A에 따른 mean&lt;/strong&gt;들의 분포:&lt;/p&gt;

    &lt;p&gt;under Ho : &lt;script type=&quot;math/tex&quot;&gt;\tau_1=..=\tau_a=0&lt;/script&gt;,&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\bar y_{i..}\sim N(M,\frac{\sigma^2}{bn})&lt;/script&gt;, (위의 notation에 대한 조건으로 사라진것+H0하에서 0이된것 때문에, M만 남는다.)&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{bn\sum_i^a(\bar y_{i..}-\bar y_{...})^2}{\sigma^2}=\frac{SSA}{\sigma^2}\sim\chi^2(a-1)&lt;/script&gt;, under H0&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;trt b에 따른 mean&lt;/strong&gt;들의 분포:&lt;/p&gt;

    &lt;p&gt;under Ho : &lt;script type=&quot;math/tex&quot;&gt;\beta_1=..=\beta_a=0&lt;/script&gt;,&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\bar y_{.j.}\sim N(M,\frac{\sigma^2}{an})&lt;/script&gt; ,(위의 notation에 대한 조건으로 사라진것+H0하에서 0이된것 때문에, M만 남는다.)&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{an\sum_j^b(\bar y_{.j.}-\bar y_{...})^2}{\sigma^2}=\frac{SSb}{\sigma^2}\sim\chi^2(b-1)&lt;/script&gt;, under H0&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;trt A, trtB의 조합 내에서의 mean&lt;/strong&gt;들의 분포: (즉, 각 cell내의 1~n의 데이터를 mean취한것의 분포)&lt;/p&gt;

    &lt;p&gt;under Ho : &lt;script type=&quot;math/tex&quot;&gt;\tau\beta_1=..=\tau\beta_{ab}=0&lt;/script&gt;,&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\bar y_{ij.}\sim N(M+\tau_i+\beta_j,\frac{\sigma^2}{n})&lt;/script&gt;. (cell내에서만 합친거라서, 위의 제약으로 사라질게 없음. 단지 H0로 &lt;script type=&quot;math/tex&quot;&gt;\tau\beta{ij}&lt;/script&gt;만이 사라졌다.)&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{n\sum_i^a\sum_j^b(\bar y_{i..}-(\hat M+\hat\tau_i+\hat\beta_j))^2}{\sigma^2}\sim\chi^2(ab-(1+a-1+b-1))&lt;/script&gt;, under H0&lt;/p&gt;

    &lt;p&gt;이때 &lt;script type=&quot;math/tex&quot;&gt;\hat M+\hat\tau_i+\hat\beta_j=\bar y_{...}+(\bar y_{i..}- \bar y_{...})+(\bar y_{.j.}-\bar y_{...})=\bar y_{i..}+\bar y_{.j.}-\bar y_{...}&lt;/script&gt;. 따라서,&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{n\sum_i^a\sum_j^b(\bar y_{i..}-(\bar y_{i..}+\bar y_{.j.}-\bar y_{...}))^2}{\sigma^2}=\frac{SSAB}{\sigma^2}\sim\chi^2((a-1)(b-1))&lt;/script&gt;, under H0.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;잘보면 형태가 interaction을 애초에 고려하지 않은 rcbd에서의 &lt;strong&gt;SSE와 완벽히 같음&lt;/strong&gt;을 알 수 있다. interaction자체가 모델의 고려대상에 없엇던 경우 H0에 관계 없는 SSE가 해당 분포를 따랐지만, 현재 모델은 각 cell별로도 다를 수 있다는 interaction term을 넣어준 것. 즉, &lt;strong&gt;더욱더 pure한 error를 잡는다&lt;/strong&gt;고도 볼 수 있다.&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;이제 H0에 의존하지 않는, indep N이고 등분산이면 만족하는 성질&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;y_{ijk}\sim N(M+\tau_i+\beta_j+\tau\beta_{ij},\sigma^2)&lt;/script&gt;, 근데 평균을 모르니까 추정.&lt;/p&gt;

    &lt;script type=&quot;math/tex; mode=display&quot;&gt;\hat M+\hat \tau_i+\hat \beta_j+\hat {\tau\beta}_{ij}=\bar y_{...}+(\bar y_{i..}-\bar y_{...})+(\bar y_{.j.}-\bar y_{...})+(\bar y_{ij.}-\bar y_{i..}-\bar y_{.j.}+\bar y_{...})=\bar y_{ij.}&lt;/script&gt;

    &lt;p&gt;즉, cell의 mean으로 추정한것과 같음. cell이 ab개니까,&lt;/p&gt;

    &lt;script type=&quot;math/tex; mode=display&quot;&gt;\frac{\sum_i^a\sum_j^b\sum_k^n(\bar y_{i..}-\bar y_{ij.})^2}{\sigma^2}=\frac{SSE}{\sigma^2}\sim\chi^2(ab(n-1))&lt;/script&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;이제 주어진것을 바탕으로, 또 cochran’s thm을 사용할 수 있따.&lt;/p&gt;

&lt;p&gt;SSTO=SSA+SSB+SSAB+SSE이고, df도 만족을 하기에 (풀어보면 cross product가 다 사라짐)&lt;/p&gt;

&lt;p&gt;이제 다음 3가지를 검정할 수 있게 되었다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;trt A에 따른 평균차&lt;/strong&gt;가 유의하냐 : 
&lt;script type=&quot;math/tex&quot;&gt;f_A=\frac{MSA}{MSE}\sim F(a-1,ab(n-1)), under H0&lt;/script&gt;
&lt;strong&gt;trt B에 따른 평균차&lt;/strong&gt;가 유의하냐 :
&lt;script type=&quot;math/tex&quot;&gt;f_B=\frac{MSB}{MSE}\sim F(b-1,ab(n-1)), under H0&lt;/script&gt;
&lt;strong&gt;trt B와 trt A의 interaction&lt;/strong&gt;이 유의하냐:
&lt;script type=&quot;math/tex&quot;&gt;f_{AB}=\frac{MSAB}{MSE}\sim F((a-1)(b-1),ab(n-1)), under H0&lt;/script&gt;
&lt;img width=&quot;432&quot; alt=&quot;two_way_anova2&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090554-b848dd80-977d-11e9-880b-47147e702600.PNG&quot; /&gt;&lt;/p&gt;

</description>
        <pubDate>Wed, 27 Feb 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%ED%86%B5%EA%B3%84%EA%B8%B0%EC%B4%88/2019/02/27/%EA%B0%9C%EC%9D%B8%EC%A0%81%EC%9D%B8-%ED%86%B5%EA%B3%84-%EB%B0%A9%EB%B2%95%EB%A1%A0-%EB%B3%B5%EC%8A%B5-(3.-%EB%8B%A4%EC%96%91%ED%95%9C-Anova%EA%B2%80%EC%A0%95).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%ED%86%B5%EA%B3%84%EA%B8%B0%EC%B4%88/2019/02/27/%EA%B0%9C%EC%9D%B8%EC%A0%81%EC%9D%B8-%ED%86%B5%EA%B3%84-%EB%B0%A9%EB%B2%95%EB%A1%A0-%EB%B3%B5%EC%8A%B5-(3.-%EB%8B%A4%EC%96%91%ED%95%9C-Anova%EA%B2%80%EC%A0%95).html</guid>
        
        <category>basic statistics</category>
        
        <category>Anova</category>
        
        <category>Randomized block design</category>
        
        <category>two-way Anova</category>
        
        
        <category>통계기초</category>
        
      </item>
    
      <item>
        <title>[통계기초 정리] 개인적인 통계 방법론 복습 (2. 추정과 검정)</title>
        <description>&lt;p&gt;기초 지식이지만 모든 고급분석의 근반이 되기에, 기초를 탄탄히 하고자 한번의 수업수강과 한번의 청강, 한번의 도강(…)까지 했다. 그치만 매번 공부하고 공부해도 까먹는 통계 기초. 늘 책찾고 헤매는 것이 힘들어서 한번에 정리해보았다.&lt;/p&gt;

&lt;h3 id=&quot;about-추정&quot;&gt;about 추정&lt;/h3&gt;

&lt;p&gt;통계학의 메인 줄기에는  &lt;strong&gt;추정&lt;/strong&gt;과 &lt;strong&gt;가설검정&lt;/strong&gt;이 있었다.&lt;/p&gt;

&lt;p&gt;&amp;lt; 좋은 추정량의 성질&amp;gt;&lt;/p&gt;

&lt;p&gt;확률표본(&lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_n&lt;/script&gt;)으로 미지의 모수 &lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;를 추정하는경우. 어떤 함수 T를 거쳐 나온 통계량 &lt;script type=&quot;math/tex&quot;&gt;T(X_1,..,X_n)=T_n&lt;/script&gt;이라할때, 좋은 추정량의 성질 3가지는 다음과 같다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;불편추정량(unbiasedness)&lt;/strong&gt; :&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;E(T_n)=\theta&lt;/script&gt;. 이를 만족하는 추청량 &lt;script type=&quot;math/tex&quot;&gt;T_n&lt;/script&gt;은 &lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;에 대한 불편추정량&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;유효성(efficiency)&lt;/strong&gt; :&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;에 대한 두 불편추정량 &lt;script type=&quot;math/tex&quot;&gt;T_{n_1},T_{n_2}&lt;/script&gt;가 있을때, &lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
Var(T_{n_1})&lt;Var(T_{n_2}) %]]&gt;&lt;/script&gt;이면, &lt;script type=&quot;math/tex&quot;&gt;T_{n_1}&lt;/script&gt;을 더 유효한 추정량이라 지칭한다.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;일치성(consistency)&lt;/strong&gt;:&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
\lim_{n\rightarrow\infty}\Pr(|T_n-\theta|&lt;\epsilon)=1 %]]&gt;&lt;/script&gt;
이를 만족하는 애를 일치추정량. 불편성과 비슷해보이지만, 무한대의 개념이고, 일치성에는 Expectation은 쓰이지도 않았음.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;구간 추정&lt;/strong&gt;은 간단해서 생략.&lt;/p&gt;

&lt;p&gt;if $X_i\sim??[\mu,\sigma^2],\forall i$, $\sigma^2$ is unknown, &lt;script type=&quot;math/tex&quot;&gt;n\ge30&lt;/script&gt;인 경우의 평균에 대한 구간추정.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;이 경우 $\sigma$를 모르지만 원래의 분포가 N이 아니기에 sample_var로 치환하고 t-distn을 사용할 수 없다. 그러나 &lt;strong&gt;By Slutsky thrm&lt;/strong&gt;, $\frac{\bar X-\mu}{S/n}\sim^AN(0,1)$로 해도 무방!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Slutsky thrm&lt;/strong&gt; : 극한분포에서 매우자주 사용되는 툴중 하나.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;$X\rightarrow^p a$&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;$Y\rightarrow^d Z$&lt;/p&gt;

    &lt;p&gt;=&amp;gt; $XY \rightarrow^d aZ$&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;위의 경우 $S\rightarrow^p\sigma$라서 성립하게 된다.&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;C.I의 해석 :&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;C.I. &lt;script type=&quot;math/tex&quot;&gt;\Pr[\hat{\theta_L}\le\theta\le\hat{\theta_U}]=(1-\alpha)&lt;/script&gt;에서, &lt;script type=&quot;math/tex&quot;&gt;\hat{\theta_U},\hat{\theta_L}&lt;/script&gt;은 sampling마다 바뀔 수 있다. 동일한 방법에서 이루어진 각 시행에서, 그들이 실제 &lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;를 포함할 확률이 &lt;script type=&quot;math/tex&quot;&gt;(1-\alpha)&lt;/script&gt;%인것!&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;&amp;lt; 가설 검정&amp;gt;&lt;/p&gt;

&lt;p&gt;귀무가설 : 가급적 지키려고 하는 가설. 또는 강력한 증거가 없는한 따르려는 가설.&lt;/p&gt;

&lt;p&gt;귀무가설에 좀더 무게가 쏠려 있으므로, 가급적 지켜야 하는 귀무가설을 잘못 기각해버린 1종오류가 더 심각한것.&lt;/p&gt;

&lt;h3 id=&quot;드디어-평균검정&quot;&gt;드디어 평균검정&lt;/h3&gt;

&lt;p&gt;큰 갈래는 데이터가 &lt;strong&gt;정규분포를 따를 경우&lt;/strong&gt;는 정규분포의 성질을 이용하여 t-분포를 이용한 평균검정, 데이터가 정규분포를 따르지 않지만, &lt;strong&gt;데이터의 수가 충분히 큰 경우&lt;/strong&gt; CLT를 이용한 평균에 대한 검정.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 1.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1) &lt;script type=&quot;math/tex&quot;&gt;X\sim?(\mu_1,\sigma_1^2), Y\sim?(\mu_2,\sigma_2^2)&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;X,Y&lt;/script&gt; are indep, 2) &lt;script type=&quot;math/tex&quot;&gt;n_1,n_2&lt;/script&gt; 이 충분히 큰수.&lt;/p&gt;

&lt;p&gt;즉, X,Y의 &lt;strong&gt;분포는 모르지만 데이터가 충분히&lt;/strong&gt; 크다. (roughly over 30). 이 경우 대표본이론, 혹은 극한분포이론을 적용할 수 있기에, 손쉬워진다.&lt;/p&gt;

&lt;p&gt;By CLT, &lt;script type=&quot;math/tex&quot;&gt;\bar X-\bar Y\sim^A N(\mu_1-\mu_2,\frac{\sigma_1^2}{n_1}+\frac{\sigma_2^2}{n_2})&lt;/script&gt;,&lt;/p&gt;

&lt;p&gt;Under H0, &lt;script type=&quot;math/tex&quot;&gt;\frac{\bar X-\bar Y}{\sqrt{\frac{\sigma_1^2}{n_1}+\frac{\sigma_2^2}{n_2}}}\sim^A N(0,1)&lt;/script&gt;. &lt;strong&gt;통계량 분포&lt;/strong&gt;를 알면 지지고 볶고가 가능.&lt;/p&gt;

&lt;p&gt;그러나 &lt;script type=&quot;math/tex&quot;&gt;\sigma_1,\sigma_2&lt;/script&gt;를 모르기에, 실제로 저 통계량은 구할 수 없음. 하지만 충분히 큰수이기에,  &lt;strong&gt;slutsky thrm&lt;/strong&gt;으로 역시나 근사가 가능.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{\bar X-\bar Y}{\sqrt{\frac{S_1^2}{n_1}+\frac{S_2^2}{n_2}}}\sim^A N(0,1)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;\because S_1\rightarrow^p\sigma_1&lt;/script&gt;, under H0&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Case 2.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;1) &lt;script type=&quot;math/tex&quot;&gt;X\sim N(\mu_1,\sigma_1^2), Y\sim N(\mu_2,\sigma_2^2)&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;X,Y&lt;/script&gt; are indep. 2) &lt;script type=&quot;math/tex&quot;&gt;n_1,n_2&lt;/script&gt;이 별로 크지 못함.&lt;/p&gt;

&lt;p&gt;이 경우 &lt;strong&gt;데이터가 정규분포&lt;/strong&gt;를 따르기에, &lt;script type=&quot;math/tex&quot;&gt;n_1,n_2&lt;/script&gt; 이  작더라도 가능.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\bar X-\bar Y\sim N(\mu_1-\mu_2,\frac{\sigma_1^2}{n_1}+\frac{\sigma_2^2}{n_2})&lt;/script&gt;, exactly. 근데 sigma를 모름. 대표본으로 손쉽게 갈수도 있지만, &lt;strong&gt;정규분포의 경우 소표본이라도 t분포가 있음&lt;/strong&gt;. 근데 또, 이때는 &lt;strong&gt;이분산일 경우 분포가 도출이 안됌&lt;/strong&gt;..&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;이분산의 경우 welch test가 있다. 그러나 별로 인정 못받는 검정법.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;‘값은 알 수 없지만, 또 평균도 모르지만, 두 r,v의 분산이 같다’라는 &lt;strong&gt;비현실적인 등분산 가정 필요&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;if 등분산case, pooled variance에 대해서.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\hat\sigma^2=S_p:=\frac{(n_1-1)S_1^2+(n_2-1)S_2^2}{(n_1-1+n_2-1)}&lt;/script&gt;, 즉, 표본분산을 데이터수에 따라 가중평균한것이 unbiased중에서도 most efficient하다는 것이 증명. (이런형태의 pooled variance가 MVUE이다.)&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\therefore \frac{\bar X-\bar Y}{\sqrt{S_p^2(\frac{1}{n_1}+\frac{1}{n_2})}}\sim t(n_1+n_2-2)&lt;/script&gt;, under H0.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;by additivity prop of Chisq,&lt;/p&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;\frac{(n_1-1)S_1^2+(n_2-1)S_2^2}{\sigma^2}\sim\chi^2(n_1+n_2-2)&lt;/script&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\therefore \frac{(n_1+n_2-2)S_p^2}{\sigma^2}\sim\chi^2(n_1+n_2-2)&lt;/script&gt;, by def of &lt;script type=&quot;math/tex&quot;&gt;S_p&lt;/script&gt;. 여기서 t-dist도출.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Case3&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;그럼 데이터 갯수도 작고, 데이터의 모집단 분포가 정규가정에도 무리가 있는 경우 어떡하냐?! 즉,&lt;/p&gt;

&lt;p&gt;1) &lt;script type=&quot;math/tex&quot;&gt;X\sim ?(\mu_1,\sigma_1^2), Y\sim ?(\mu_2,\sigma_2^2)&lt;/script&gt;,&lt;script type=&quot;math/tex&quot;&gt;X,Y&lt;/script&gt; are indep. 2) &lt;script type=&quot;math/tex&quot;&gt;n_1,n_2&lt;/script&gt;이 별로 크지 못함.&lt;/p&gt;

&lt;p&gt;그나마 &lt;strong&gt;Bootstrap&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Under Ho, 평균에 차이가 없으니까, X_data, Y_data를 shuffle해도 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;H0하에서는 그래도 말이 된다는 얘기. 귀무가설하의 통계량의 분포를 구하려는 거니까 H0하라는 틀안에서만 생각해도 된다.&lt;/p&gt;

  &lt;p&gt;다른 분포이더라도, 평균이 같다면 E(X+Y)=E(X)+E(Y)니까, 평균은 여전히 같을것. 고로 sample mean으로 검정할때 둘이 바꿔도 H0하에서는 말된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;각각 데이터가 X 10개, Y 10개 있었다면 &lt;script type=&quot;math/tex&quot;&gt;_{20}C_{10}&lt;/script&gt;번의 shuffle이 가능하고, 각각의 시행에 대해 &lt;script type=&quot;math/tex&quot;&gt;\bar X_{10}-\bar Y_{10}&lt;/script&gt;의 값들을 측정할 수 있음. 이를 ‘&lt;strong&gt;귀무가설하의 표본분포’&lt;/strong&gt;로 생각하여, 우리가 실제 얻은 &lt;script type=&quot;math/tex&quot;&gt;\bar x-\bar y&lt;/script&gt;가 &lt;strong&gt;분포상의 어느 percentile&lt;/strong&gt;에 위치하는지를 통해 검정을 할 수 있음!&lt;/p&gt;

&lt;p&gt;bootstrap은 신박하고 손쉽지만, 실험설계를 어떻게 해야 내 의도대로 설계된건지 잘 따져봐야한다. 그렇기에 더 생각하는 능력이 필요.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;모비율 검정&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;생략. 버놀리에서 &lt;script type=&quot;math/tex&quot;&gt;\bar X,\bar Y&lt;/script&gt;를 정규근사+slutsky해서 푸는것. 크게 다르지는 않다. 충분히 크지 않은 경우엔 역시나 bootstrap뿐..(만약 &lt;script type=&quot;math/tex&quot;&gt;n_1&gt;&gt;n_2&lt;/script&gt;인 경우엔 어떡할까? size bias를 줄여주기 위해 50:50으로 뽑을까??)&lt;/p&gt;

&lt;h3 id=&quot;paired-data-의-평균검정&quot;&gt;Paired data 의 평균검정!&lt;/h3&gt;

&lt;p&gt;paired검정의 가장 대표적인 경우 : paired t-test.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;paired는 굳이 그 본연의 특성이 짝지어져 있지 않더라도 필요한 경우도 있음.&lt;/p&gt;

  &lt;p&gt;Ex) blocking factor가 있는 경우. X : Finance팀의 income과 Y : Marketing팀의 income을 비교하는데, 만약 GPA가 둘의 income에 모두 영향을 준것같다면? 여전히 &lt;script type=&quot;math/tex&quot;&gt;\bar X-\bar Y&lt;/script&gt;로 비교할 수 있지만, 각각의 variance가(제3의 요인으로) 커져 있는 상태기에 Type 2 error의 확률이 커진다. 이때, 순수한 finance&amp;lt;-&amp;gt; marketing의 영향을 보기 위해 GPA가 비슷한 애들끼리 pair를 맺어줄수도. (뒤에 anova에서 확장되어 다룬다)&lt;/p&gt;

  &lt;p&gt;근데 사실, 가법적으로 영향을 안미칠 수도 있는데, 상당히 강한 가정이 들어간것. ex) E(Finance_income_GPA4.0)=M_f + alpha,  E(Marketing_income_GPA4.0)=M_m + alpha. 라서 block design하면 효과를 뺄 수 있다는 가정. Finance에서의 4.0이 marketing에서의 학점4.0과 의미가 다를수도 있는데, 그냥 빼면 된다는 생각&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;암튼, &lt;strong&gt;pair의 평균에 차이가 없다&lt;/strong&gt;를 검정하고픔.&lt;/p&gt;

&lt;p&gt;paired_data &lt;script type=&quot;math/tex&quot;&gt;(X_1,Y_1),..,(X_n,Y_n)&lt;/script&gt;에서 &lt;script type=&quot;math/tex&quot;&gt;D_i=(X_i-Y_i)&lt;/script&gt;.&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;X,Y ~ N&lt;/strong&gt;, then (t-tets는 &lt;strong&gt;다변량정규가정&lt;/strong&gt;을 필요로한다는거 상기!)&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;D_i\sim N(\mu_d,\sigma^2_d)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;H0:\mu_d=0&lt;/script&gt;. paired의 diff를 각각 하나의 데이터로 생각한것.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;D_i=(X_i-Y_i)&lt;/script&gt;이므로, &lt;script type=&quot;math/tex&quot;&gt;D_i\sim N(\mu_d,\sigma^2_d)&lt;/script&gt;는 굳이 풀어쓰면 &lt;script type=&quot;math/tex&quot;&gt;D_i\sim N(\mu_x-\mu_y,\sigma_x^2+\sigma_y^2-2\sigma_x\sigma_y)&lt;/script&gt;이다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;또한, D의 분산을 모르므로,&lt;script type=&quot;math/tex&quot;&gt;D_i&lt;/script&gt;들의 sample variance를 이용하여 t-dist를 사용
&lt;script type=&quot;math/tex&quot;&gt;\frac{\bar D-0}{\sqrt{S_d^2/n_d}}\sim t(n_d-1), underH_0&lt;/script&gt;&lt;/p&gt;

&lt;h3 id=&quot;분산에-대한-검정-using-f-dist&quot;&gt;분산에 대한 검정 using F-dist&lt;/h3&gt;

&lt;p&gt;Case :&lt;/p&gt;

&lt;p&gt;1) &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_{n_1}\sim^{iid}N(\mu_x,\sigma_x^2)&lt;/script&gt;,&lt;/p&gt;

&lt;p&gt;2)&lt;script type=&quot;math/tex&quot;&gt;Y_1,..,Y_{n_1}\sim^{iid}N(\mu_y,\sigma_y^2)&lt;/script&gt;,&lt;/p&gt;

&lt;p&gt;3)&lt;script type=&quot;math/tex&quot;&gt;X,Y&lt;/script&gt; are indep. 를 만족해야 사용할 수 있다.&lt;/p&gt;

&lt;p&gt;Variance에 대한 검정은 &lt;script type=&quot;math/tex&quot;&gt;\sigma_x^2-\sigma_y^2&lt;/script&gt;로 볼 수 없다. (이 방식으로 표본분포 도출된게 없다.) 고로, &lt;script type=&quot;math/tex&quot;&gt;\frac{\sigma_x^2}{\sigma_y^2}&lt;/script&gt;의 형태로 본다.&lt;/p&gt;

&lt;p&gt;그럼 &lt;script type=&quot;math/tex&quot;&gt;\frac{\sigma_x^2}{\sigma_y^2}&lt;/script&gt;의 분포 형태는? 완전 간단. 거의 맞춤형으로 F분포가 잇음&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;$\frac{(n_1-1)S_1^2}{\sigma_x^2}\sim\chi^2(n_1-1)​$&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;$\frac{(n_2-1)S_2^2}{\sigma_y^2}\sim\chi^2(n_2-1)$&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;X,Y&lt;/script&gt; are indep&lt;/p&gt;

    &lt;p&gt;=&amp;gt; &lt;script type=&quot;math/tex&quot;&gt;\frac{\frac{(n_1-1)S_1^2}{\sigma_x^2}/(n_1-1)}{\frac{(n_2-1)S_2^2}{\sigma_y^2}/(n_2-1)}=\frac{\sigma_y^2}{\sigma_x^2}\frac{S_1^2}{S_2^2}\sim F(n_1-1,n_2-1)&lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;또한, F분포는 &lt;script type=&quot;math/tex&quot;&gt;F_{1-\frac{\alpha}{2},n_1,n_2}=1/F_{\frac{2}{\alpha},n_1,n_2}&lt;/script&gt;라는 편리한 성질이 있어서, &lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
\Pr(lb&lt;\frac{\sigma_y^2}{\sigma_x^2}\frac{S_1^2}{S_2^2}&lt;ub)=1-\alpha %]]&gt;&lt;/script&gt;가지고 이리저리 볶아서 CI만들 수 잇다.&lt;/p&gt;
</description>
        <pubDate>Tue, 12 Feb 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%ED%86%B5%EA%B3%84%EA%B8%B0%EC%B4%88/2019/02/12/%EA%B0%9C%EC%9D%B8%EC%A0%81%EC%9D%B8-%ED%86%B5%EA%B3%84-%EB%B0%A9%EB%B2%95%EB%A1%A0-%EB%B3%B5%EC%8A%B5-(2.-%EC%B6%94%EC%A0%95%EA%B3%BC-%EA%B2%80%EC%A0%95).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%ED%86%B5%EA%B3%84%EA%B8%B0%EC%B4%88/2019/02/12/%EA%B0%9C%EC%9D%B8%EC%A0%81%EC%9D%B8-%ED%86%B5%EA%B3%84-%EB%B0%A9%EB%B2%95%EB%A1%A0-%EB%B3%B5%EC%8A%B5-(2.-%EC%B6%94%EC%A0%95%EA%B3%BC-%EA%B2%80%EC%A0%95).html</guid>
        
        <category>basic statistics</category>
        
        <category>estimator</category>
        
        <category>statistical test</category>
        
        <category>t - test</category>
        
        <category>paired t - test</category>
        
        
        <category>통계기초</category>
        
      </item>
    
      <item>
        <title>[데이터분석 정리] Mahalanobis거리와 MCD 개인적 정리</title>
        <description>&lt;p&gt;마할라노비스 거리는 다변량 거리의 기본이다. 개념자체는 쉽다. 다변량의 데이터에서, 분포의 형태를 고려하여 거리를 재겠다는 문제의식에서 등장한 거리 척도이다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;d(u,v)=\sqrt{(u-v)\Sigma^{-1}(u-v)^T}&lt;/script&gt;

&lt;p&gt;다변량의 데이터 &lt;script type=&quot;math/tex&quot;&gt;u&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;v&lt;/script&gt;의 mahalanobis거리를 구하는 식이다. 대표적으로는 &lt;script type=&quot;math/tex&quot;&gt;u&lt;/script&gt;에는 각 데이터, &lt;script type=&quot;math/tex&quot;&gt;v&lt;/script&gt;는 데이터의 평균이 될것이다. (예를 들면 &lt;script type=&quot;math/tex&quot;&gt;u=&lt;/script&gt;(키1,몸무게1), &lt;script type=&quot;math/tex&quot;&gt;v=&lt;/script&gt;(키평균,몸무게평균))&lt;/p&gt;

&lt;p&gt;식을 보면, 마치 단변수에서 z-score를 구하듯이, covariance matrix의 inverse matrix를 곱하여 거리를 재는 방식이다. 이를 통해 변수들간의 correlation등 분포를 고려하여 거리를 잴 수 있다. 실제로, 모든 변수들이 independant이고 variance가 1로 정규화되어 있다면, &lt;script type=&quot;math/tex&quot;&gt;\Sigma=\boldsymbol I&lt;/script&gt;가 되고, 마할라노비스 거리는 유클리드 거리와 같아진다.&lt;/p&gt;

&lt;p&gt;(즉, &lt;script type=&quot;math/tex&quot;&gt;d(u,v)=\sqrt{(u-v)I^{-1}(u-v)^T}=\sqrt{(u-v)\cdot(u-v)}=\sqrt{(u_1-v_1)^2+..+(u_p-v_p)^2}&lt;/script&gt;) 아래의 그림처럼, 데이터들이 강한 correlation을 가지고 있는 경우 그 분포를 고려하여, 유클리디언 상으로는 같은 거리일 지라도 correlation에 따라 중심에서 먼 정도가 달라지게 된다. 그림 상의 두 빨간 점은 모두 원점으로부터의 거리는 같지만, mahalanobis는 등고선에서 나와있듯이, x축의 데이터를 중심에서 더 가까운 데이터라고 본다. (correlation을 고려하였을때 y축의 데이터가 더 rare한 경우이기 때문이다.)&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;488&quot; alt=&quot;mahalanobis1&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60076891-a8bc9b00-9763-11e9-9116-221ba9a1274e.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;scipy : https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.mahalanobis.html&lt;/p&gt;

&lt;p&gt;sklearn : https://scikit-learn.org/stable/auto_examples/covariance/plot_mahalanobis_distances.html&lt;/p&gt;

&lt;h3 id=&quot;distribution-of-distance&quot;&gt;distribution of distance&lt;/h3&gt;

&lt;p&gt;원문 : https://core.ac.uk/download/pdf/22873068.pdf&lt;/p&gt;

&lt;p&gt;신기한점은, 만약 데이터가 &lt;strong&gt;다변량 정규분포를&lt;/strong&gt; 따른다면, distance의 &lt;strong&gt;exact distribution&lt;/strong&gt;을 알 수 있다. (물론 그 distribution이 true parameter &lt;script type=&quot;math/tex&quot;&gt;\mu,\Sigma​&lt;/script&gt;에 베이스하기에 결국은 근사적.) &lt;strong&gt;변수가 p개인&lt;/strong&gt; 데이터의 maha거리의 제곱은, 다음의 &lt;strong&gt;카이제곱분포&lt;/strong&gt;를 가진다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;d^2_{\Sigma}(X_i,\mu)\sim \chi^2_{p}&lt;/script&gt;

&lt;p&gt;카이제곱분포의 성질에 따라 평균p와 분산 2p도 자연스레 내포한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;느낌적으로는, maha거리가 마치 p차원의 데이터에 대한 normalize처럼 작용하기에, 표준정규분포Z를 제곱해서 p개 더한듯한 느낌이라고 생각하자&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;(그 외에도, 이리 저리 조합해서 beta 분포, F분포 등을 도출해낼 수 있다. 이건 너무 깊게 들어가기에, 논문을 참고하는것이 좋다.)&lt;/p&gt;

&lt;p&gt;이에 따라 카이제곱분포의 0.975 quantile지점까지를 기준으로 삼고 &lt;strong&gt;다변량의 관점&lt;/strong&gt;에서, outlier이다 아니다 등으로 딱 떨어지게 논할수가 있다. 이에 따라 단변량의 z-score를 고려하는 것보다 좀더 합리적인 outlier를 검출할 수 있게 된다.&lt;/p&gt;

&lt;p&gt;그러나 (뒤에설명할) MCD를 이용한 robust에서는 exact distribution을 도출할 수 없다. MCD estimator역시 consistency를 가지기에 근사적으로 카이제곱을 따른다 할 수 있지만, 경험적으로 0.975로 끊을 경우 필요이상을 이상치라고 말하게 된다고 한다. 뒤에서 더 자세히 설명하겠다.&lt;/p&gt;

&lt;h1 id=&quot;minimum-covaraicen-determinantmcd&quot;&gt;Minimum covaraicen determinant(MCD)&lt;/h1&gt;

&lt;p&gt;원문 : https://wis.kuleuven.be/stat/robust/papers/2010/wire-mcd.pdf&lt;/p&gt;

&lt;p&gt;Mahalanobis를 구하기 위해선 &lt;strong&gt;covariance matrix&lt;/strong&gt;를 구해야하고, 사실 이것이 majhalanobis거리의 핵심이다. 그러나 variance는 제곱텀에서 만들어지기에, &lt;strong&gt;outlier에 굉장히 취약&lt;/strong&gt;하다. 따라서 몇개의 이상한 극단치 데이터들이 covairance matrix를 망칠 수 있고 이에 따라 합리적이지 않은 distance가 측정될 수 있는것이다. 이렇듯 oulier에 취약한 variance의 문제를 완화하고자 나온 개념이 바로 MCD이다. &lt;strong&gt;robust variance&lt;/strong&gt;정도로 받아들이면 좋다. Variance matrix를 이용하는 mahalanobis 거리를 공부하면서 접하게 된건데, mcd를 이용할 경우 아래의 그림과 같이, 소수의 outlier에 대해 영향을 받지 않고 variance를(나아가 mahalanobis 거리를) 계산하게 된다. 단변수뿐아니라 다변수에서도 활용가능하다. robust한 cov_matrix를 구하는것이기에, &lt;strong&gt;outlier로부터 robust한 correlation을 구하는데도 사용&lt;/strong&gt;될 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;384&quot; alt=&quot;mahal1&quot; src=&quot;https://user-images.githubusercontent.com/31824102/54182455-e8c57e00-44e4-11e9-8e34-a71efd12540f.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;정의는 간단하다. 주어진 n*p의 데이터에서 &lt;strong&gt;Determinant of sample covariance matrix&lt;/strong&gt;를 &lt;strong&gt;최소로 만드는 h개의 데이터&lt;/strong&gt;를 뽑아 그들만 이용하여 variance나 mean을 구한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Cov_mat의 Determinant는 단변수의 std와 아주아주 rough하게 연관되 있다. multivariate normal일경우 어느정도 &lt;a href=&quot;https://math.stackexchange.com/questions/889425/what-does-determinant-of-covariance-matrix-give&quot;&gt;성립&lt;/a&gt;. 즉 coaviance matrix의 ‘크기’를 determinant로 계산한다고 보면 된다. 단변수인 경우 그냥 variance를 최소로 하는 h개를 iteration돌며 뽑아서 계속 계산해본다생각하면 된다. 그러나 matrix의 경우 크기라는 개념이 애매해지기 때문에 determinant를 사용하게 된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;MCD계산에 사용되는 데이터의 갯수 h는 &lt;script type=&quot;math/tex&quot;&gt;(n+p+1)/2\le h\le n&lt;/script&gt;을 이용한다. (&lt;script type=&quot;math/tex&quot;&gt;2p\le n&lt;/script&gt;의 조건이 필요하지만 차원의 저주로부터 안정적이기 위해 &lt;script type=&quot;math/tex&quot;&gt;5p\le n&lt;/script&gt;정도를 요한다고 한다.) 이 경우 consistenct나 asymptotic normality등의 &lt;strong&gt;대표본성질이 여전히 만족&lt;/strong&gt;한다는 특성이 있다.&lt;/p&gt;

&lt;p&gt;또한, MCD estimator(mu,sigma)는 &lt;strong&gt;affine equivariant&lt;/strong&gt;하다는 특성이 있다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;affine equivariant란?&lt;/p&gt;

  &lt;p&gt;for any nonsingular matrix &lt;script type=&quot;math/tex&quot;&gt;A&lt;/script&gt; and constant vector &lt;script type=&quot;math/tex&quot;&gt;b\in R^p&lt;/script&gt;에 대해서,&lt;/p&gt;

  &lt;p&gt;‘(AX + b)의 MCD_mu’ = A’(X)의 MCD_mu’ + b&lt;/p&gt;

  &lt;p&gt;‘(AX + b)의 MCD_sigma’ = A’(X)의 MCD_sigma’ A^T&lt;/p&gt;

  &lt;p&gt;즉, 우리가 흔히 아는 mu와 variance의 사칙연산의 성질이 MCD estimator에게도 그대로 유지된다!&lt;/p&gt;

  &lt;p&gt;왜? 모든 subset h에 대해서, Determinant의 order가 유지되기 때문에. 원문참조&lt;/p&gt;

  &lt;p&gt;&lt;img width=&quot;563&quot; alt=&quot;mcd1&quot; src=&quot;https://user-images.githubusercontent.com/31824102/54182457-e95e1480-44e4-11e9-8400-98af856d5b91.PNG&quot; /&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이러한 방법을 통해, 극단적인 데이터를 제외하고 좀더 robust한 covariance matrix를 계산할 수 있게 된다. 또한, covariance matrix의 off-diagonal term이 covariance라는 점에서, 이는 outlier를 제외한 &lt;strong&gt;robust correlation&lt;/strong&gt;으로도 활용될 수 있다.&lt;/p&gt;

&lt;p&gt;그러나 정확한 MCD 계산은 전체 n개의 데이터 중 h개의 데이터를 계속 뽑아서 계속 variance matrix를 구하고 determinant를 계산해야하기 때문에 &lt;script type=&quot;math/tex&quot;&gt;_nC_h&lt;/script&gt;번의 계산작업을 요한다. 즉 computation이 매우 버겁다. 이를 완화하고자 FAST_MCD 방법이 탄생하였다.&lt;/p&gt;

&lt;h3 id=&quot;fast-mcd&quot;&gt;Fast MCD&lt;/h3&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;_nC_h&lt;/script&gt;는 n이 커질때마다 기하급수적으로 커진다. 따라서, 굉장한 연산량을 요한다. 이를 근사하기 위한 fast MCD방법이 있는데, 다음과 같은 순서를 통해 계산된다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;n개의 data중 h개의 subset &lt;script type=&quot;math/tex&quot;&gt;H_1&lt;/script&gt;을 뽑고, 그들로 &lt;script type=&quot;math/tex&quot;&gt;\hat \mu_1, \hat \Sigma_1&lt;/script&gt;를 구한다.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;위에서 구해진 estimator를 이용해서 전체n개의 데이터에 대한 mahalanobis 거리를 계산한다, 즉&lt;/p&gt;

    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;d_1(i):=\sqrt{(x_i-\hat\mu_1)^T\hat\Sigma_1^{-1}(x_i-\hat\mu_1)}&lt;/script&gt;, for &lt;script type=&quot;math/tex&quot;&gt;i=1,..,n&lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;2번에서 구해진 거리에 따라, 거리가 가장 최소인 h개의 subset &lt;script type=&quot;math/tex&quot;&gt;H_2&lt;/script&gt;을 다시뽑고, 그들로 &lt;script type=&quot;math/tex&quot;&gt;\hat\mu_2,\hat\Sigma_2&lt;/script&gt;를 구한다. (이경우, det(&lt;script type=&quot;math/tex&quot;&gt;\hat\Sigma_1&lt;/script&gt;)&lt;script type=&quot;math/tex&quot;&gt;\ge&lt;/script&gt;det(&lt;script type=&quot;math/tex&quot;&gt;\hat\Sigma_{2}&lt;/script&gt;)이 보장된다.)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;2번3번을 반복한다. 언제까지? det(&lt;script type=&quot;math/tex&quot;&gt;\hat\Sigma_i&lt;/script&gt;)=0이되거나, det(&lt;script type=&quot;math/tex&quot;&gt;\hat\Sigma_i&lt;/script&gt;)=det(&lt;script type=&quot;math/tex&quot;&gt;\hat\Sigma_{i+1}&lt;/script&gt;) 이 될때까지!&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;이와 같은 방법은 정확한 MCD보다 빠르게 수렴하게 된다. &lt;strong&gt;그러나, global minimal point에 도달한다는 보장이 없다.&lt;/strong&gt; 고로 approximation.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;또한 initial &lt;script type=&quot;math/tex&quot;&gt;H_1&lt;/script&gt;을 뽑을때에는 h개가 아닌 p+1개를 뽑거나, 그 p+1개가 det(&lt;script type=&quot;math/tex&quot;&gt;\Sigma_1&lt;/script&gt;)=0인경우 하나씩 더 추가하며 뽑는 initialize가 더 좋다고 한다. 단순히 outlier가 덜 들어가기 때문이라고 설명해주었다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;활용법&quot;&gt;활용법&lt;/h3&gt;

&lt;p&gt;MCD로 oulier를 trim한후 regresion하는 Least Trimmed Square와(trimmed방법은 여러가지로 사용된다. trimmed mle등 무수히 많을수)  robust Covariance matrix의 eigenvector를 이용하는 ROBPCA등이 가장 대표적이다.&lt;/p&gt;

&lt;p&gt;덧. 아래는 원문을 읽어야 더 도움이 되는 부분인 이론적인 파트이다. 그러나 MCD의 distance 자체가 활용되는 경우는 많지 않기에, 참고만 해도 좋을듯하다.&lt;/p&gt;

&lt;h3 id=&quot;mcd-를-이용한-distance의-distribution&quot;&gt;MCD 를 이용한 distance의 distribution&lt;/h3&gt;

&lt;p&gt;역시나 원문 : https://core.ac.uk/download/pdf/22873068.pdf&lt;/p&gt;

&lt;p&gt;해당 논문에서는 이론적인 도출은 못함. 그러나 추론적인 도출과, 그에 대해 경험적인 진단을 해서 정당성을 획득했다. 추론의 과정을 아주 축약하자면 다음과 같다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;데이터가 정규분포를 따를때, MCD로 찾은 Sigma(&lt;script type=&quot;math/tex&quot;&gt;S^*&lt;/script&gt;)는 다음의 분포를 따른다. (&lt;script type=&quot;math/tex&quot;&gt;m&lt;/script&gt;은 unknown degress of freedom, &lt;script type=&quot;math/tex&quot;&gt;c&lt;/script&gt;는 다음을 만족시키는 adjust constant &lt;script type=&quot;math/tex&quot;&gt;E[S^*]=c\Sigma&lt;/script&gt;). 
&lt;script type=&quot;math/tex&quot;&gt;mc^{-1}S^*\sim Wishart_p(m,\Sigma)&lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;tail쪽에 있는 data들은 MCD의 estimate과 독립인듯한 형태를 띄고 있다.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;고로 tail의 데이터 &lt;script type=&quot;math/tex&quot;&gt;X_i&lt;/script&gt;는 &lt;script type=&quot;math/tex&quot;&gt;S^*&lt;/script&gt;와 독립이기에, tail의 element는 다음의 F분포로 근사할 수 있을것이다!
&lt;script type=&quot;math/tex&quot;&gt;\frac{c(m-p+1)}{pm}d^2_{s^*}(X_i,\bar X^*) \approx F_{p,m-p+1}&lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;3번을 보면 알 수 있듯이, 엄밀하게는 distance에 대한 분포라기 보단 extreme데이터에 국한된 distance의 분포이다. 또한 &lt;script type=&quot;math/tex&quot;&gt;m,c&lt;/script&gt;에 대한 추정은 &lt;script type=&quot;math/tex&quot;&gt;m,S^*&lt;/script&gt;이 multiple of Wishart의 분포를 가지고 있다는 가정하에서 다음의 추정을 할 수 있다고 한다.&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;328&quot; alt=&quot;mcd2&quot; src=&quot;https://user-images.githubusercontent.com/31824102/54182458-e95e1480-44e4-11e9-9656-fb43b8c59802.PNG&quot; /&gt;&lt;/p&gt;

</description>
        <pubDate>Mon, 11 Feb 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/02/11/Mahalanobis-and-MCD.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2019/02/11/Mahalanobis-and-MCD.html</guid>
        
        <category>Mahalanobis distance</category>
        
        <category>Minimum covariance determinant</category>
        
        <category>outlier detection</category>
        
        <category>fast MCD</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[통계기초 정리] 개인적인 통계 방법론 복습 (1. 용어와 확률분포)</title>
        <description>&lt;p&gt;기초 지식이지만 모든 고급분석의 근반이 되기에, 기초를 탄탄히 하고자 한번의 수업수강과 한번의 청강, 한번의 도강(…)까지 했다. 그치만 매번 공부하고 공부해도 까먹는 통계 기초. 늘 책찾고 헤매는 것이 힘들어서 한번에 정리해보았다.&lt;/p&gt;

&lt;h3 id=&quot;용어의-정의&quot;&gt;용어의 정의&lt;/h3&gt;

&lt;p&gt;정의란? : 토씨하나 틀리지 않고, 그대로 외우는것(구어체도 좀 있으니 유도리 있게 접근하자)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;통계적 실험(random experiment)&lt;/strong&gt; : 자료의 수집과 해석이 ‘확률’에 바탕을 두는 실험. (우리가 관찰하는 모든것은 통계적 실험이라 할 수 있다. )ex)동전던지기.H,T&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;random&lt;/strong&gt; : 딱히 정의가 내려지지 않고 사용되어 버렸다. 이는 확률이 이론이 아닌 실생활에서(정확히는 도박에서) 자연스럽게 파생되었기 때문.
    &lt;ul&gt;
      &lt;li&gt;교수님 생각의 random : 결과를 보기 전엔 그 누구도 정확하게 예측할 수 없는 것.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;표본공간(Sample Space)&lt;/strong&gt; :  통계적 실험의 ‘&lt;strong&gt;모든&lt;/strong&gt;’ ‘&lt;strong&gt;가능한&lt;/strong&gt;’ 결과들의 집합. &lt;script type=&quot;math/tex&quot;&gt;\Omega&lt;/script&gt;&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;ex) 서로다른 동전 세입을 던졌을때의 결과
        &lt;ul&gt;
          &lt;li&gt;
            &lt;script type=&quot;math/tex; mode=display&quot;&gt;\Omega=\left\{ (H,H,H), (H,H,T)..(T,T,T) \right\}&lt;/script&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;

    &lt;blockquote&gt;
      &lt;p&gt;모든 사상들(표본공간의 부분집합)의 집합을 &lt;script type=&quot;math/tex&quot;&gt;F&lt;/script&gt;로 따로 부르기도.&lt;/p&gt;

      &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;F=\left\{\left\{\emptyset\right\}..\left\{\Omega\right\}\right\}&lt;/script&gt;등도 포함하기에 Sample Space와 같은개념이 아님.&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;사상(event)&lt;/strong&gt; : ‘표본공간의 부분집합’ (우리가 흔히 생각하는 event의 의미랑 직결됨)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;확률&lt;/strong&gt; : 이 역시 명확하게 &lt;strong&gt;정의&lt;/strong&gt;내려져 있지는 않음. 다만, &lt;strong&gt;확률의 3가지 공리&lt;/strong&gt;만이 정립되있다.&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;
        &lt;p&gt;처음엔 도박에서 나옴. ‘반복시행’이 가능한 것에 대해서 그 상대비율이 어디로 수렴하는지.&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;그러나 ‘반복시행’이 가능하지 않은 경우에도 확률을 쓰기 시작함. 그로 인해 생긴 확률의 &lt;strong&gt;‘공리적 정의’&lt;/strong&gt;.  (누구나 이해할 수 있는 성질 3개를 가지고 정의를 해보자)&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;확률이란, 사상들의 집합 &lt;script type=&quot;math/tex&quot;&gt;F&lt;/script&gt;에서  실수&lt;script type=&quot;math/tex&quot;&gt;R&lt;/script&gt;로 가는, &lt;strong&gt;함수&lt;/strong&gt;인데, 다음의 3가지 성질을 만족한다.&lt;/p&gt;

        &lt;ul&gt;
          &lt;li&gt;
            &lt;ol&gt;
              &lt;li&gt;
                &lt;p&gt;$0\le P(E)\le1, \forall E$&lt;/p&gt;
              &lt;/li&gt;
              &lt;li&gt;
                &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;P(S)&lt;/script&gt;=1&lt;/p&gt;
              &lt;/li&gt;
              &lt;li&gt;
                &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;E_1,.,E_n&lt;/script&gt;이 서로 배반일때,&lt;/p&gt;

                &lt;p&gt;$P(\cup_{i=1}^nE_i)=\sum_{i=0}^nP(E_i)$&lt;/p&gt;
              &lt;/li&gt;
            &lt;/ol&gt;
          &lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;확률 변수(random variable) : 사실 ‘&lt;strong&gt;확률함수&lt;/strong&gt;‘가 의미상 더 맞는데, 잘못 정착된것.&lt;/p&gt;

    &lt;p&gt;정의역을 Sample Space에서 공역을 실수&lt;script type=&quot;math/tex&quot;&gt;R&lt;/script&gt;로 가는 ‘&lt;strong&gt;함수&lt;/strong&gt;‘이다.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;Sample space의 원소들(전체 혹은 일부)을 실수로 매핑하는 함수. ex)(H,H,H)-&amp;gt;3, (H,H,T)-&amp;gt;2 이런식으로.&lt;/p&gt;
    &lt;/blockquote&gt;

    &lt;p&gt;확률변수는 &lt;strong&gt;항상&lt;/strong&gt;, 그에 따른 &lt;strong&gt;확률분포&lt;/strong&gt;를 가지고 있다!&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;확률변수를 설명하실땐 이해를 위해서 인지 이산형을 기준으로 설명하심.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;이산형 확률 변수&lt;/strong&gt; : 확률변수긴한데, 확률변수가 취할 수 있는 값의 개수가 infinite, or countably infinite일때. 즉 취할 수 있는 값 사이에 ‘&lt;strong&gt;간격&lt;/strong&gt;‘이 존재할때! (이 경우 확률분포표로 확률변수가 취할 수 있는 가능한 값과 그에따른 확률을 나열할 수 있다.)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;연속형 확률변수&lt;/strong&gt; : 확률변수가 실수의 일부구간이나 모든 시룻에 대해 값을 취할때, 이를 연속형 확률변수라고 한다.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;결합(Joint) 확률 분포&lt;/strong&gt; : Joint, 즉 확률변수가 2개 이상. 이산형에 대해, 취할 수 있는 모든 사상과 그에 대해 취할 확률을 나열한것.즉, ‘다변량 분포’이다.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;이 결합확률 분포를 하나의 확률변수만 남기고 intergral한게 marginal distribution. 즉, ‘결합확률을 안다는 것은 marginal도 안다는것!’&lt;/p&gt;

      &lt;p&gt;ex)&lt;script type=&quot;math/tex&quot;&gt;f_{X}(x)=\sum_{\forall y}f_{X,Y}(x,y)&lt;/script&gt;. 반대의 경우 성립하지 않는다. 왜? 뒤에 나올 covariance때문에.&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;독립&lt;/strong&gt; : X,Y가 독립이다 &amp;lt; = &amp;gt; &lt;script type=&quot;math/tex&quot;&gt;f_{XY}(x,y)=f_{X}(x)f_Y(y),\forall (x,y)&lt;/script&gt;. 즉, 확률변수들의 결합확률 질량함수가 각각의 주변확률 질량함수의 곱으로 나타내질때.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;확률표본(random sample)&lt;/strong&gt; : &lt;strong&gt;iid 확률변수들의 집합&lt;/strong&gt;. 즉, 독립적이고, 동일한 분포를 이루는 확률변수 &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_n&lt;/script&gt;을 &lt;strong&gt;크기n의 ‘하나의’ 확률표본&lt;/strong&gt;이라 부른다.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;즉, 확률표본, 혹은 r.s라는 말을 쓴 순간 &lt;strong&gt;iid가 자동 내포&lt;/strong&gt; 된다는 것을 상기!&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;통계량 (a statistic)&lt;/strong&gt; : 확률표본 (&lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_n&lt;/script&gt;)의 ‘함수’. ex) &lt;script type=&quot;math/tex&quot;&gt;\bar X, Median&lt;/script&gt;&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;iid확률변수들의 함수이기에, 통계량도 자연스레 확률변수이다.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;표본분포 (sampling distribution)&lt;/strong&gt; : ‘통계량’의 확률분포.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;but 밝혀진 표본분포는 거의 없다. sample mean에 대해서만 좀 있음.&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;describing-prob-dist-func&quot;&gt;Describing prob dist func&lt;/h3&gt;

&lt;p&gt;평균, 분산, 표준편차. 간단한 부분은 지면상 생략하겠다. 기억할 만한 부분만 적음.&lt;/p&gt;

&lt;p&gt;확률분포의 특성에 대해서, 대표적으로 1차moment, 2차 moment가 있다.&lt;/p&gt;

&lt;p&gt;1차 moment=평균=&lt;script type=&quot;math/tex&quot;&gt;E(x)=\sum_{\forall x} x^1f(x)&lt;/script&gt;. 무게중심이 된다.&lt;/p&gt;

&lt;p&gt;2차 moment는 &lt;script type=&quot;math/tex&quot;&gt;E(X^2)=\sum_{\forall x} x^2f(x)&lt;/script&gt;이지만, 평균을 중심으로 한 2차 moment는 분산.&lt;/p&gt;

&lt;p&gt;즉, &lt;strong&gt;평균,분산 등은&lt;/strong&gt; 확률분포를 &lt;strong&gt;온전하게&lt;/strong&gt; 알아야 구할 수 있다.&lt;/p&gt;

&lt;p&gt;왜 표준편차를 굳이 정의하느냐? =&amp;gt; 분산이 제곱텀이기에, 원데이터와 unit(scale)을 맞춰주려고.&lt;/p&gt;

&lt;p&gt;공분산 : 결합확률분포에 대한건 특성치. &lt;strong&gt;joint pdf를 모르면 얻을 수 없다.&lt;/strong&gt;&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\because Cov(X,Y)=E[(x-\mu_x)(y-\mu_y)]=E(XY)-\mu_x\mu_y&lt;/script&gt;

&lt;p&gt;여기서 &lt;script type=&quot;math/tex&quot;&gt;E(XY)=\sum_\forall x\sum \forall yf_{XY}(xy)&lt;/script&gt;이므로 &lt;strong&gt;결합확률 분포를 알아야만&lt;/strong&gt; 구할 있는 특성치가 COV.&lt;/p&gt;

&lt;p&gt;+, Cov는 X와 Y의 &lt;strong&gt;‘선형적강도’&lt;/strong&gt;이다. 즉, 상당히 제한적인 측도.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Correlation&lt;/strong&gt; : 코스슈바르츠 부등식에 의해 -1에서 1까지로 bound되있다는걸 증명가능하다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;코시슈바르츠 부등식&lt;/strong&gt; :&lt;/p&gt;

&lt;p&gt;​	&lt;script type=&quot;math/tex&quot;&gt;[E(XY)]^2\le E(X^2)E(Y^2)&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;​	간단 proof.&lt;/p&gt;

&lt;p&gt;​		&lt;script type=&quot;math/tex&quot;&gt;E(X^2)\ge0, \forall X.&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;​		&lt;script type=&quot;math/tex&quot;&gt;\therefore E[(ax-y)^2]\ge0&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;​		&lt;script type=&quot;math/tex&quot;&gt;a^2E(x^2)-2aE(xy)+E(y^2)\ge0&lt;/script&gt;. 이걸 a에 대한 2차부등식으로 볼 수 있다. 이를 판별식으로&lt;/p&gt;

&lt;p&gt;​		&lt;script type=&quot;math/tex&quot;&gt;D=E(xy)-E(x^2)E(y^2)\le 0&lt;/script&gt;…CS부등식 증명 끝.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;여러가지-대표적-분포들&quot;&gt;여러가지 대표적 분포들&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;버놀리&lt;/strong&gt; : 결과값이 True, False의 두가지로 나뉘어질 수 있는 random variable의 분포&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;$X\sim ber(p)$&lt;/li&gt;
  &lt;li&gt;$f(x)=p^x(1-p)^{1-x},x=0,1$&lt;/li&gt;
  &lt;li&gt;$E(x)=p, Var(x)=p(1-p)$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;이항분포&lt;/strong&gt; : n개의 버놀리r.v들의 합. 총n개의 버놀리 r.v중 True가 몇개인지를 나타내는 새로운 변수 X에 대한 분포&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;$X\sim bin(n,p)$&lt;/li&gt;
  &lt;li&gt;$f(x)=_nC_xp^x(1-p)^{n-x}, x=0,1,..,n$&lt;/li&gt;
  &lt;li&gt;$E(x)=np, Var(x)=np(1-p)$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;포아송&lt;/strong&gt; : 포아송 분포는 binomial dist의 극한분포로써 처음으로 관찰되었다. 이항분포에서 n은 매우 커지고, p는 매우 작은 경우의 분포(예를들면 교통사고 처럼, 확률은 매우 낮지만 시행횟수, 즉 이동차량이 매우 많은 경우를 나타내는 분포)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;$X\sim pois(\lambda)$&lt;/li&gt;
  &lt;li&gt;$f(x)=\frac{e^{-\lambda}\lambda^x}{x!}$&lt;/li&gt;
  &lt;li&gt;$E(x)=\lambda, Var(X)=\lambda$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;카이제곱&lt;/strong&gt; : derived from &lt;script type=&quot;math/tex&quot;&gt;Z&lt;/script&gt;(표준정규분포).&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;Z\sim N(0,1)&lt;/script&gt;, then &lt;script type=&quot;math/tex&quot;&gt;Z^2\sim \chi^2(1)&lt;/script&gt;&lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;​&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Let &lt;script type=&quot;math/tex&quot;&gt;Z_1,..,Z_n&lt;/script&gt; indep.&lt;/p&gt;

    &lt;p&gt;$Z_i\sim N(0,1), \forall i$&lt;/p&gt;

    &lt;p&gt;then &lt;script type=&quot;math/tex&quot;&gt;\sum_{i=1}^nZ_i^2\sim \chi^2(n)&lt;/script&gt;.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;즉, Normal을 따르는 r.v. Z_i들의 제곱합 &lt;script type=&quot;math/tex&quot;&gt;\sum_{i=1}^nZ_i^2&lt;/script&gt; 역시 r.v.이 r.v.의 확률분포가 &lt;script type=&quot;math/tex&quot;&gt;\chi^2(n)&lt;/script&gt;라는것.&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;$E(X)=n,V(X)=2n$&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Chisq의 가법성:&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;
        &lt;p&gt;1) &lt;script type=&quot;math/tex&quot;&gt;X_1\sim\chi^2(n_1)&lt;/script&gt;&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;2) &lt;script type=&quot;math/tex&quot;&gt;X_2\sim\chi^2(n_2)&lt;/script&gt;&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;3) &lt;script type=&quot;math/tex&quot;&gt;X_1 , X_2&lt;/script&gt; are indep&lt;/p&gt;

        &lt;p&gt;=&amp;gt;&lt;script type=&quot;math/tex&quot;&gt;X_1+X_2\sim\chi^2(n_1+n_2)&lt;/script&gt;.&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ul&gt;

    &lt;blockquote&gt;
      &lt;p&gt;이 가법성은 이항분포, 포아송 분포 역시 만족한다.&lt;/p&gt;

      &lt;p&gt;또한 뒤에서 설명하지만 chisq는 gamma분포의 한 형태로 볼수도 있다.&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;t-distn(티 분포)&lt;/strong&gt; : N에서 파생되는 애들중 하나.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;def :&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;
        &lt;p&gt;$Z\sim N(0,1)$&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;$X_n\sim\chi^2(n)$&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Z,X_n&lt;/script&gt; are indep&lt;/p&gt;

        &lt;p&gt;=&amp;gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{Z}{\sqrt{X_n^2/n}}\sim t(n)&lt;/script&gt;,&lt;/p&gt;

        &lt;p&gt;즉 chisq따르는 rv를 그의 분포의 자유도로 나눠준 애가 분모에 들간다. 후에 보지만 이놈이 기막히게 들어가서 N을 따르는 샘플에서의 검정등에 t-dist로 귀결이 된다.&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;E(X)=1,V(X)=\frac{n}{n-2}\ge1&lt;/script&gt;, 분산이 큰것은 꼬리가 N보다 두꺼운것과도 상통.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;F-distn(에프 분포)&lt;/strong&gt; : chisq를 따르는 두 r.v들의 분수형태. ANOVA에 사용된다!&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;def :&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;
        &lt;p&gt;$X\sim\chi^2(n)$&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;$Y\sim\chi^2(m)$&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;X,Y​&lt;/script&gt; are indep. (즉 n개의 지들끼리 indep한 &lt;script type=&quot;math/tex&quot;&gt;Z_i​&lt;/script&gt;와, m개의 지들끼리indep한 &lt;script type=&quot;math/tex&quot;&gt;Z_j​&lt;/script&gt;가, n과 m 서로서로의 &lt;script type=&quot;math/tex&quot;&gt;Z_i,Z_j​&lt;/script&gt;와도 indep함.)&lt;/p&gt;

        &lt;p&gt;=&amp;gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{X/n}{Y/m}\sim F(n,m)&lt;/script&gt;&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;if &lt;script type=&quot;math/tex&quot;&gt;X\sim t(n)&lt;/script&gt;, then &lt;script type=&quot;math/tex&quot;&gt;X^2\sim F(1,n)&lt;/script&gt;, 왜냐면 분자에 Z가 있으니까, (Z랑 분모의 rv랑도 by def로 indep니까)&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;지수분포(exponential distn)&lt;/strong&gt; : 생존분석의 대표적이고 기본적인 분포로, 무기억성과 failure rate가 constant라는 특성이 있다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;$X\sim exp(\lambda)$&lt;/li&gt;
  &lt;li&gt;$f(x)=\lambda e^{-\lambda x}$&lt;/li&gt;
  &lt;li&gt;$E(x)=\frac{1}{\lambda}, Var(x)=\frac{1}{\lambda^2}$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;감마분포&lt;/strong&gt; : non_negative r.v를 모델링할때 쓰이는 분포로, 다양한 형태를 취할 수 있다. 또, expo distn과 chisq distn을 포함하는 포괄적 분포이다&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;$X\sim gamma(\alpha,\beta)$&lt;/li&gt;
  &lt;li&gt;$f(x)=\frac{\beta^\alpha}{\Gamma(\alpha)}x^{\alpha-1}e^{-\beta x}$&lt;/li&gt;
  &lt;li&gt;$E(x)=\frac{\alpha}{\beta},Var(x)=\frac{\alpha}{\beta^2}$&lt;/li&gt;
  &lt;li&gt;$exp(\lambda)\equiv gamma(1,\frac{1}{\lambda})$&lt;/li&gt;
  &lt;li&gt;$\chi^2(p)\equiv gamma(\frac{p}{2},\frac{1}{2})$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;베타분포&lt;/strong&gt; : x가 존재가능한 공간이 [0,1]일때 자주 사용되는 분포로, 역시 다양한 형태를 취할 수 있다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;$X\sim beta(\alpha,\beta)$&lt;/li&gt;
  &lt;li&gt;$f(x)=\frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}x^{\alpha-1}(1-x)^{\beta-1}$&lt;/li&gt;
  &lt;li&gt;$E(x)=\frac{\alpha}{\alpha+\beta},Var(x)=\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;음이항분포(negative binomial distn)&lt;/strong&gt; : 버놀리r.v와 관련된 또다른 분포. 성공확률 p 의 사건에서 r번의 성공을 하기 위해 필요한 시도횟수x에 대한 분포이다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;$X\sim neg_bin(r,p)$&lt;/li&gt;
  &lt;li&gt;$f(x)=\begin{pmatrix}  x+r-1 \ r-1  \end{pmatrix}(1-p)^xp^r,x=0,1,2..$&lt;/li&gt;
  &lt;li&gt;$E(x)=\frac{r(1-p)}{p}, Var(x)=\frac{r(1-p)}{p^2}$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;덧. 같은 분포이더라도 &lt;script type=&quot;math/tex&quot;&gt;\beta&lt;/script&gt;를 &lt;script type=&quot;math/tex&quot;&gt;1/\beta&lt;/script&gt;로 설정한다던지로 인해 형태가 약간 달라질 수 있다. 이런 파라미터의 사용에 대해서 통일이 되어있지 않다.&lt;/p&gt;

&lt;p&gt;막간상식 : 왜 자연현상의 많은 것이 N비슷?(ex키)&lt;/p&gt;

&lt;p&gt;=&amp;gt;지금의 자연현상에 영향을 준 요인들은 오래전부터의 유전적 요인들의 가중평균.(ex 증조부의 키,할부지의 키,..) n은 거의 inf에 가까움. 이는 확장된 CLT에 의해 N에 근사하게 됨.&lt;/p&gt;

&lt;hr /&gt;

&lt;h3 id=&quot;fundamental-theorem-of-normal-distn&quot;&gt;Fundamental theorem of Normal distn&lt;/h3&gt;

&lt;p&gt;Let &lt;script type=&quot;math/tex&quot;&gt;X_i\sim N(\mu,\sigma^2), \forall i&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;X_i&lt;/script&gt;’s are indep, 즉, iid X들이 다 N을 따를때, 다음의 &lt;strong&gt;3가지 성질을&lt;/strong&gt; 만족.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;$\bar X\sim N(\mu,\frac{\sigma^2}{n})$&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{(n-1)S^2}{\sigma^2}\sim\chi^2(n-1)&lt;/script&gt;, 이는 &lt;script type=&quot;math/tex&quot;&gt;\frac{\sum(x_i-\bar x)}{\sigma^2}\sim\chi^2(n-1)&lt;/script&gt;와 같은말.&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;proof는 공책에. 증명에 아래의 3번 가정도 필요함&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;S^2, \bar X&lt;/script&gt; are indep.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;여기에서 variance를 sample variance로 대체한 t-dist가 도출됨
&lt;script type=&quot;math/tex&quot;&gt;\frac{\bar X-\mu}{S/\sqrt{n}}\sim t(n-1)&lt;/script&gt;
&lt;script type=&quot;math/tex&quot;&gt;\because T=\frac{Z}{\sqrt{Y/df}}&lt;/script&gt;,&lt;/p&gt;

&lt;p&gt;here &lt;script type=&quot;math/tex&quot;&gt;Z=\frac{\bar X-\mu}{\sigma/\sqrt{n}}\sim N(0,1)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;Y=\frac{(n-1)S^2}{\sigma^2}\sim \chi^2(n-1)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;Z,Y&lt;/script&gt; are indep.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;2번 공식에 대한 proof. (수통에서 가져옴 66p)&lt;/p&gt;

  &lt;p&gt;&lt;img width=&quot;472&quot; alt=&quot;funda_thm_proof&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60090557-b848dd80-977d-11e9-9b73-ab0e1caf30be.PNG&quot; /&gt;&lt;/p&gt;

  &lt;p&gt;N을 따르는 n개의 iid data를 cov=0인 multivariate Normal로 봐서, &lt;script type=&quot;math/tex&quot;&gt;\bar X&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;S^2&lt;/script&gt;의 구성원간에 cov가 0임을 밝혔다.&lt;/p&gt;
&lt;/blockquote&gt;
</description>
        <pubDate>Tue, 15 Jan 2019 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%ED%86%B5%EA%B3%84%EA%B8%B0%EC%B4%88/2019/01/15/%EA%B0%9C%EC%9D%B8%EC%A0%81%EC%9D%B8-%ED%86%B5%EA%B3%84-%EB%B0%A9%EB%B2%95%EB%A1%A0-%EB%B3%B5%EC%8A%B5-(1.-%EC%9A%A9%EC%96%B4%EC%99%80-%ED%99%95%EB%A5%A0%EB%B6%84%ED%8F%AC).html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%ED%86%B5%EA%B3%84%EA%B8%B0%EC%B4%88/2019/01/15/%EA%B0%9C%EC%9D%B8%EC%A0%81%EC%9D%B8-%ED%86%B5%EA%B3%84-%EB%B0%A9%EB%B2%95%EB%A1%A0-%EB%B3%B5%EC%8A%B5-(1.-%EC%9A%A9%EC%96%B4%EC%99%80-%ED%99%95%EB%A5%A0%EB%B6%84%ED%8F%AC).html</guid>
        
        <category>basic statistics</category>
        
        <category>statistical distribution</category>
        
        <category>random variable</category>
        
        <category>sample space</category>
        
        
        <category>통계기초</category>
        
      </item>
    
      <item>
        <title>[cheat sheet] SQL cheating sheet</title>
        <description>
&lt;h3 id=&quot;시작하기-앞서&quot;&gt;시작하기 앞서&lt;/h3&gt;

&lt;p&gt;PostgreSQL을 가지고 배우지만, 여기서 배우는 모든 sql구문은 any major type of SQL Dababase(MySQL, Orcale등)에 모두 적용가능한 구문이다.&lt;/p&gt;

&lt;p&gt;대소문자에 insensitive. 상관없지만, SQL keyword는 대문자로 쓰는게 관습.&lt;/p&gt;

&lt;h4 id=&quot;select&quot;&gt;Select&lt;/h4&gt;

&lt;p&gt;SELECT column1,column2,.., FROM table_name; (콤마로 여러개를 부른다. ‘;’가 나와야 문장이 끝난것으로 인식한다)&lt;/p&gt;

&lt;p&gt;실무에선 SELECT *****를 쓸일은 거의 없음. 넘 큰데이터에 모든 정보를 다부르는거니까 속도가 무지 느려질것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT first_name,last_name FROM actor;&lt;/p&gt;

  &lt;p&gt;SELECT * FROM actor;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;select-distinct&quot;&gt;Select distinct&lt;/h4&gt;

&lt;p&gt;SELECT DISTINCT column1,column2,.., FROM table_name;&lt;/p&gt;

&lt;p&gt;중복값 없애고 부르기&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT DISTINCT release_year from film;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;select-where&quot;&gt;Select where&lt;/h4&gt;

&lt;p&gt;특정 조건을 만족하는 데이터만을 부름&lt;/p&gt;

&lt;p&gt;SELECT column1,column2,.., FROM table_name WHERE conditions;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT e_mail From customer where first_name=’Jared’ AND last_name = ‘Rice’;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;count&quot;&gt;Count&lt;/h4&gt;

&lt;p&gt;SELECT  COUNT(columns) FROM table; (count는 null값은 세지 않는다)&lt;/p&gt;

&lt;p&gt;SELECT  COUNT(DISTINCT columns) FROM table; (이렇게 distinct의 갯수세기.)&lt;/p&gt;

&lt;h4 id=&quot;limit&quot;&gt;Limit&lt;/h4&gt;

&lt;p&gt;몇줄보내줄지 정하는거.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT * FROM customer LIMIT 5;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;order-by&quot;&gt;Order By&lt;/h4&gt;

&lt;p&gt;SELECT column1, column2 FROM table_name ORDER BY column1 ASC&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT first_name, last_name from customer ORDER BY first_name ASC, last_name DESC; (first_name으로 오름차순sorting하고, first_name이 겹치는 사람들에 대해선 last_name으로 내림차순sorting한번 더하기)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;between-in-like-where안에-쓰이는애들&quot;&gt;Between, In, Like (Where안에 쓰이는애들)&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Between&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;‘value &lt;script type=&quot;math/tex&quot;&gt;\ge&lt;/script&gt; low and value &lt;script type=&quot;math/tex&quot;&gt;\le&lt;/script&gt; high’==’value BETWEEN low and high’&lt;/p&gt;

&lt;p&gt;단순히 조건문을 더 fancy하게 만들어줌. (NOT BETWEEN도 가능)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT * FROM payment WHERE  amount NOT BETWEEN 8 AND 9 ; (8~9가 아닌 모든애들)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;IN&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;value IN (value1,value2).&lt;/p&gt;

&lt;p&gt;value IN (SELECT value FROM table_name). (즉, IN의 평가대상이될 괄호 안에는 subquery가 들어갈수도 있다.) between과 마찬가지로, NOT IN도 가능&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT customer_id,return_date FROM rental WHERE customer_id IN (10,100);&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;LIKE&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT first_name, last_name FROM customer WHERE first_name LIKE ‘Jen%’; (Jen으로 시작하는 패턴과 맞는애들을 반환해라.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;패턴매칭에 대해선 뒤에서 더 자세히.&lt;/p&gt;

&lt;p&gt;% : 암거나 관계없이 &lt;strong&gt;무수히&lt;/strong&gt; 받을 수잇음&lt;/p&gt;

&lt;p&gt;_ : 암거나 관계없이 ‘&lt;strong&gt;하나&lt;/strong&gt;’ 받을 수 있음&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT first_name, last_name FROM customer WHERE first_name LIKE ‘_her%’; (Cheryl, Theresa,..)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;aggregate-function&quot;&gt;Aggregate Function&lt;/h3&gt;

&lt;p&gt;사실 count도 이 중 하다. 여러row들을 signale value로 합쳐주는 애들.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MIN&lt;/strong&gt; : SELECT MIN(amount) FROM payment;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MAX&lt;/strong&gt; : SELECT MAX(amount) FROM payment;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AVG&lt;/strong&gt; : SELECT ROUND(AVG(amount),3) FROM payment; (ROUND는 3자리까지 허용하는 우리가 아는 그 함수.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SUM&lt;/strong&gt; : SELECT SUM(amount) FROM payment;&lt;/p&gt;

&lt;h4 id=&quot;group-by-중요&quot;&gt;GROUP BY (중요!)&lt;/h4&gt;

&lt;p&gt;SELECT colum1, aggregate_func(column2) FROM table_name GROUP BY column1; (GROUP BY로 묶이는 대상의 컬럼은, select에서 불러준다. 안해도되는 sql도 있지만 안정성을 위해.)&lt;/p&gt;

&lt;p&gt;group을 묶어서 각 group마다 aggregate func를 취하는 형태로 많이 쓰인다. 물론 aggregate func없이도 사용가능 (판다스의 groupby상기)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT customer_id, SUM(amount), COUNT(amount) FROM payment GROUP BY customer_id;&lt;/p&gt;

  &lt;p&gt;SELECT rating, COUNT(rating) FROM film GROUP BY rating; (각 rating의 count를 하기 위해선 이렇게. 각 count가 어느 rating의 count인지를 알려주기 위해 rating도 select한다.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;having&quot;&gt;Having&lt;/h4&gt;

&lt;p&gt;주로 group by와 함께 조건을 추가하기 위해 쓰임. (group by의 결과물 전용where같은 느낌)&lt;/p&gt;

&lt;p&gt;SELECT column1,agg_func(column2) FROM table_name GROUP BY column1 HAVING condition&lt;/p&gt;

&lt;p&gt;where은 groupby전에, having은 groupby한 대상에 대해 쓰이기에, &lt;strong&gt;select, from, where, groupby, having&lt;/strong&gt;순으로 쓰인다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT custormer_id, SUM(amount) FROM payment GROUP BY customer_id HAVING SUM(amount) &amp;gt; 200;&lt;/p&gt;

  &lt;p&gt;(groupby에만 쓰일수 있는 sum이 having에 들간것 주의. 저런 condi를 만족하는 group만 반환해달라.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;as&quot;&gt;As&lt;/h4&gt;

&lt;p&gt;그냥 별명짓기&lt;/p&gt;

&lt;p&gt;SELECT customer_id, SUM(amount) AS my_name1, AVG(amount) AS my_name2 FROM payment GROUP BY customer_id;&lt;/p&gt;

&lt;p&gt;SELECT cus.customer_id, first_name, payment_id FROM customer as cus INNER JOIN payment as ppay ON ppay.customer_id=cus.customer_id;&lt;/p&gt;

&lt;p&gt;이렇게 테이블에도 별명 지어줄수도&lt;/p&gt;

&lt;h3 id=&quot;join&quot;&gt;JOIN&lt;/h3&gt;

&lt;p&gt;다수의 테이블을 합칠때. (주로 테이블A의 primary key를 테이블B의 외래키와 비교해서 합치는 경우이다.)&lt;/p&gt;

&lt;h4 id=&quot;inner-join&quot;&gt;Inner Join&lt;/h4&gt;

&lt;p&gt;교집합의 데이터 반환.&lt;/p&gt;

&lt;p&gt;SELECT A.prim_key, A.col11 B.forin_key, B.col21 FROM A INNER JOIN B ON A.prim_key = B.forein_key; (사실 select에서 ‘A.’ 과 같은 테이블 명시는 col이 겹칠때만 해도됨. 즉 col11이 A에만 있음 A.col11대신 col11로 해도된다.)&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;207&quot; alt=&quot;inner_join&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60664516-220f6880-9e9d-11e9-865f-ed228363c3b1.PNG&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT customer.customer_id, first_name, payment_id FROM customer 
INNER JOIN payment ON payment.customer_id=customer.customer_id;&lt;/p&gt;

  &lt;p&gt;(여기서 payment_id는 payment table에만 있었다.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;full-outer-join&quot;&gt;full outer join&lt;/h4&gt;

&lt;p&gt;전체 집합. 이럼 당근 A에는 있었지만 B에는 없던 데이터가 있을것. 그건 그냥 ‘null’로 셀이 채워져서 반환된다&lt;/p&gt;

&lt;p&gt;SELECT * FROM tableA FULL OUTER JOIN tableB ON tableA.name=tabelB.name;&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;191&quot; alt=&quot;full_outer_join&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60664514-2176d200-9e9d-11e9-8b17-91e1bd5f4990.PNG&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;left-outer-join-right-outer도-마찬가지&quot;&gt;Left outer join (right outer도 마찬가지)&lt;/h4&gt;

&lt;p&gt;From의 대상이 left임. left에 있는 애들 중심으로 데려오기.&lt;/p&gt;

&lt;p&gt;SELECT * FROM tableA LEFT OUTER JOIN tableB ON tableA.name=tabelB.name; (LEFT JOIN만써줘도 된다.)&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;207&quot; alt=&quot;left_outer_join&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60664517-220f6880-9e9d-11e9-9269-25be8b0f86e9.PNG&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;덧-left-outer-join-with-where-left에만-있는애들-고르기&quot;&gt;덧. Left outer join with WHERE (left에만 있는애들 고르기)&lt;/h4&gt;

&lt;p&gt;SELECT * FROM tableA LEFT OUTER JOIN tableB ON tableA.name=tabelB.name WHERE tableB.name IS null; (A에만 있는 애들은 B에서 null로 나올것이기에, 이렇게 where로 pure A를 구할 수 있다.)&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;206&quot; alt=&quot;left_outer_join_where&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60664513-2176d200-9e9d-11e9-9053-6cdd8b8b890f.PNG&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;덧2-full-outer-join-with-where&quot;&gt;덧2. full outer join with WHERE&lt;/h4&gt;

&lt;p&gt;SELECT * FROM tableA FULL OUTER JOIN tableB ON tableA.name=tabelB.name WHERE tableA.name IS null OR tableB.name IS null;&lt;/p&gt;

&lt;p&gt;&lt;img width=&quot;201&quot; alt=&quot;full_outer_join_where&quot; src=&quot;https://user-images.githubusercontent.com/31824102/60664515-2176d200-9e9d-11e9-88f9-6b7e3e733a15.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/&quot;&gt;join정리한 사이트&lt;/a&gt;&lt;/p&gt;

&lt;h4 id=&quot;union&quot;&gt;Union&lt;/h4&gt;

&lt;p&gt;key그런거 상관없이, 그냥 같은크기면 concat해주는 애.(duplicate면 하나의 row로 합침.)&lt;/p&gt;

&lt;p&gt;SELECT col1,col2 FROM tbl_name1 &lt;strong&gt;UNION&lt;/strong&gt; SELECT col1,col2 FROM tbl_name2;&lt;/p&gt;

&lt;p&gt;(합치는 두개가 같은 수의column이어야. col1끼리, col2끼리 데이터타입이 같아야.)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT * FROM customer_list1 UNION SELECT * FROM customer_list2;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;advanced-sql-commands&quot;&gt;Advanced SQL Commands&lt;/h2&gt;

&lt;h4 id=&quot;timestamp&quot;&gt;Timestamp&lt;/h4&gt;

&lt;p&gt;시간(혹은 달력)의 의미를 보존한 timestamp object를 다루는법.&lt;/p&gt;

&lt;p&gt;이부분은 Mysql등에서 조금씩 다를 수 있다. 쓰기전 document를 봐라. (ex. ‘mysql datetime’)&lt;/p&gt;

&lt;p&gt;date ‘2001-09-28’ + integer ‘7’같은 timestamp용 operator나 age(timestamp_obj) 같이 timestamp용 function을 쓸 수 있다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;SELECT SUM(amount), extract(month from payment_date) AS mmonth FROM payment GROUP BY mmonth; (datetime obj에서 ‘달’만 떼와서 활용한 extract예시)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;mathmatical-function&quot;&gt;Mathmatical function&lt;/h4&gt;

&lt;p&gt;모든 func는 ‘postgresql math’등 검색. 우리가 흔히 아는 math func임&lt;/p&gt;

&lt;h4 id=&quot;string-function-and-operators&quot;&gt;String function and operators&lt;/h4&gt;

&lt;p&gt;역시나 ‘postgresql string function’검색.&lt;/p&gt;

&lt;p&gt;SELECT first_name || || last_name AS full_name FROM customer; (이름과 성을 concat.)&lt;/p&gt;

&lt;p&gt;SELECT lower(first_name) FROM customer;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;지원하지 않는 더 복잡한 형태는 정규표현식(regular expression)을 찾아봐라.&lt;/strong&gt;&lt;/p&gt;

&lt;h4 id=&quot;subquery&quot;&gt;Subquery&lt;/h4&gt;

&lt;p&gt;쿼리안에 들어가있는 쿼리. 괄호()로 감싸져표현됨.&lt;/p&gt;

&lt;p&gt;간단하게 말하면 select를 두번 쓸 수 있게해줌. 즉 훨씬더 간결하고 유연한쿼리작성 가능.&lt;/p&gt;

&lt;p&gt;SELECT film_id, rental_rate FROM film WHERE rental_rate &amp;gt; &lt;strong&gt;( SELECT AVG(rental_rate) from film)&lt;/strong&gt;;&lt;/p&gt;

&lt;p&gt;SELECT film_id FROM film 
WHERE film_id IN (SELECT…); (subquery로 list를 만든경우)&lt;/p&gt;

&lt;h4 id=&quot;self-join&quot;&gt;Self Join&lt;/h4&gt;

&lt;p&gt;같은 테이블내의 데이터(row)를 합치고 싶은 경우 self join을 함. 이 경우 left와 right를 구분하기 위해 AS 를 써서 alias를 붙임. (sql면접에서 많이 나온다고 한다.)&lt;/p&gt;

&lt;p&gt;SELECT a.first_name,a.last_name,b.first_name,b.last_name 
FROM customer as a, customer as b
WHERE a.first_name = b.last_name;&lt;/p&gt;

&lt;p&gt;본인과 합치는것이기에, 실제 JOIN구문을 안쓰고 할수도 있다.&lt;/p&gt;

&lt;p&gt;이렇게 JOIN을 쓰는 구문도 있다(같은 결과다).&lt;/p&gt;

&lt;p&gt;SELECT a.first_name,a.last_name,b.first_name,b.last_name 
FROM customer as a JOIN customer as b
ON a.first_name = b.last_name;&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;참고한 자료&lt;/p&gt;

&lt;p&gt;시각화로 join 잘 설명한 사이트 : https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/&lt;/p&gt;
</description>
        <pubDate>Sat, 01 Sep 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EC%BD%94%EB%94%A9cheat%20sheet/2018/09/01/SQL-cheating-sheet.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EC%BD%94%EB%94%A9cheat%20sheet/2018/09/01/SQL-cheating-sheet.html</guid>
        
        <category>SQL</category>
        
        <category>cheating sheet</category>
        
        
        <category>코딩cheat sheet</category>
        
      </item>
    
      <item>
        <title>[DS from Scratch] Logistic regression 이해, 구현하기(with Python)</title>
        <description>
&lt;blockquote&gt;
  &lt;p&gt;(가독성과 재생산성을 모두 살리기 위해 맨 아래부분에 직접사용한 함수들을 모아놓았습니다. 코드를 실행하려면 맨아래 cell의 함수를 먼저 실행하고 위에서 부터 순서대로 실행하면 됩니다.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;원래 multiple regression을 다루면서 ridge등을 구현할 예정이었으나 이번 공모전이 classification문제라서, 진도를 유동적으로 바꿨습니다.&lt;/p&gt;

&lt;p&gt;총 200명의 data가 있고, 각 직장 경력, 연봉을 통해서 해당 사람이 premium계정을 구입했는지를 classificatino하는 문제가 있다고 해보자.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;48000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;48000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;63000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;76000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;69000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;76000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;88000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;83000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;83000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;43000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;79000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;76000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;92000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;75000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;69000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;56000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;67000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;74000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;63000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;82000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;58000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;90000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;57000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;102000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;54000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;65000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;82000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;107000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;46000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;48000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;84000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;45000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;30000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;89000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;48000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;76000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;77000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;56000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;48000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;56000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;44000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;78000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;63000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;79000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;56000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;52000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;56000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;51000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;71000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;65000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;33000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;62000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;71000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;61000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;75000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;81000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;62000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;88000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;44000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;55000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;41000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;66000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;78000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;102000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;48000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;66000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;56000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;69000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;77000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;86000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;68000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;75000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;49000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;98000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;85000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;88000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;46000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;37000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;86000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;57000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;85000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;69000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;63000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;48000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;72000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;45000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;95000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;95000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;65000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;80000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;91000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;68000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;58000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;74000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;76000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;49000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;81000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;62000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;94000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;63000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;69000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;77000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;86000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;94000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;72000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;53000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;97000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;65000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;71000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;66000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;91000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;84000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;55000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;62000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;79000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;57000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;47000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;62000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;79000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;58000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;80000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;61000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;62000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;85000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;51000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;58000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;43000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;54000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;74000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;55000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;41000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;73000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;66000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;81000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;69000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;72000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;58000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;49000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;78000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;56000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;36000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;90000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;59000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;95000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;72000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;63000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;61000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;74000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;66000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;59000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;61000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;56000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;76000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;78000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;59000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;74000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;54000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;52000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;69000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;76000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;63000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;51000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;78000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;54000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;59000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;52000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;87000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;73000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;98000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;84000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;6.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;73000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;72000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;69000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;79000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#years of experience at work, salary, whether use premium account
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;48000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#데이터 예시. 0.7년 근무에 연봉 48000, premium=True
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;우선, 데이터를 처리할 수 있도록 x,y형태로 나눠준다. 그리고 학습을 빠르게 할 수 있도록 normalize도 해준다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# each element is [1, experience, salary], note '1' is for intercept term
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# each element is paid_account
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rescaled_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rescale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# 평균 0, 분산1로 만들어주기
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;X_mean&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;repeat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_std&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;repeat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_std&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isnan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;isnan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#numpy사용해서 scaling한것과 값같다.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;첫번째 시도로 0과1의 클래스를 나타내는 categorical 변수에 단순히 multiple regression을 이용하여 적합해보자. 이런 경우에도, &lt;strong&gt;값은 나온다&lt;/strong&gt;(이런 잘못된 사용을 지양하기 위해 모델에 대한 이해가 있어야 한다)&lt;/p&gt;

&lt;p&gt;다음은 적합된 값들과 실제 값들을 plot으로 그린것이다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;sklearn.linear_model&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LinearRegression&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#지난번에 구현한 GD로 적합할수도 잇으나 logistic에 집중하기 위해 생략하고 sklearn import.
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;try&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;del&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linear_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#just for sure
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;except&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;pass&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;linear_reg&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LinearRegression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_hat&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linear_reg&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'y_hat'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'y(true_value)'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'o'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44199229-0d19d180-a133-11e8-994b-739ca0a59cd2.png&quot; alt=&quot;output_7_0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;값을 보면 다음과 같은 특징이 있다.
당근, 0과 1의 값만으로 나오지 않고, &lt;strong&gt;-0.5~1.50&lt;/strong&gt;정도의 continuous 한 값으로 나왓다. 우리가 원하는 0과 1로 구분하는 task와 거리가 있음을 알 수 있다.&lt;/p&gt;

&lt;p&gt;그렇다면, linear regression이 class가 1인 애들은 1에 가까운 값을 내도록 적합하려 했을것이기에,
continuous한 값을 각각 ‘1에 가까울 확률’이라고 보려고 한다.
그러나 이경우에도 0보다 작은 값들, 1보다 큰값들도 잇어 바로 확률로 해석하기가 힘들다.&lt;/p&gt;

&lt;p&gt;굳이 1.5의 값을 유지하며 linear regression을 고수하려고 해보자.(이경우 error를 0.5로 설정할것이다.) 그럼 다음과 같은 가정의 위반을 직면하게 된다.&lt;/p&gt;

&lt;p&gt;우선, X~Y가 선형이 될 수 없다. (Y는 [0,1]의 값을 가져야 하기에, boundary가 있다.) (&lt;strong&gt;선형성 가정 위반.&lt;/strong&gt;)&lt;/p&gt;

&lt;p&gt;두번째로, 각각의 값들에 대해 [0,1]의 boundary를 맞춰주기 위해 x가 커지거나 작아지거나 할경우 error term도 그만큼 커져야 함을 의미하게 되는데, 이는 error가 x의 수준에 의존하지 않고 언제나 iid라는 linear regression의 가정을 위반하게 된다. 구체적으로는 분산도 달라지고(&lt;strong&gt;등분산 가정 위반&lt;/strong&gt;), &lt;strong&gt;평균&lt;/strong&gt;도 달라지게 된다(&lt;strong&gt;mean0가정 위반&lt;/strong&gt;)&lt;/p&gt;

&lt;p&gt;또한, Y변수가 0,1과 같은 discrete한 값들이기에, Y와 적합값Y_hat의 차인 error역시 normal분포를 띈다고 가정하기 힘들다(&lt;strong&gt;오차의 정규가정 위반&lt;/strong&gt;)&lt;/p&gt;

&lt;p&gt;무엇보다, 이중 가장 중요한것은 mean0위반이다. 위의 regression을 고수한다면 큰 x값에 대해 error도 mean0가 아니고, 결국 우리의 추정이 &lt;strong&gt;biased된 값&lt;/strong&gt;이라는 결론을 내게 된다.(i.e. $E(y.hat)\neq Y$)&lt;/p&gt;

&lt;p&gt;좀더 이해를 수우러하게 하기 위해 단변수에 대해 적합을 해서 그래프로 확인해보자. 다음은 premium~salary의 관계를 보기 위해 산점도를 그려본 것이다. (왠지 모르게 이 예제 데이터에서는 salary가 적은 사람들일 수록 premium이다)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[:,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'o'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'salary'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'whether premium'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44199230-0d19d180-a133-11e8-9556-0bca187471b2.png&quot; alt=&quot;output_10_0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이에 대해 linear regression을 적합하여, 0과 1을 예측한다고 해보자. 적합된 회귀선을 함께 그림으로 그려보면, 다음과 같다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;try&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;del&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linear_reg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;except&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;pass&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;linear_reg&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LinearRegression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[:,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;coeff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linear_reg&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coef_&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;intercept&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linear_reg&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;intercept_&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[:,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'o'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2e4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;12e4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2e4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;12e4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coeff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;intercept&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'salary'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'whether premium'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44199231-0d19d180-a133-11e8-8d2d-5f53bed1cfda.png&quot; alt=&quot;output_11_0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그림으로 보면 알 수 있듯이, salary가 큰사람일 수록 y_hat값은 무한정 음수로 떨어질 것이고, (error=y-y_hat이므로) error는 0(또는 간혹1)을 유지하기 위해 positive 쪽으로 무한정 커지게 될것이다. 즉, 등분산가정이 깨질뿐더러 mean0가정이 깨지고, error의 mean0가정이 깨진다는 것은 E(y_hat)=y가 될 수 없다는 것이므로 우리 모델이 bias되어있다는 것!&lt;/p&gt;

&lt;h1 id=&quot;then-how&quot;&gt;then, how?&lt;/h1&gt;

&lt;p&gt;앞서 말했듯이, linear regression이 class가 1인 애들은 1에 가까운 값을 내도록 적합하려 했을것이기에,
continuous한 값을 각각 ‘1에 가까울 확률’이라고 보려고 하는 것은 합리적이다. 그러나 [-inf,inf]가 나올 수 있는 이 적합값y_hat을 &lt;strong&gt;어떻게 [0,1]이라는 probabilty의 틀&lt;/strong&gt;에 넣어 해석할 수 있을지에 대한 문제로 귀결된다.&lt;/p&gt;

&lt;p&gt;이를 boundary problem이라고 한다. 로지스틱 회귀에서는 이 문제를, 결과값에 특정한 함수를 씌워서 해결한다&lt;/p&gt;

&lt;h1 id=&quot;logistic-function&quot;&gt;Logistic function&lt;/h1&gt;

&lt;p&gt;로지스틱 회귀에서는 이 문제를, 결과값에 특정한 함수 로지스틱을 씌워서 해결한다.&lt;/p&gt;

&lt;p&gt;로지스틱 함수는 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;f(x)=\frac{1}{1+e^{-x}}&lt;/script&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;try&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;except&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;OverflowError&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-9&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#원래 try구문만으로 완벽한 식이지만, x에 지나치게 큰수가 들어갈 경우 error가 나서 except구문을 만들어줬다
#뒤에서 gd할때 step size를 이상한거로(e.g. 100) 막 넣어서 계산하면 e^5000이런게 나와버려서 계산을 못한다
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;함수에 대한 설명을 하기 전에 우선 그림으로 직관적으로 봐보자. [-10,10]이었던 X값들이 logistic함수이라는 특정한를 씌우니 [0,1]로 수렴하는 것을 볼 수 있다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#plt.ylim(-10,10)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axhline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'y'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axvline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;color&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'y'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44199234-0db26800-a133-11e8-840a-43f265ac0b92.png&quot; alt=&quot;output_17_0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44199235-0e4afe80-a133-11e8-95c8-58787cbfbc9a.png&quot; alt=&quot;output_17_0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;x가 커질수록, $e^{-x}$는 0에 가까워져서 $\frac{1}{1+e^{-x}}$는 1에 가까워지고,&lt;/p&gt;

&lt;p&gt;x가 작아질수록, $e^{-x}$는 inf에 가까워져서 $\frac{1}{1+e^{-x}}$는 0에 가까워지며,&lt;/p&gt;

&lt;p&gt;x가 0일때 $e^{-x}$는 (모든 수가 그러하듯이) 1이므로 $\frac{1}{1+e^{-x}}=1/2$가 된다&lt;/p&gt;

&lt;p&gt;이렇게 logistic function을 결과값에 씌워 [0,1]의 값을 갖게 하여, 해당 데이터가 이러한 feature들을 갖고 있을때 y=True가 나올 &lt;strong&gt;conditional probability&lt;/strong&gt;로 표현할 수 있도록 한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;참고로 logistic function은 딥러닝의 non-linear function에서 sigmoid함수라고도 불린다. 엄밀히 말하지면 sigmoid function은 S자 모양의 모든 함수를 지칭하는 것이고, 로지스틱은 그중 한가지 예시일 뿐이다 &lt;a href=&quot;https://en.wikipedia.org/wiki/Sigmoid_function&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;또하나의 참고로 sigmoid func의 미분은 다음과 같게 된다(back prop에 사용된다)&lt;/p&gt;

  &lt;p&gt;$f(x)=\frac{1}{1+e^{-x}}=\frac{1}{g(x)}$, where $g(x)=1+e^{-x}$&lt;/p&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;f'(x)=\frac{d}{dx}({\frac{1}{g(x)}})=\frac{d}{dx}(g(x)^{-1})=-1*g(x)^{-2}*g'(x)=-\frac{g'(x)}{g(x)^{2}}&lt;/script&gt;

  &lt;p&gt;$g’(x)=\frac{d}{dx}(1+e^{-x})=-1*e^{-x}$근데 이는 다시 g(x)의 형태로 (굳이)나타낼 수 있다. (그럼 최종 결과가 f(x)의 형태로 나와서 합성함수 계산에서 편하게 표현할수 있다)&lt;/p&gt;

  &lt;p&gt;$-1*e^{-x}=-e^{-x}=1-(1+e^{-x})=1-g(x), $&lt;/p&gt;

  &lt;p&gt;$\therefore g’(x)=1-g(x)$&lt;/p&gt;

  &lt;p&gt;$\therefore f’(x)=-\frac{1-g(x)}{g(x)^2}=\frac{\frac{-1}{g(x)}+1}{g(x)}=\frac{1}{g(x)}*(1-\frac{1}{g(x)})$&lt;/p&gt;

  &lt;p&gt;$\therefore f’(x)=f(x)*(1-f(x))$&lt;/p&gt;

  &lt;p&gt;이를 코드로 표현해서 도함수 역시 정의해놓는다&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;logistic_prime&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;우리가 하는것은 앞에 나왔던 regression의 값을 0,1으로 만들어줘서 확률로써 해석하는 것이다.
수식으로 표현하면 다음과 같다&lt;/p&gt;

&lt;p&gt;$y_i=f(\boldsymbol X_i \beta)+\epsilon_i$, 여기서 f는 로지스틱함수이다&lt;/p&gt;

&lt;p&gt;로지스틱 함수는 least square방식이 아니라 maximum likelihood로써 적합을 한다(구체적으로는, mse는 loss function이 convex형태로 표현되지 않는다고 한다)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;또한, 그렇기에 logistic regression의 coefficient는 likelihood ratio test를 이용하여 검정한다. 이쯤가면 너무 통계통계한 부분이므로 여기서 생략하겠다.(사실 잘 모른다.)&lt;/p&gt;

  &lt;p&gt;또한 그로 인해 기존의 여러 가정들이 필요하지 않게 되었지만, 반면에 mse보다 수렴속도가 더 느리다고 한다. &lt;a href=&quot;http://www.statisticssolutions.com/wp-content/uploads/wp-post-to-pdf-enhanced-cache/1/assumptions-of-logistic-regression.pdf&quot;&gt;참고&lt;/a&gt; 또한, mle는 lse보다 효율적이지 않기에, 추정을 위해 더 많은 데이터가 필요해진다. (흔히 OLS에선 &lt;strong&gt;n&amp;gt;3p&lt;/strong&gt;를 추천하지만, mle에선 &lt;strong&gt;n&amp;gt;5p&lt;/strong&gt;를 추천한다. &lt;strong&gt;n&amp;gt;10p&lt;/strong&gt;를 추천하는 통계학자들도 많다.)&lt;/p&gt;

  &lt;p&gt;사라진 가정 : 로지스틱은 정규성가정이 필요 없다. 또한, 등분산성 가정 역시 필요 없다.&lt;/p&gt;

  &lt;p&gt;여전히 유효한 가정 : error term들은 서로 indep해야한다, 즉 표본들은 독립적데이터다. 다중공선성이 없거나 적어야한다. (있을 경우, centering그래도 안될경우 factor analysis등의 방법을 취한다.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;여기서는 likelihood를 maximize하기 위해 지난시간에 사용했던 GD 함수를 이용하여 적합을 해보겠다.&lt;/p&gt;

&lt;h1 id=&quot;likelihood&quot;&gt;Likelihood&lt;/h1&gt;
&lt;p&gt;likelihood는 단순하게 해당 y들을 맞출수 있을 가장 그럴듯한 beta라고 보면 된다.&lt;/p&gt;

&lt;p&gt;고정된 beta에서, 특정 y_i에 대해서 우리 모델이 뱉는 확률(i.e 모델이 추정한 bernouli 분포는)은 다음과 같이 말할 수 있다.(yi=1 or 0의 두가지 경우이다)&lt;/p&gt;

&lt;p&gt;$p(y_i\vert\boldsymbol X_i,\beta)=f(\boldsymbol x_i \beta)^{y_i}*(1-f(\boldsymbol x_i \beta))^{1-y_i}$&lt;/p&gt;

&lt;p&gt;이를 단순히 beta에 대해 표현하면, beta에 대한 likelihood가 되어 해당 likelihood를 maximize하는 beta를 구할 수 있다. 또한, 이는 계산상의 이유로(underflow방지, derivative에서 훨씬 수월) log를 씌워 log_likelihood로 표현하기도 한다. (log는 단조증가여서 정보의 손실이 없다)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44199314-44887e00-a133-11e8-8093-fac2130062ad.PNG&quot; alt=&quot;likelihood_logistic&quot; /&gt;&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;logistic_log_likelihood_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;#print('when True,',logistic(dot(x_i, beta)))
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;#print(x_i,beta)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;#print('dot is ',dot(x_i,beta))
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;#print('here is ValueError',logistic(dot(x_i, beta)))
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#likelihood에서 결국 boundary된 확률값들을 cummprod해주는게 필요한데(아님 log_cumsum) 
#근데 해당 확률이 0에 계산오차로 완전수렴해 버리는 경우도 잇어서(물론 그경우 mle의 고려대상이 아니겟지만, for문돌며 gd할때 오류가 나버려서 1e-9를 해주었다)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;또한, 만약 우리가 (대부분의 ML 기법이 기본가정으로 깔고가듯이) &lt;strong&gt;각 데이터가 서로 독립이라고 가정&lt;/strong&gt;한다면, 
위에서 구한 likelihood를 모든 data y_i들에 대해서 cumproduct를 해서 전체 데이터에 대한 likelihood와, 그 전체 데이터의 likelihood를 maximize하는 beta를 구할 수 잇을 것이다.(혹은 log-likelihood의 경우. 이 경우 cumprod가 아니라 cumsum이라는 것만 달라진다)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;logistic_log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#log의 경우 cumprod가 cumsum이 되므로, 단순히 더해준다.
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic_log_likelihood_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;blockquote&gt;
  &lt;p&gt;데이터들간의 독립이 뭘까? 예를 들자면 키~몸무게로 regression을할때 데이터안에 4명의 가족이 끼어있다면, 그들은 indep가 아니다(error항이 서로 비슷할 것이다)
 은 timeseries데이터들(사람1의 10살키,몸무게..사람1의 80살키,몸무게.사람n의 80살키,몸무게)를 예측할때에도 같은 timeseries는 서로 연관이 되어있다고 봐야한다&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;즉, 모든 데이터$y_i$에 대해 구한 우리의 최종적인 목적함수 log likelihood는 다음과 같다.&lt;/p&gt;

&lt;p&gt;(bold체는 하려하다가 귀찬아서 생략했지만, $\boldsymbol \beta$는 모두 $(\beta_0,…,\beta_p)$의 차원을 가진 벡터이고 $x_i$ 역시 intercept를 포함해서 $(1,x_1,..,x_p)$의 벡터이다)&lt;/p&gt;

&lt;p&gt;$J(\boldsymbol\beta)=\log L(\beta)=\frac{1}{n}[\sum_i^n y_i\log f(x_i\beta)+\sum(1- y_i)\log(1-f(x_i\beta))]$]&lt;/p&gt;

&lt;p&gt;해당 최종식을 gradient descent를 통해 최적화를 할것이다. 그러기 위해선 각 $\beta_j$에 대해 gradient를 구해야 한다.&lt;/p&gt;

&lt;p&gt;수학시간은 아니지만, 해당 식의 gradient를 이번만 짚고 넘어가보자.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{align}\frac{\partial J(\boldsymbol\beta)}{\partial\beta_j }&amp;=\frac{\partial}{\partial\beta_j}[\frac{1}{n}\sum_i^n y_i\log f(x_i\beta)+\sum(1- y_i)\log(1-f(x_i\beta))]\\ &amp;= \frac{1}{n}\sum [\frac{y_i\frac{\partial}{\partial\beta_j}f(x_i\beta)}{f(x_i\beta)}+\frac{(1-y_i)\frac{\partial}{\partial \beta_j}(1-f(x_i\beta))}{1-f(x_i\beta)}] \\&amp;=\frac{1}{n}\sum [\frac{y_i\ f'(x_i\beta)*x_{ij}}{f(x_i\beta)}+\frac{(1-y_i)(-f'(x_i\beta))*x_{ij}}{1-f(x_i\beta)}],\\&amp; (\because \frac{\partial x_i\beta}{\partial\beta_j}= \frac{\partial (x_{i1}\beta_1+..+x_{ij}\beta_j+..)}{\partial\beta_j}=x_{ij})\\ &amp; =\frac{1}{n}\sum [\frac{y_i*f(x_i\beta)*(1-f(x_i\beta))*x_{ij}}{f(x_i\beta)}-\frac{(1-y_i)*(f(x_i\beta)*(1-f(x_i\beta))*x_{ij}}{1-f(x_i\beta)}],\\&amp;(\because f'(A)=[f(A)*(1-f(A)])\\&amp;=\frac{1}{n}\sum [{y_i*(1-f(x_i\beta))*x_{ij}}-{(1-y_i)*f(x_i\beta)*x_{ij}}]\\&amp;=\frac{1}{n}\sum[(y-f(x_i\beta))x_{ij}]\end{align} %]]&gt;&lt;/script&gt;

  &lt;p&gt;즉, 특정 데이터 $x_i$에 대해 계수 $\beta_j$의 gradient는 ‘$\frac{1}{n}\sum[(y-f(x_i\beta))x_{ij}]$’이다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;다음은 앞서 정리한 내용을 바탕으로 구현된 logistic regression이다.대해 모든 데이터(혹은 sgd의 경우 샘플링된 데이터)에 대해  log likelihood의 편미분값을 더하고(혹은 평균내고. $\frac{1}{n}$은 상수이므로 최적화에 영향을 미치지 않는다) 거기에 미리 지정한 learning rate(여기선 step size라고 notation이 써져있다)를 곱하여 그만큼 update를 한다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;logistic_log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#log의 경우 cumprod가 cumsum이 되므로, 단순히 더해준다.
&lt;/span&gt;    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;for x_i, y_i in zip(x, y):
        print(logistic_log_likelihood_i(x_i, y_i, beta))&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic_log_likelihood_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;logistic_log_partial_ij&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;here i is the index of the data point,
    j the index of the derivative&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;logistic_log_gradient_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#각 계수 1~j에 대해 구한 partial deriv를 가진 1*j 벡터
&lt;/span&gt;    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;the gradient of the log likelihood 
    corresponding to the i-th data point&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;#print('this is x_i',x_i)
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;#print([logistic_log_partial_ij(x_i, y_i, beta, j)for j, _ in enumerate(beta)])
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic_log_partial_ij&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
            
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;logistic_log_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#그 벡터들을 모든 데이터 i개에 대해서 더해준다
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;#print('this si array',np.array([logistic_log_gradient_i(x_i, y_i, beta)for x_i, y_i in zip(x,y)]))
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic_log_gradient_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;%%&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;logistic regression:&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_test_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rescaled_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.33&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# want to maximize log likelihood on the training data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;partial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic_log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;partial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic_log_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# pick a random starting point
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# and maximize using gradient descent
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;maximize_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#모든 데이터에 대해 gradient를 구해서 sum을하고, 그만큼 update하는것.
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;beta_batch&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;logistic regression:
next_theta [-0.98255588458629939, 2.3852843058873878, -2.1113132057851853]
next_theta [-1.6231205844767986, 2.9325005457297024, -2.9904220026290869]
next_theta [-1.6845316575352558, 3.4541986134410352, -3.2120994183075102]
next_theta [-1.763457666332795, 3.5988394252854343, -3.4983715931343213]
next_theta [-1.8178162645708138, 3.7684258957250201, -3.6508389962038663]
next_theta [-1.8506352010086142, 3.8733776113222493, -3.7382869413690938]
next_theta [-1.8711133955049506, 3.9396845394768709, -3.7907247408212608]
next_theta [-1.884057747511656, 3.9818799446732993, -3.8231967753842135]
next_theta [-1.8923209208041496, 4.0087980588515881, -3.8437741842667696]
next_theta [-1.8976291568201162, 4.0259916573174905, -3.8570150985780529]
next_theta [-1.9010484929931222, 4.0369915442924063, -3.8656049709518974]
next_theta [-1.9032580841621607, 4.0440371450804316, -3.8712051897327044]
next_theta [-1.9049000320852507, 4.0502654786007559, -3.8743316201458753]
next_theta [-1.9057510521365857, 4.0524794633637535, -3.8770025027550772]
beta_batch [-1.906182482651773, 4.0530838693737428, -3.8788953691426906]
Wall time: 1.04 s
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;%%&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;maximize_stochastic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic_log_likelihood_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                           &lt;span class=&quot;n&quot;&gt;logistic_log_gradient_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                           &lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;beta stochastic&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;min_theta updates [1, 1, 1]
min_theta updates [-1.2679993666825518, 2.0110699795905385, -1.930051041435664]
min_theta updates [-1.4768306698812361, 2.743237461070941, -2.6392424401722647]
min_theta updates [-1.6057675528751156, 3.1559211370221583, -3.0229551097263743]
min_theta updates [-1.690510565123893, 3.415967989691299, -3.2665060117900717]
min_theta updates [-1.7504435935307276, 3.583775137243253, -3.4405470946821524]
min_theta updates [-1.793646263969424, 3.704489929737186, -3.5590487749898037]
min_theta updates [-1.8174922511616782, 3.7925518487145067, -3.6454846681199076]
min_theta updates [-1.8408885825791077, 3.8624878817342068, -3.70068299132356]
min_theta updates [-1.8547808871820977, 3.9134815135640904, -3.743702967792522]
min_theta updates [-1.8662758232017913, 3.9481631856179966, -3.777549032672308]
iterations_with_no_improvement is growing... 5
min_theta updates [-1.8914001807751846, 3.9918356822733148, -3.820470489514673]
iterations_with_no_improvement is growing... 5
min_theta updates [-1.8888930102866952, 4.008210432054739, -3.834111274491687]
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
min_theta updates [-1.8993159351402242, 4.0229180503190705, -3.85260331633106]
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 25
iterations_with_no_improvement is growing... 45
iterations_with_no_improvement is growing... 65
iterations_with_no_improvement is growing... 85
beta stochastic [-1.901794592305049, 4.0402458845427285, -3.8670118939700515]
Wall time: 1.12 s
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;둘다 실제값인 beta_hat = [-1.90, 4.05, -3.87]과 거의 동일한 예측값을 추정하였음을 알 수 있다.&lt;/p&gt;

&lt;p&gt;덤으로 test set에 대해 precision과 recall을 계산해 보았다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;#decision boundary를 0.5로 설정해서 precision과 recall을 봐본다. 근데 unbalanced인경우 등 threshold를 바꿔줄수도
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;true_positives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;false_positives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_negatives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;false_negatives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;predict&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predict&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# TP: paid and we predict paid
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;true_positives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;                   &lt;span class=&quot;c1&quot;&gt;# FN: paid and we predict unpaid
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;false_negatives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predict&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;             &lt;span class=&quot;c1&quot;&gt;# FP: unpaid and we predict paid
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;false_positives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;                            &lt;span class=&quot;c1&quot;&gt;# TN: unpaid and we predict unpaid
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;true_negatives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;precision&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_positives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_positives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;false_positives&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;recall&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_positives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_positives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;false_negatives&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;precision&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;precision&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;recall&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;recall&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;precision 0.9333333333333333
recall 0.8235294117647058
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logistic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scatter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;predicted probability&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;actual outcome&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Logistic Regression Predicted vs. Actual&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44199236-0e4afe80-a133-11e8-8ca5-77c130fe2eec.png&quot; alt=&quot;output_38_0&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;덧-해석에-관하여&quot;&gt;덧. 해석에 관하여&lt;/h3&gt;

&lt;p&gt;그럼 왜 굳이 하고 많은 S자형 함수 중에 logistic function이 classification에 사용된것일까? 많은 해석을 할 수 있겠지만 그중 한가지 이유는 바로 logistic function을 사용할 경우 모델을 odds의 개념으로 해석할 수 있기 때문이다.&lt;/p&gt;

&lt;h3 id=&quot;오즈odds란&quot;&gt;오즈(Odds)란?&lt;/h3&gt;

&lt;p&gt;오즈란 간단히 말해 &lt;strong&gt;(일어날확률)/(일어나지 않을확률)&lt;/strong&gt;이다. 통계학에서, 혹은 도박에서 승산의 상대적인 강도를 토현할때 사용되는 지표라고 보면 된다. 예를들어 도박에서 이길 확률($P(X=True)$)이 0.75, 질 확률($1-P(X=True)$)이 0.25이면, 이때 odds=$\frac{P(X)}{1-P(X)}=\frac{0.75}{0.25}=3$이라고 볼 수 있다. 우리가 평소에 이길확률이 질확률 보다 3배 높은 게임이라고 표현하는 것이 오즈를 이용한 표현이다.&lt;/p&gt;

&lt;p&gt;왜 굳이 확률을 확률로써 보면 되지 오즈를 새로 정의하냐? 로지스틱함수와 같은 특정상황에서는 해석을할때 확률로써하는 것보다 &lt;strong&gt;오즈로써 해석하는것이 훨씬 수월한 상황들이 있기 때문&lt;/strong&gt;(아래 좀더 설명한다).&lt;/p&gt;

&lt;p&gt;다시 돌아와서, binary classification을 하는 로지스틱함수는, 사실 해당 feature를 가진 데이터가 $Y=True$를 가질 확률을 나타내는것이라 볼 수 있다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;X:사건이 일어났는지 안났는지. 사건이 일어났으면 X=1, 안일어 났으면 X=0&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;E(Y)=1*P(X)+0*(1-P(X))=P(X)&lt;/script&gt;, 즉, 사건이일어날 &lt;strong&gt;확률&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;그리고 여기서, (우리가 로지스틱함수를 사용하였기때문에,) 오즈에 로그를 씌운 &lt;strong&gt;로짓을 X에 대해 선형으로써 표현&lt;/strong&gt;할 수 있게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;$Y=\frac{1}{1+e^{-f(x)}}+\epsilon, $ where $f(x)=\beta_0+\beta_1x_1+..+\beta_px_p$&lt;/p&gt;

  &lt;p&gt;$E(Y)=\frac{e^{f(x)}}{e^{f(x)}+1}$&lt;/p&gt;

  &lt;p&gt;$e^{f(x)}*E(Y)+E(Y)=e^{f(x)}$&lt;/p&gt;

  &lt;p&gt;$e^{f(x)}(Y-1)=-Y$&lt;/p&gt;

  &lt;p&gt;$e^{f(x)}=\frac{E(Y)}{1-E(Y)}$&lt;/p&gt;

  &lt;p&gt;$\therefore f(x)=\log(\frac{E(Y)}{1-E(Y)})=\log(\frac{P(X)}{1-P(X)})+\epsilon$&lt;/p&gt;

&lt;/blockquote&gt;

&lt;p&gt;즉 로지스틱 회귀는 해당 &lt;strong&gt;Y변수의 로짓(log_odds)&lt;/strong&gt;이 &lt;strong&gt;X변수들&lt;/strong&gt;과 &lt;strong&gt;선형관계&lt;/strong&gt;가 있다고 가정을 하는것이라고 해석할 수 있다.&lt;/p&gt;

&lt;h3 id=&quot;그에-따른-계수에-해석&quot;&gt;그에 따른 계수에 해석&lt;/h3&gt;

&lt;p&gt;또한, 이렇게 로짓으로 표현가능하다는 점에서, &lt;strong&gt;계수에 대한 해석&lt;/strong&gt; 역시 선형회귀처럼 용이해진다.(이 부분이 아직까지 로지스틱이 많이 쓰이는 이유이다. 즉, 해석력이 좋기때문)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;linear regression&lt;/strong&gt;에서 계수$\beta_j$는 다른 변수($x_i$)들이 고정되어있는 상태에서 $x_j$가 1증가했을때 &lt;strong&gt;Y의 증가량의 기대값&lt;/strong&gt;(즉, $\beta_j$=3이라면 $x_j$가 1 증가하면 $E(Y)$는 3증가한다. )을 의미한다. 반면에 &lt;strong&gt;logistic regression&lt;/strong&gt;에서 Y는 ‘해당 데이터가 class1에 속할 확률’을 나타내는데, 확률은 S자 개형을 가지고 있기때문에 X의 증가량이 우리모델에서 &lt;strong&gt;확률(Y)자체에 어떤 영향을 미치는지는 상수로 표현할 수 없다&lt;/strong&gt;. (sigmoid의 개형을 생각해보자. x가 1증가할때 y가 몇증가할지는 각 구간마다 다 다르다.)&lt;/p&gt;

&lt;p&gt;그러나 로지스틱함수로서 로짓의 개념을 사용할 수 있기에, 로지스틱회귀에서 계수$\beta_j$는 $x_j$가 1증가했을때 Y의 &lt;strong&gt;로짓&lt;/strong&gt;의 증가량의 기대값이라는 의미를 갖게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;위의 증명에서 아주 간단하게 이어진다.&lt;/p&gt;

  &lt;p&gt;$f(x)=\beta_0+\beta_1x_1+..+\beta_px_p=\log(\frac{P(X)}{1-P(X)})+\epsilon$,&lt;/p&gt;

  &lt;p&gt;따라서 $x_j$의 계수가 $\beta_j$라면, ‘$x_j$가 1 증가할때(i.e. $\beta_j(x_j+1)$) &lt;strong&gt;1. 로짓&lt;/strong&gt;이 $\beta_j$만큼 증가할것(add)’이라고 표현할 수 있다.&lt;/p&gt;

  &lt;p&gt;로짓이 아니라 오즈로 표현한다면, 다음과 같이 지수부분에 들어가서 product로 표현되므로,&lt;/p&gt;

  &lt;p&gt;‘$x_j$가 1 증가할때 &lt;strong&gt;2. 오즈비가&lt;/strong&gt; $e^{\beta_j}$배 만큼 커질것(product)’라고도 표현할 수 있다. 사실상 둘이 같은 말이니 헷갈리지 말자.(1.로짓의 표현과 2.오즈비의 표현이 같은 의미인데, 나는 헷갈려서 구글링 1시간을 소비하고 정리하였다ㅋㅋ)&lt;/p&gt;

  &lt;p&gt;$e^{f(x)}=\frac{P(X)_1}{1-P(X)_1}=odds_1$ =&amp;gt; &lt;script type=&quot;math/tex&quot;&gt;e^{f(x)+\beta_j}=[\frac{P(X)_1}{1-P(X)_1}]*e^{\beta_j}=odds_1*e^{\beta_j}=odds_2&lt;/script&gt;&lt;/p&gt;

  &lt;p&gt;$\therefore odds_2=odds_1*e^{\beta_j}$&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;끝! 아래는 정리와 사용한 함수들. 맨아래cell을 실행하고 위에를 실행하면 모두 제대로 실행됩니답&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;참고:&lt;/p&gt;

&lt;p&gt;가장 정리 잘해놓은곳. 로짓과 선형관계 증명:http://www.win-vector.com/blog/2011/09/the-simpler-derivation-of-logistic-regression/)&lt;/p&gt;

&lt;p&gt;전반적인 강의안 : http://www.columbia.edu/~so33/SusDev/Lecture_10.pdf&lt;/p&gt;

&lt;p&gt;gradient 편미분 증명:https://stats.stackexchange.com/questions/278771/how-is-the-cost-function-from-logistic-regression-derivated
로지스틱에 대한 andew ng강의정리:http://gnujoow.github.io/ml/2016/01/29/ML3-Logistic-Regression/)
mle에 대하여:https://onlinecourses.science.psu.edu/stat414/node/191/)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;functools&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;partial&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;partial_difference_quotient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;compute the ith partial difference quotient of f at v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# add h to just the ith element of v
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# [원래a,원래b,,,,i+h,...]이런식의 리스트 반환, 즉 i만 h만큼 아주 조금 옴겻을때!
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;squared_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;squared_error_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;# alpha partial derivative
&lt;/span&gt;            &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# beta partial derivative
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#여기서는 loss function에 y까지 필요하다
#위에서는 이미 '편차'의 제곱과 같이 input하나로 loss구햇으면 지금은 x,y둘다 넣어줘서 구하는형식!
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;minimize_stochastic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;safe&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    

    &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;                             &lt;span class=&quot;c1&quot;&gt;# initial guess
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_0&lt;/span&gt;                             &lt;span class=&quot;c1&quot;&gt;# initial step size
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;min_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;inf&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# the minimum so far
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# if we ever go 100 iterations with no improvement, stop
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;safe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'too much iter!'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# if we've found a new minimum, remember it
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# and go back to the original step size
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;min_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'min_theta updates'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_0&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# otherwise we're not improving, so try shrinking the step size
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;  &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;iterations_with_no_improvement is growing...&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;# and take a gradient step for each of the data points        
&lt;/span&gt;        &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;for x_i, y_i in in_random_order(data):
            gradient_i = gradient_fn(x_i, y_i, theta)
            theta = vector_subtract(theta, scalar_multiply(alpha, gradient_i))&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;indexes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))];&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indexes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rand_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indexes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;gradient_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rand_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rand_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector_subtract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scalar_multiply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_theta&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vector_subtract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;subtracts corresponding elements&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scalar_multiply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;c is a number, v is a vector&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;minimize_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.000001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;use gradient descent to find theta that minimizes target function&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;step_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.00001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# set theta to initial value
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;#target_fn = safe(target_fn) # safe version of target_fn
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# value we're minimizing
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;#print('value:',value)
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;#print('theta',theta)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;#print('gradient',gradient)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;next_thetas&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step_size&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;#print('text_thetas',next_thetas)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# choose the one that minimizes the error function
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;next_theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_thetas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#추정값중 가장 minimum
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'next_theta'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;next_value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;#print('next_value',next_value)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# stop if we're &quot;converging&quot;
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_value&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;distance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;power&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;direction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;move step_size in the direction from v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;direction_i&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;direction_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;direction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squares_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#다변량 square일때 각각의 편미분들
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#다변량일때의 gradient는 편미분을해서 구한다.
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;partial_difference_quotient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;compute the ith partial difference quotient of f at v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# add h to just the ith element of v
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# [원래a,원래b,,,,i+h,...]이런식의 리스트 반환, 즉 i만 h만큼 아주 조금 옴겻을때!
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#i만 아주 약간의 차이가 있는 두 리스트를 각각의 f(x)에 넣엇을때의 차이(를 h로 나누기)
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;estimate_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.00001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;partial_difference_quotient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#여러 변수의 각각의 편미분이 나오는 리스트 반환
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squares&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;computes the sum of squared elements in v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;difference_quotient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;least_squares_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;given training values for x and y,
    find the least-squares values of alpha and beta&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correlation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;standard_deviation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;standard_deviation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;correlation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stdev_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stdev_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdev_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdev_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cov&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdev_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdev_y&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# if no variation, correlation is zero
&lt;/span&gt;    
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;covariance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;standard_deviation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;variance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;    

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;variance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;assumes x has at least two elements&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;deviations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sum_of_squares&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deviations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;translate x by subtracting its mean (so the result has mean 0)&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_bar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_bar&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squares&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;computes the sum of squared elements in v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;the error from predicting beta * x_i + alpha
    when the actual value is y_i&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squared_errors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;#즉 이런식
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;

&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;math&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;num_rows&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# number of features of first row
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_rows&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_column&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# jth element of row A_i
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# for each row A_i
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;standard_deviation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;variance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;variance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;assumes x has at least two elements&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;deviations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sum_of_squares&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deviations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squares&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;v_1 * v_1 + ... + v_n * v_n&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;v_1 * w_1 + ... + v_n * w_n&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_i&lt;/span&gt;
               &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;translate x by subtracting its mean (so the result has mean 0)&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_bar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_bar&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;returns the means and standard deviations of each column&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;num_rows&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get_column&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stdevs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;standard_deviation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;get_column&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdevs&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;make_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_rows&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;entry_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;returns a num_rows x num_cols matrix
    whose (i,j)th entry is entry_fn(i, j)&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;entry_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# given i, create a list
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# [entry_fn(i, 0), ... ]
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_rows&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# create one list for each i
&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rescale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;rescales the input data so that each column
    has mean 0 and standard deviation 1
    leaves alone columns with no deviation&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdevs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rescaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdevs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdevs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;num_rows&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;make_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_rows&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_cols&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rescaled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;estimate_beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta_initial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minimize_stochastic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;squared_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;squared_error_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;beta_initial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vector_add&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;adds corresponding elements&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;split_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;split data into fractions [prob, 1 - prob]&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;row&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prob&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;row&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_test_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_pct&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# pair corresponding values
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;split_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_pct&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# split the data set of pairs
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# magical un-zip trick
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_test&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;maximize_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.000001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minimize_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;negate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                          &lt;span class=&quot;n&quot;&gt;negate_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                          &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                          &lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;maximize_stochastic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minimize_stochastic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;negate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;negate_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;negate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;return a function that for any input x returns -f(x)&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;args&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;args&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;negate_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;the same when f returns a list of numbers&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;args&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;args&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</description>
        <pubDate>Thu, 16 Aug 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/08/16/Scratch-Logistic-regression.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/08/16/Scratch-Logistic-regression.html</guid>
        
        <category>machine learning</category>
        
        <category>python implementation</category>
        
        <category>DataScience from Scratch</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[DS from Scratch] linear regression 이해하고 Gradient descent로 직접 최적화하기(with Python)</title>
        <description>
&lt;blockquote&gt;
  &lt;p&gt;(가독성과 재생산성을 모두 살리기 위해 맨 아래부분에 직접사용한 함수들을 모아놓았습니다. 코드를 실행하려면 맨아래 cell의 함수를 먼저 실행하고 위에서 부터 순서대로 실행하면 됩니다.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;아직 읽은 부분이 많지도 않아 충분히 바뀔 수 있습니다만, 한주동안 책을 접해보니, 다음과 같습니다.&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;가볍게 써져있다. 모델에 대한 근원적인 이야기나 수학적인 원리등은 거의(isl보다도 더) 안건들고 있습니다. 모델에 대한 간단한 특성설명, 파이썬으로 구현해보기가 메인입니다.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;그럼에도 불구하고 좋다. ISL로 모델에 대한 아주 얉은 지식이나마 쌓은 후에 접하기 좋은것 같다. 간단히 설명되는 특성에서도 나름 스스로 얻고 구글링해서 더 알아볼만한 점들이 많이 나온다. 무엇보다, numpy도 없이 모델을 구현하는데 나름 재미도 있다. (for문 돌리면서 멍때리고 쳐다보기..)&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;1-미분으로-simple-linear-regression-적합하기&quot;&gt;1. 미분으로 Simple Linear Regression 적합하기&lt;/h1&gt;

&lt;p&gt;ISL때와 마찬가지로, linear regression부터 나가도록 하겠습니다. 지난 ISL때 선형회귀의 이론에 집중하였다면 이번에는 좀더 선형회귀의 특성과 &lt;strong&gt;gradient descent를 통한 직접적인 구현&lt;/strong&gt;에 집중하도록 하겠습니다.&lt;/p&gt;

&lt;p&gt;선형회귀는 설명변수와 반응변수간에 선형적인 관계가 있을것이라는 다소 맹목적인 가정하에서 만들어진 모델이다. 고로 설명변수&lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;와 반응변수 &lt;script type=&quot;math/tex&quot;&gt;y&lt;/script&gt;가 있을때 목표는 &lt;script type=&quot;math/tex&quot;&gt;y_i=\beta x_i + \alpha + \epsilon_i&lt;/script&gt; 식의 계수를 찾는것으로 귀결된다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;#즉 이런식
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;어떻게 최적의 계수 $\alpha, \beta$를 찾을까? 가장 대표적인 방법이 sum of squared error를 줄이는 least square이다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;the error from predicting beta * x_i + alpha
    when the actual value is y_i&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squared_errors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;1-2-least-square와-maximum-likelihood&quot;&gt;1-2. least square와 maximum likelihood.&lt;/h2&gt;

&lt;p&gt;least square에 대한 해석이 물론 여러가지 있지만 그 방법중 하나로 &lt;strong&gt;정규가정일경우 maximum likelihood estimator를 찾는것과 같은 결과&lt;/strong&gt;가 된다는 것이다.&lt;/p&gt;

&lt;p&gt;likelihood는 간단히 말해, 해당 데이터를 가질만한 가장 likely한 모수&lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;이다. (데이터 $v_1,..,v_n$이 있을때, 그들이 나왔을 가장 가능성이 높은 모수 $\theta$)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44249323-dac5ae00-a1de-11e8-96cb-89d16d63439c.PNG&quot; alt=&quot;likelihood&quot; /&gt;&lt;/p&gt;

&lt;p&gt;근데 만약 우리가 (대표적으로 simple linear에서 그러하듯이, )error에 대해 mean0의 정규분포를 가정하면, &lt;script type=&quot;math/tex&quot;&gt;E(y)=\alpha+\beta*x&lt;/script&gt;이기 때문에&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;y&lt;/script&gt; ~ &lt;script type=&quot;math/tex&quot;&gt;N(\hat y,\sigma)&lt;/script&gt;이므로 해당 데이터에 대한 pdf는 밑에 식이 된다. (나머지는 fixed x에 대해 모두 fixed이기 때문에 error의 분포를 그대로 받게 된다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44249329-de593500-a1de-11e8-91e6-794bdb47c397.PNG&quot; alt=&quot;mle_mse&quot; /&gt;&lt;/p&gt;

&lt;p&gt;또한, 만약 우리가 (대부분의 ML 기법이 기본가정으로 깔고가듯이) &lt;strong&gt;각 데이터가 서로 독립이라고 가정&lt;/strong&gt;한다면,  전체 데이터에 대한 joint_pdf는 데이터 n개에 대해 곱하는 것과 같다. 수식으로 나타내면 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;% &lt;![CDATA[
\begin{align} J(\alpha,\beta)&amp;=\prod_i^n\frac{1}{\sqrt{2\pi\sigma}}exp(\frac{-(y_i-\alpha-\beta x_i)^2}{2\sigma^2})\\ &amp; =(\frac{1}{\sqrt{2\pi\sigma}})^nexp(\frac{-\sum_i^n(y_i-\alpha-\beta x_i)^2}{2\sigma^2})\end{align} %]]&gt;&lt;/script&gt;

&lt;p&gt;이때, $\pi$나 $\sigma$같은 (모델의 가정하에서) fixed constant를 빼면, 결국 &lt;script type=&quot;math/tex&quot;&gt;\sum(y-\alpha-\beta x)^2&lt;/script&gt;, 즉 &lt;strong&gt;least square만이 남는다&lt;/strong&gt;. 다시말해, error에 대한 정규분포를 가정하였을 경위 least square는 mle를 찾는 것과 완벽하게 동치이다.&lt;/p&gt;

&lt;p&gt;다시 본론으로 돌아와서, leas square를 봐보자.&lt;/p&gt;

&lt;p&gt;위 식에서 loss fuctiondl, 즉 sum of squares를 최소화하는 계수는 다음과 같다.&lt;/p&gt;

&lt;p&gt;$b_{0}=\bar y -b_{1}\bar x$&lt;/p&gt;

&lt;p&gt;$b_{1}=\frac{\sum x_{i}(y_{i}-\bar y)}{\sum x_{i}(x_{i}-\bar x)}$&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;$b_{0}$의 경우&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac {\partial RSS} {\partial b_0}=\frac {\partial \sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})^2} {\partial b_0}=0&lt;/script&gt;이 되는 값을 찾으면 된다.&lt;/p&gt;

  &lt;p&gt;${- 2\sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum(y_{i})-nb_{0}-\sum b_{1}x_{i}}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum(y_{i})-\sum b_{1}x_{i}}=nb_{0} $&lt;/p&gt;

  &lt;p&gt;$b_{0}=\frac{\sum(y_{i})}{n} -\frac{\sum b_{1}x_{i}}{n}$&lt;/p&gt;

  &lt;p&gt;$\therefore b_{0}=\bar y -b_{1}\bar x$&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;$b_{1}$의 경우&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac {\partial RSS} {\partial b_1}=\frac {\partial \sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})^2} {\partial b_1}=0&lt;/script&gt;이 되는 값을 찾으면 된다.&lt;/p&gt;

  &lt;p&gt;${- 2\sum_{i=1}^{n}x_{i}(y_{i}-b_{0}-b_{1}x_{i})}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum_{i=1}^{n}x_{i}(y_{i}-b_{0}-b_{1}x_{i})}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum(x_{i}y_{i})-b_{0}\sum x_{i}-\sum b_{1}x_{i}^2}=0 $&lt;/p&gt;

  &lt;p&gt;$\sum x_{i}(y_{i}-\bar y)-b_{1}\sum x_{i}(x_{i}-\bar x)=0, \because b_{0}=\bar y -b1\bar x$&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\therefore b_{1}=\frac{\sum x_{i}(y_{i}-\bar y)}{\sum x_{i}(x_{i}-\bar x)}&lt;/script&gt;, 이는 &lt;script type=&quot;math/tex&quot;&gt;\frac{\sum (x_{i}-\bar x)(y_{i}-\bar y)}{\sum (x_{i}-\bar x)(x_{i}-\bar x)}&lt;/script&gt;로도 나타낼 수 있어(전개하면 똑같다) &lt;script type=&quot;math/tex&quot;&gt;b_{1}=\frac{Sxy}{Sxx}&lt;/script&gt;라고 쓰기도 한다 (sum of x&amp;amp;y, sum of x&amp;amp;x)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;식을 잘보면, 결국 $\beta$(혹은 $b_1$)는 $\frac{cov(x,y)}{var(x)}$임을 알 수 있다.(분모분자에 각각 n혹은 n-1이 약분되었다고 보면 된다.)&lt;/p&gt;

&lt;p&gt;따라서 1차 단순선형회귀에서 $\beta$는 &lt;strong&gt;x변수의 변동성 대비 y와 관계있는 정도&lt;/strong&gt;라고 정성적으로 이해하여 쓰이기도 한다.(사회과학에서는 특히나 이런식으로 자주 쓰인다.)&lt;/p&gt;

&lt;p&gt;파이썬에서 미분을 전부 해서 스스로 최적해를 찾도록 할 수 있다면 좋겠지만, 파이썬에서 미분은 가능하지 않다. 그래서 이 책에서는 least_square_fit이라는 함수에 단순히 cov/var로써 표현을 하였다.(cov/var는 $corr*std(y)/std(x)$와 똑같다. corr의 정의가 $\frac{cov}{std(x) * std(y)}$이므로.)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;least_squares_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;given training values for x and y,
    find the least-squares values of alpha and beta&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correlation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;standard_deviation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;standard_deviation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;이를 통해 사이트내 친구 수로써 사이트활동 시간을 예측하는 선형회귀모델을 만들어보자.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;num_friends_good&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;49&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;41&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;21&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;21&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;19&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;19&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;daily_minutes_good&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;68.77&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;51.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;52.08&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;38.36&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;44.54&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;57.13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;51.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;41.42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;31.22&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;34.76&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;54.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;38.79&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;47.59&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;49.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.66&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;41.03&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.73&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;48.65&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;28.12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;46.62&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.57&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.98&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.07&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;23.77&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;39.73&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;40.57&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;31.65&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;31.21&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;20.45&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;21.93&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.34&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;23.49&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;46.94&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;30.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;33.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.23&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;21.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.94&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.24&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;40.57&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;25.07&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;19.42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;22.39&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;18.42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;46.96&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;23.72&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.41&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.97&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.76&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;40.32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;29.47&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;30.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;31&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;38.11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;38.18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.31&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;21.03&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;30.86&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.07&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;28.66&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;29.08&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;37.28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;15.28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.17&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;22.31&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;30.17&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;25.53&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;19.85&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.37&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;44.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;17.23&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;13.47&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.33&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.09&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.81&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;19.33&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;28.77&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.26&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;31.98&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;25.73&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.86&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;16.28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;34.51&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;15.23&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;39.72&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;40.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.06&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.76&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;34.76&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;16.13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;44.04&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;18.03&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;19.65&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.62&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.59&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;39.43&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;14.18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.24&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;40.13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;41.82&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.45&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.07&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;43.67&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.61&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;20.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;21.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;18.79&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.61&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.21&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.61&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;29.77&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;20.59&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.53&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;13.82&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;33.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;33.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.65&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;18.63&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;14.87&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;22.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.81&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;25.53&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.62&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.25&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;18.21&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;28.08&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;19.42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;29.79&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.99&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;28.32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.79&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.88&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;29.06&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;14.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;36.63&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;37.49&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;18.58&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;38.48&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.48&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;18.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;33.55&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;14.24&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;29.04&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.51&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;25.63&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;22.22&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;19&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.73&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;15.16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;13.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;29.27&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;33&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;13.74&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;20.42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;18.23&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;28.48&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.08&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.62&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;20.12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;35.26&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;19.92&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;31.02&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;16.49&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;12.16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;30.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;31.22&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;34.65&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;13.13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.51&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;33.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;31.57&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;14.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;33.42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;17.44&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;10.12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;24.42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.82&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;23.39&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;30.93&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;15.03&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;21.67&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;31.09&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;33.29&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;22.61&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;26.89&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;23.48&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;8.38&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;27.81&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;32.35&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;23.84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;least_squares_fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_friends_good&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;daily_minutes_good&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;alpha&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;beta&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;alpha 22.9167813834
beta 0.908340529495
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;결과는 수식으로 다 정리해놓고 cov/var로 파라미터 $\beta$들을 그냥 적합을 해버리니 조금 심심하다.  좀더 스스로 짠 모델답도록 알아서 최적의 해를 찾아가게 할 방법은 없을까?&lt;/p&gt;

&lt;h1 id=&quot;2-gradient-descent&quot;&gt;2. Gradient descent&lt;/h1&gt;

&lt;p&gt;이번엔 그럼 이미 계산된 해로써 모델을 만드는게 아니라, gradient descent를 사용하여 직접 최적화를 시켜주자. 그전에, gradient descent에 대해서 알아보자.&lt;/p&gt;

&lt;p&gt;###Gradient descent란?&lt;/p&gt;

&lt;p&gt;Gradient descent는, 대표적인 parameter 최적화방법으로, 매 iteration(혹은 시도)마다 각 parameter들의 gradient를 구해서 loss func를 최소화하는 방향으로 업데이트 해주는 최적화방식이다.(말이 조금 지저분한데, 아래 다시 설명한다.)&lt;/p&gt;

&lt;p&gt;우리가 만든 모델은 어떤 목적함수(cost function)이 있을테고, 그를 구성하고 있는 파라미터$\beta$들이 있을 것이다. (위의 linear regression예시에서는 $\sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})^2$, 즉 sse가 우리의 목적함수 였고 그를 구성하는 파라미터는 각각 기울기$b_1$과 intercept $b_0$이 있었다.). cost function은 사실상 $b_0,b_1…$등의 &lt;strong&gt;변수&lt;/strong&gt;로 이루어진 &lt;strong&gt;함수&lt;/strong&gt;이므로, 우리가 이차함수 $y=x^2$을 그리듯이, 아래의 그림처럼 그래프로써 표현할 수 있다(절대로 아래 그림처럼 항상 원만한 형태로 나오지는 않을것이다). 이때 cost function을 최소화 시키는 parameter들을 찾는것이 우리의 목적이다. 변수가 하나뿐인 simple linear regresssion의 경우 몇줄의 수식으로 손쉽게 미분을하여 cost function을 최소화시키는 점을 찾을 수 있었기에, 이 경우는 굳이 다른 최적화 방법을 찾을 필요가 없다. 그러나, 변수가 많아지거나, cost function이 복잡해지는 등 문제가 조금만 복잡해지면, 최적해를 찾기가 굉장히 어렵거나, 혹은 최적해가 존재하는지도 명확하지 않은 경우가 많다. 그 경우 가능한 최적해에 가깝(근사)하다고 할만한 해를 찾아야 하는데, 이때 여러가지 최적화방법이 사용된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44206560-ca172880-a149-11e8-8221-0298002571b0.PNG&quot; alt=&quot;gradient&quot; /&gt;&lt;/p&gt;

&lt;p&gt;gradient descent는 cost function의 최적해를 찾기위해, 각각의 계수에 대하여 미분(혹은 다변량인 경우 편미분)을 하여 gradient를 구하고, 해당 cost function을 최소화 시키는 방향으로 조금씩 update를 해나가는 최적화 방법이다.&lt;/p&gt;

&lt;p&gt;다시 위 그림의 cost function에서, 빨간색 화살표가 gradient방향을 가르키고 해당 방향으로 조금씩 update를 하는 것이다.&lt;/p&gt;

&lt;h3 id=&quot;편미분이란&quot;&gt;편미분이란?&lt;/h3&gt;

&lt;p&gt;편미분이란, 하나의 계수(혹은 변수)에 대해서만 행해지는 미분이다. 예를들어 변수가 $\beta_0,..,\beta_p$와 같이 여러개일때 $\beta_j$의 편미분이란 $\beta_j$를 제외한 모든 변수들이 다 고정된 상수(그 값을 모르더라도, 고정된 채라고 가정하고)라고 치부한 상태에서 $\beta_j$에 대해서만 행해지는 미분이다. 즉, &lt;strong&gt;다른 모든 변수들이 고정되어 있을때,&lt;/strong&gt; &lt;strong&gt;해당 변수 $\beta_j$가 아주 조금 변화하였을때, 해당 cost function은 얼마나 영향을 받아 변화할지&lt;/strong&gt;를 나타낸다고 할 수 있다.&lt;/p&gt;

&lt;p&gt;그럼 편미분은 어떻게 구현하느냐? 단변수에 대한 미분은 아래와 같은 그림처럼, h-&amp;gt;0에 수렴하는 아주 작은 값을 움직일때 값이 얼마나 변하는지를 의미한다 할 수 있다.
&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44206561-ca172880-a149-11e8-8153-3ee2632004de.PNG&quot; alt=&quot;approximate&quot; /&gt;
그러나 파이썬에는 limit(0은 아니지만 0에 무한히 가까운 수)를 구현할 수 없기에, 여기서는 아주 작은 값을 input으로 근사를한다&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squares&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;computes the sum of squared elements in v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;difference_quotient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#'h'만큼 움직였을때의 변화율로써 근사를 한다. 여기서 h는 1e-9와같이 매우 작은 수가 들어간다.
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;또, 다변량인 경우 gradient는 편미분을 해서 구하는 함수를 짠다. 1~j개의 변수가 있을때, 각각 다른 변수들은 고정된채 하나의 변수만 아주 조금 옴겼을때의 변화율을 모두 구한다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;#다변량일때의 gradient는 편미분을해서 구한다.
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;partial_difference_quotient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#여기서도 역시 'h'만큼 움직였을때의 변화율로써 근사를 한다. 여기서 h는 1e-9와같이 매우 작은 수가 들어간다.
&lt;/span&gt;    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;compute the ith partial difference quotient of f at v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# add h to just the ith element of v
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# [원래a,원래b,,,,i+h,...]이런식의 리스트 반환, 즉 i만 h만큼 아주 조금 옴겻을때!
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;#i만 아주 약간의 차이가 있는 두 리스트를 각각의 f(x)에 넣엇을때의 차이(를 h로 나누기)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;최종적으로 estimate_gradient에는, 편미분을 통해 각각의 변수에 대해 구해진 모든 변화율들을 포함한 list를 반환하는 함수를 만든다.&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;estimate_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.00001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;partial_difference_quotient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#여러 변수의 각각의 편미분이 나오는 리스트 반환
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;이제 간단한 loss funcstion을 정의해서 위의 함수를 test해보자.&lt;/p&gt;

&lt;p&gt;예를 들어, loss function을 &lt;script type=&quot;math/tex&quot;&gt;\sum^n_{i} i*{x_i}&lt;/script&gt; 이라고 정의해보면 다음과 같다. (&lt;script type=&quot;math/tex&quot;&gt;0*x_0+1*x_1+..10*x_{10}&lt;/script&gt;과 같은 형태가 될것이다.)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;사실 loss function에는 실제 데이터를 통해 구해진 $x_i$들이 있을테고, 그를 각 데이터들에 대해 sum(혹은 mean)을 하여 cost function을 구하게 된다. 각 데이터들에 대해서 구하는 작업은 잠시 차치하고, 여기서는 쉬운 이해를 위해 $x_i$를 직접 설정하여 넣어준다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;my_sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_ilst&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;res_list&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_ilst&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;res_list&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp_ilst&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;my_sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;([0, 1, 4, 9, 16, 25, 36, 49, 64, 81], 285) 우선 partial_difference_quotient로 5번째 변수에 대해서 편미분값을 구해보자.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;#5번째에 대한 편미분
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;partial_difference_quotient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;my_sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;777&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#1*i_1+2_i2....식으로 가니, i_5의 편미분은 5!
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;4.94765117764473  $0*x_0+1*x_1+..10*x_{10}$와 같은 형태이니 $x_5$의 편미분값이 5가 나오는 것을 확인할 수 있다.(실제 limit값을 사용하지 않았기에, 약간의 계산오차가 존재한다.)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;이번에는 etimate_gradient함수를 이용해서, 모든 변수에 대해서 gradient를 구해보자.  &lt;script type=&quot;math/tex&quot;&gt;0*x_0+1*x_1+..10*x_{10}&lt;/script&gt;와 같은 형태이니 &lt;script type=&quot;math/tex&quot;&gt;x_n&lt;/script&gt;에 [0~10]의 리스트를 넣거나 [0~20]의 리스트를 넣거나 gradient값은 [0,1,..,10]이 나올 것이다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;estimate_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;my_sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[0.0,
 0.9999999997489795,
 1.999999999497959,
 2.9999999992469384,
 4.000000000132786,
 4.999999999881766,
 5.999999999630745,
 7.000000000516593,
 8.000000000265572,
 9.000000000014552]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;이제 gradient는 구했고, 이를 통해 진짜 gradient descent를 이용한 최적화를 해보자. 우선 가장 쉽게, loss func이 &lt;script type=&quot;math/tex&quot;&gt;\sum x^2&lt;/script&gt;라고 해보자. (해당 loss function식을 최소화하는 &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;들은 당연히 &lt;script type=&quot;math/tex&quot;&gt;x=(0,0,.,0)&lt;/script&gt;일것임을 직관적으로 알고 있다.) 우선 각각에 대한 편미분은 &lt;script type=&quot;math/tex&quot;&gt;2*x&lt;/script&gt;일 것이므로 이를 정의한다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;direction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;move step_size in the direction from v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;direction_i&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;direction_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;direction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squares_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#다변량 square일때 각각의 편미분들
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;distance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;power&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# pick a random starting point
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[7, 0, 4] 그리곤 구해진 gradient의 방향으로 (**-1** x step_size)만큼 업데이트를 해준다. 만약 더이상 유의미한 업데이트가 되지 않는다 생각하면, break구문을 이용해 멈춘다. (별다른 업데이트가 되지 않았다는 것을 여기서는 update이전의 parameter와 update된 parameter들간의 L2norm으로 정의하였다.)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.00000000000000000001&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sum_of_squares_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# compute the gradient at v
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;next_v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# take a negative gradient step
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;distance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# stop if we're converging
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_v&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# continue if we're not
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[4.290199788520775e-09, 0.0, 2.4515427362975787e-09] 역시나 0에 매우 근사한 수치로 수렴함을 알 수 있다.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;왜--1-x-step_size&quot;&gt;왜 “-1 X step_size”???&lt;/h2&gt;

&lt;p&gt;위에서, gradient를 구하고, (그 gradient의 방향) x (&lt;strong&gt;-1&lt;/strong&gt; x step_size)만큼을 업데이트 해준다고 하였다. step_size는 우리가 흔히 아는 learning rate, 즉 그 방향으로 어느정도를 갈지 설정해준것인데, 왜 &lt;strong&gt;-1&lt;/strong&gt;을 곱해줄까?&lt;/p&gt;

&lt;h3 id=&quot;임의의-cost-function에-대하여-해당-function을-minimize하는-방향언-언제나-gradient의-반대-방향이다&quot;&gt;임의의 cost function에 대하여, 해당 function을 minimize하는 방향언 ‘언제나’ gradient의 ‘반대 방향’이다.&lt;/h3&gt;

&lt;p&gt;사실 gradient descent를 보면서 언제나 $-1*\eta$만큼 업데이트한다는걸 수식으로 보고 별 생각 없이 넘겼었는데, 예전에 누군가 ‘gradient가 음수이면 -1곱하는게 더 커지는게 아니에요?’하고 물어보니 흠칫한적이 있었다. 왜 gradient의 반대 방향으로 가는게 &lt;strong&gt;‘언제나’&lt;/strong&gt; minimize의 방향인걸까? 사실 위의 질문은, ‘gradient의 뱡향’과 ‘gradient방향으로 갔을때 cost function의 변화’에 대해 혼동된 질문이다.&lt;/p&gt;

&lt;p&gt;우리의 목적은 &lt;strong&gt;cost function이 얼마나 움직이는 가&lt;/strong&gt;이다. 특정 gradient에 대해서, 우리가 어떻게 움직이던 업데이트는 &lt;strong&gt;‘움직인 방향’  x ‘gradient ‘&lt;/strong&gt;가 될것이다(현재 주어진 정보인 gradient가 유지된다는 가정에서. 즉 taylor expension). 즉,   gradient가 음수일 경우 gradient방향으로 가는 $(x+\Delta x)​$는 ‘&lt;strong&gt;그negative방향&lt;/strong&gt;‘으로 ‘&lt;strong&gt;negative만큼&lt;/strong&gt;‘간다는 의미가 되버린다. 즉, &lt;strong&gt;gradient방향&lt;/strong&gt;으로 갈 경우 &lt;strong&gt;언제나 cost function은 최대화 된다&lt;/strong&gt;. 다음의 예시에서 조금 더 설명한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/44249345-f466f580-a1de-11e8-9c87-bb582806a71d.PNG&quot; alt=&quot;x_square&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위와 같이 $y=x^2$이라는 함수가 있다고 해보자. gradient는 언제나 $2*x$일 것이다. 만약 데이터 x가 -2였어서 gradient가 -4였다면, 해당 점(즉, -2)에서 gradient만큼 -4를 움직이는 것은 언제나 해당 함수를 증가시킨다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;x-4이때 $\Delta x$는 -4, 근데 이때 또 기울기는 -4니가 사실상 업데이트량은 -4*-4즉 &lt;strong&gt;언제나 제곱텀&lt;/strong&gt;. 즉 &lt;strong&gt;절대 음수될수 없다&lt;/strong&gt;. 즉 언제나 gradient만큼 빼주는게 minimize해주는 방향이다.&lt;/p&gt;

  &lt;p&gt;다시 정리하자.&lt;/p&gt;

  &lt;p&gt;x+1,x 둘의 delta는 1, 이때의 변화는 1*gradient_x이지만,&lt;/p&gt;

  &lt;p&gt;x+gradient_x까지 간다면 이때의 &lt;strong&gt;delta&lt;/strong&gt;는 &lt;strong&gt;gradient_x&lt;/strong&gt;*gradient_x. 즉, 제곱항. 항상 양수일수밖에 없다.(x=&lt;script type=&quot;math/tex&quot;&gt;\Delta x&lt;/script&gt;의 delta는 &lt;script type=&quot;math/tex&quot;&gt;\Delta x&lt;/script&gt;X&lt;script type=&quot;math/tex&quot;&gt;\Delta x&lt;/script&gt;) 고로 x+gradient_x는 언제나 maximize하는 방향, x-gradient_x는 언제나 minimize.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;밑바닥부터 구현하기인 만큼, $\sum x^2$의 편미분값 $2x$를 손으로 입력해주지 말고 이전에 정의하였던 estimate_gradient함수를 통해서 찾아보자. (즉, $\frac{f(x+h)-f(h)}{h}$를 통해 &lt;strong&gt;미분에 근사한&lt;/strong&gt; 식을 직접 구하는것!)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;777&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#아무 숫자 v
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#gradient의 결과값은 이렇게 2*v로 나와야 할것이다!
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[0, 1554, 3108, 4662, 6216, 7770, 9324, 10878, 12432, 13986] 확인을 위해 아무 숫자를 가진 list(v)를  loss func$\sum x^2$에 넣어보자. 결과값은 위에 명시된 2*v가 나와야 한다.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;estimate_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;# x^2의 합이니까 gradient는 2x들 맞다
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[0.0,
 1554.0000796318054,
 3108.000159263611,
 4661.999940872192,
 6216.000020503998,
 7770.000100135803,
 9324.000179767609,
 10878.000259399414,
 12432.000041007996,
 13986.000120639801]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;그럼 이제, 앞에꺼를 이어붙인 최종 완성본을 만들어보자, 이때 step은 어떻게 정하나? 다양한 방법이 있는데(e.g. 특정 step size로 고정한다, 몇번의 iter가 끝나면 점점 step size를 줄인다, 각 iter마다 다양한 step의 계산해서 가장 최적의 변화를 일으키는 step size를 택한다), 여기서는 각iter마다 여러번 step시도해보고 최적으로 간다.&lt;/p&gt;

&lt;p&gt;이번에는 역시  loss func$\sum x^2$을 최적화할것이다. 우리는 이미 답이 $(0,0,..,0)$이 나와야 함을 알고 있다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;minimize_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.000001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;use gradient descent to find theta that minimizes target function&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;step_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.00001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# set theta to initial value
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;#target_fn = safe(target_fn) # safe version of target_fn
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# value we're minimizing
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;cnt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cnt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;next_thetas&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step_size&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# choose the one that minimizes the error function
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;next_theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_thetas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#추정값중 가장 minimum
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cnt&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;            
            &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'this is next theta'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;next_value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# stop if we're &quot;converging&quot;
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_value&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;%%&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;my_theta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;77&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;my_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;' this is first theta'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;finished_theta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;minimize_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;estimate_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;u&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;my_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tolerance&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.000001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#람다항에서 u는 my_theta를 받는다
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[0, 77, 154, 231, 308]  this is first theta
[-4.9423384496094513e-05, 0.887700135395562, 1.7754496933229689, 2.6631992519609184, 3.5509488109186123] this is next theta
[-4.999335213775463e-05, 0.010185062218061793, 0.020420117778473162, 0.03065517334706549, 0.04089022891927558] this is next theta
[-4.999981287931518e-05, 0.00023809138994608964, 0.0005261825924960112, 0.0008142737952761995, 0.0011023649981581664]  this is finished theta
Wall time: 3.99 ms
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;역시나 0에 매우 가까운 값을 갖게 됨을 알 수 있다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 지금 위에서 한것들은 summation 이 없는, 하나의 데이터에 대해서 한것이지만 원래는 mse같이 sum(error)로 해야한다.
# 즉 위의 예시의 경우 loss func는 단순히 [i*i for ]가 아니라 sum([i*i for] for range(len(data)))와 같은 형태로 되고
# 그에 맞춰 estimated gradient는 2*(sum(x))등으로 나와야 한다.
# 모든 데이터에 대해 loss func을 때리고 모든 데이터 기준으로 gradient를 구하고
#(이 경우, 혹은 많은 경우 loss func이 각 데이터에 대한 error의 sum이라 gradient도 각각의 sum으로 하게 된다)
# 최적화를 한다. 단순 sum인경우, 몇개(혹은 한개의 subset)의 데이터에 대해서만 구하는 sgd를 반복하는게 더 효율적인 경우가 많다
# (더 robust해지기도한다)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;3-stochastic-gradient-descent&quot;&gt;3. Stochastic Gradient Descent&lt;/h1&gt;

&lt;p&gt;지금까지 편의를 위해 $\sum_i^n x_i^2$과 같이 x들을 직접 설정해주었지만, 실제로 SSE등을 구할때는 $\sum_i^n(y_i-\hat{ y_i})^2$와 같이, 데이터에 대해서 직접 $(y_i-\hat{ y_i})^2$를구한후, 이들 모든 데이터에 대해 반복하고 평균을 내줘야 최종 cost function을 구할 수 있다 .&lt;/p&gt;

&lt;p&gt;그러나, 만약 데이터가 1억개였다면, 이를 매 iteration마다 반복하는 것이 매우 버거운 일일 수 있다.&lt;/p&gt;

&lt;p&gt;그런데 cost function은, 사실 각각의 데이터에 대해 loss function을 구하고 이를 평균 취하여 구하는 것이다. 그렇다면, 어차피 선형 연산으로 +를 해주는 것이라면, 몇개의 데이터만 뽑아서 loss function을 구하고 update하는 것을 계속 반복하면 결국 전체 데이터에 대해서 update를 해주는것과 차이가 없지 않을까?&lt;/p&gt;

&lt;p&gt;이러한 관점에서 등장한것이 stochastic gradient descent이다. 전체 데이터에 대해 평균을 내는 것이나, ramdom sampling 된 데이터에 대해 평균을 내는것이나, 확률적으로 그 &lt;strong&gt;기댓값&lt;/strong&gt;은 같다는 이론에 기반을 둔 것이다. ($E(\frac{total_data}{n_t})=E(\frac{sampled_data}{n_s})$)&lt;/p&gt;

&lt;p&gt;또한, 전체의 데이터에 대해서 적합을 하면 특정 local minima에 빠질 경우 절대 빠져나올 수가 없지만, 몇몇 샘플링 된 데이터에 대해서는 해당 local minima를 빠져나올 확률이 좀더 생긴다는 점에서도, local minima에 대해서 좀더 robust한 특성을 갖게되어 최적화방식에서 gradient descent를 대부분 대체하여 사용되는 방법이다.&lt;/p&gt;

&lt;p&gt;딥러닝에서의 SGD는 보통 mini batch에 대해 업데이트를 하는 것을 의미하지만, 이때 sampling은 mini_batch를 뽑아서 하던, 임의의 10개를 뽑아서 하던, 1개를 뽑아서 하던 random sampling만을 만족시킨다면 모두 SGD의 범주에 포함된다고 할 수 있다. 여기에서는 random sampling된 1개의 데이터에 대해서만 gradient를 구한다.&lt;/p&gt;

&lt;p&gt;이번에는 실제 데이터 전체에 대해 적합하는 만큼, improvement가 없더라도 100번의 iter를 더 돌면서 update를 해보고, 100연속 improvement가 없다면 멈추는 구문을 추가하였다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;#여기서는 loss function에 y까지 필요하다
#위에서는 이미 '편차'의 제곱과 같이 input하나로 loss구햇으면 지금은 x,y둘다 넣어줘서 구하는형식!
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;minimize_stochastic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;safe&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    

    &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_0&lt;/span&gt;                             &lt;span class=&quot;c1&quot;&gt;# initial guess
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_0&lt;/span&gt;                             &lt;span class=&quot;c1&quot;&gt;# initial step size
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;min_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;inf&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# the minimum so far
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# if we ever go 100 iterations with no improvement, stop
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;amp;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;safe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'too much iter!'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# if we've found a new minimum, remember it
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# and go back to the original step size
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;min_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cnt_for_inf_loop&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'min_theta updates'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha_0&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# otherwise we're not improving, so try shrinking the step size
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;  &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;iterations_with_no_improvement is growing...&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iterations_with_no_improvement&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;# and take a gradient step for each of the data points        
&lt;/span&gt;        &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;for x_i, y_i in in_random_order(data):
            gradient_i = gradient_fn(x_i, y_i, theta)
            theta = vector_subtract(theta, scalar_multiply(alpha, gradient_i))&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;indexes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))];&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indexes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rand_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indexes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;gradient_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rand_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rand_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vector_subtract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scalar_multiply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_theta&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vector_subtract&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;subtracts corresponding elements&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scalar_multiply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;c is a number, v is a vector&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h1 id=&quot;4-gradient-descent로-linear-regression적합하기&quot;&gt;4. Gradient Descent로 Linear regression적합하기&lt;/h1&gt;

&lt;p&gt;이제 드디어, 모든 도구를 다 갖추었다. 맨 앞에서 했던 단순히 cov/var로써 적합하는 게 아닌, 데이터에 대해서 gradient를 구해서 최적해를 찾아보자.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;squared_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;squared_error_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;# alpha partial derivative
&lt;/span&gt;            &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# beta partial derivative
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;$(y_i-(\beta*x_1+\alpha))^2$가 목적함수니까 편미분은 각각&lt;/p&gt;

&lt;p&gt;$\frac{\partial f}{\partial \alpha}=-2(\beta*x_1+\alpha)$&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{\partial f}{\partial \beta}=-2*x_1(\beta*x_1+\alpha)&lt;/script&gt;이 될것이다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;%%&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minimize_stochastic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;squared_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                  &lt;span class=&quot;n&quot;&gt;squared_error_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                  &lt;span class=&quot;n&quot;&gt;num_friends_good&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                  &lt;span class=&quot;n&quot;&gt;daily_minutes_good&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                  &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                  &lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Final parameter :'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;min_theta updates [0.8444218515250481, 0.7579544029403025]
min_theta updates [12.287728757179368, 1.6212965611920966]
min_theta updates [15.560144551056357, 1.415040172643511]
min_theta updates [17.822358779447857, 1.3909027828252298]
min_theta updates [19.340607552944455, 1.1994438991099778]
min_theta updates [20.387544972589787, 1.1035908826138416]
min_theta updates [21.61801889250819, 1.001274091679216]
min_theta updates [22.00488567039699, 0.9843192992048934]
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 25
iterations_with_no_improvement is growing... 45
iterations_with_no_improvement is growing... 65
iterations_with_no_improvement is growing... 85
Final parameter : 22.93746417548679 0.9043371597664965
Wall time: 546 ms
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;실제 정답값인 (22.95,0.903)에 매우 근접한 값을 찾을 수 있었다.&lt;/p&gt;

&lt;p&gt;또한, loss function 기준 변수가 2개(알파와 베타), 즉 다변량이니까 위에서 짯던 partial gradient를 사용해볼수 있다.&lt;/p&gt;

&lt;p&gt;예를 들어, parameter가 각각 $\alpha=3, \beta=2$이었을때 데이터 $(x,y)=(6,18)$에 대해서 어떤 gradient를 갖는지 보자.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'This is one with real derivative:'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;squared_error_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;#3*-2랑 3*-2*6
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'This is one with sudo derivative:'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;estimate_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coeff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;squared_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coeff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;This is one with real derivative: [-6, -36]
This is one with sudo derivative: [-5.9998999999777425, -35.99640000013338]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;오예.&lt;/p&gt;

&lt;p&gt;따라서 마지막으로 이미 미분되어있는 식 말고, 이전에 짯던 partial derivative를 이용하여 gradient까지 직접 구하여 SGD를 해보자.&lt;/p&gt;

&lt;p&gt;이를 위해 특정 데이터 x_i,y_i를 받았을때 현재 coeff를 가지고 loss function인 squared_error에 대해서 gradient를 구할 수 있는 my_ols를 함수를 짜서 적합해본다. 물론, 조금 더 느릴수 있다.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;my_ols&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coeff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;#print((x_i,y_i,coeff))
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;estimate_gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;coeff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;squared_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coeff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;coeff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;o&quot;&gt;%%&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;time&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;minimize_stochastic&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;squared_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                  &lt;span class=&quot;n&quot;&gt;my_ols&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                  &lt;span class=&quot;n&quot;&gt;num_friends_good&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                  &lt;span class=&quot;n&quot;&gt;daily_minutes_good&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                  &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                  &lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;safe&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'Final parameter :'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;min_theta updates [0.8444218515250481, 0.7579544029403025]
min_theta updates [12.28805514597721, 1.6212228195868175]
min_theta updates [15.560565522578992, 1.414956622720906]
min_theta updates [17.822844346718213, 1.3908099012563253]
min_theta updates [19.341138465457096, 1.199346739728466]
min_theta updates [20.38810706840187, 1.1034939193107496]
min_theta updates [21.618617382498233, 1.0011793142052967]
min_theta updates [22.005494362904244, 0.9842221133970033]
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
min_theta updates [22.862947253725665, 0.9141561880824236]
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 5
iterations_with_no_improvement is growing... 25
iterations_with_no_improvement is growing... 45
iterations_with_no_improvement is growing... 65
iterations_with_no_improvement is growing... 85
Final parameter : 22.94909060432333 0.9041386511875767
Wall time: 1.24 s
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;짠. 이번에도 역시 실제 정답값인 (22.95,0.903)에 매우 근접한 값을 찾을 수 있었다!&lt;/p&gt;

&lt;hr /&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;random&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;nn&quot;&gt;functools&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;partial&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;correlation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stdev_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stdev_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdev_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdev_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cov&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdev_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stdev_y&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;# if no variation, correlation is zero
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;covariance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;standard_deviation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;variance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;    

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;variance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;assumes x has at least two elements&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;deviations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sum_of_squares&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deviations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;de_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;translate x by subtracting its mean (so the result has mean 0)&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_bar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_bar&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum_of_squares&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;s&quot;&gt;&quot;&quot;&quot;computes the sum of squared elements in v&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</description>
        <pubDate>Wed, 01 Aug 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/08/01/Scratch-Linear-regression-&-Gradient-descent.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/08/01/Scratch-Linear-regression-&-Gradient-descent.html</guid>
        
        <category>machine learning</category>
        
        <category>python implementation</category>
        
        <category>DataScience from Scratch</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[NLP] Memory Networks 논문 리뷰</title>
        <description>
&lt;p&gt;Memory Networks 논문 리뷰&lt;/p&gt;

&lt;p&gt;논문 : https://arxiv.org/abs/1410.3916  (2014)&lt;/p&gt;

&lt;h2 id=&quot;abstract&quot;&gt;Abstract&lt;/h2&gt;

&lt;p&gt;새로운 학습방식인 memory network를 제시한다. memory network는 long-term memory요소와 inference 요소(뭘까…QA에서는 질문인듯. 어떤 task에서 추론을 위한 요소인듯. 질문이면 input도 아니니까, 이를 inference component라고 표현하는 듯 하다.)를 통해 reason(판단)을 한다. long-term memory가 효과적으로 작동하는 Question answering task에 적용하였다.&lt;/p&gt;

&lt;p&gt;굉장히 범용적인 개념인데다 여러가지 적용을 해본거라, 설명도 범용적이다..&lt;/p&gt;

&lt;h2 id=&quot;1-introduction&quot;&gt;1. Introduction&lt;/h2&gt;

&lt;p&gt;대부분의 모델들은, 특히 input이 매우 길어질때 long-term memory component를 잡아내고 이를 inference와 매끄럽게 결합하는것을 잘 못한다.  예를 들어, 하나의 story를 듣고 question에 답하는 경우를 생각해보자. 이론상으로 RNN과 같이 이전의 흐름들을 읽고 다음 word를 예측하는 모델들이 이를 해낼 수 있다. 그러나 하나의 hidden state와 weight로 이루어진 그들의 memory능력은 매우 작다. 과거의 내용들이 fixed vector로 압축되어 표현되어야 하기에, 결국 과거의 정보를 제대로 구분해내지 못한다. 이에 따라 RNN은 들어온 input seq를 그대로 내뱉는 간단한 task에서 약점을 보인다.(!) 이는 text뿐아니라 audio등 log term memory가 필요한 어느곳에서도 동일하다.&lt;/p&gt;

&lt;p&gt;우리는 이러한 문제를 해결할 수 있는 memory network를 제시한다. 주요 아이디어는 기존의 머신러닝 방법으로 구해진 inference에 읽고 쓰여질 수 있는 memory component를 결합하는 것이다. 이를 어떻게 잘 결합할 수 있는지를 학습한다. 섹션2에서 구체적인 frame work를 제시하고 센션3에서 QA task에 대해 실행해본 결과를 제시할 것이다.&lt;/p&gt;

&lt;h2 id=&quot;2-memory-networks&quot;&gt;2. Memory Networks&lt;/h2&gt;

&lt;p&gt;메모리 네트워크는 &lt;script type=&quot;math/tex&quot;&gt;m_i&lt;/script&gt;로 index가 되어있는 ‘메모리&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol m&lt;/script&gt;‘과, 학습되는 4개의 요소 ‘&lt;script type=&quot;math/tex&quot;&gt;I,G,O,R&lt;/script&gt;‘로 이루어진다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;I&lt;/script&gt; : input feature map. input을 feature representation으로 바꿔준다&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;G&lt;/script&gt; : generalization. 새로운 input이 들어오면 이를 토대로 이전 memory를 update해준다.&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;O&lt;/script&gt; : output feature map. 새로운 input과 현재의 memory를 토대로 새로운 output(feature representation)을 만든다&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;R&lt;/script&gt; : response. output(feature representation)을 원하는 형태로 변환시킨 뒤 response를 한다.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;구체적으로, input &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;가 들어왔을때 모델의 작동방식은 다음과 같다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;를 feature representation &lt;script type=&quot;math/tex&quot;&gt;I(x)&lt;/script&gt;로 바꾼다&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;해당 input을 토대로 memory를 update한다. &lt;script type=&quot;math/tex&quot;&gt;m_i=G(m_i,I(x),\boldsymbol m), \forall i&lt;/script&gt;&lt;/p&gt;

    &lt;blockquote&gt;
      &lt;p&gt;(메모리와 메모리의 update방식은 말그대로 아무거나 가능하다. i번째 인풋을 i번째 메모리에만 넣어줄 수도 있고, i번째 메모리는 이전0~i까지의 input을 반영할수도 있고(이경우 attention을 활용한 RNN의 느낌적인 느낌), 혹은 input이 모든 slot의 메모리에 영향을 줄수도 있을 것이다.)&lt;/p&gt;
    &lt;/blockquote&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;새로운 input(&lt;script type=&quot;math/tex&quot;&gt;I(x)&lt;/script&gt;)와 메모리(&lt;script type=&quot;math/tex&quot;&gt;m&lt;/script&gt;)를 토대로 output feature &lt;script type=&quot;math/tex&quot;&gt;o&lt;/script&gt;를 계산한다.  &lt;script type=&quot;math/tex&quot;&gt;o=O(I(x),\boldsymbol m)&lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;output feature &lt;script type=&quot;math/tex&quot;&gt;o&lt;/script&gt;를 response로 디코딩한다. &lt;script type=&quot;math/tex&quot;&gt;r=R(o)&lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;물론 test 과정에서는 memory는 저장되지만 I,G,O,R은 update되지 않고 유지된다. 이때 I,G,O,R은 머신 러닝에서 이미 존재하는 어떤것도 사용가능하다. (SVM, Decision tree, etc)&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;I&lt;/script&gt; component : I는 parsing, entity resolution(&lt;a href=&quot;http://www.datacommunitydc.org/blog/2013/08/entity-resolution-for-big-data&quot;&gt;참고&lt;/a&gt;)과 같은 기존의 pre-processing과정일 수도 있고, input을 internal feature representationd로 인코딩하는과정 역시 사용될 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;G&lt;/script&gt; component :  G의 가장 간단한 form은 &lt;script type=&quot;math/tex&quot;&gt;I(x)&lt;/script&gt;를 메모리의 한 슬롯에 저장하는 것이다. 
&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol m_{H(x)}=I(x)&lt;/script&gt;
여기서 H(.)는 슬롯의 한부분을 지칭하는 func을 의미한다. 즉 (가장 간단한)G는 &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol m&lt;/script&gt;의 H(x)부분만을 업데이트해주고 나머지 memory는 건들지 않는 함수이다. 더욱 복잡한 G는 새로운 input x에 기반하여 이전메모리(혹은 전체 이전메모리)를 업데이트해줄 것이다. 만약 input이 character나 word level이라면 이들을 group해서 memory slot에 넣어줄 수 있을 것이다 .&lt;/p&gt;

&lt;p&gt;만약 memory가 매우 거대, 즉 wikipedia같이 거대한 input이 들어온다면, 메모리를 organize할 필요가 있는데, 이역시 indexing 을 해주는 H(.)으로써 해결할 수 있다. 예를 들어 entity에 따라서 같은 slot으로 취급하도록 design(혹은 그런방식으로 train)하는 것이다. 결과적으로 scale에 대해서 효율적이려면 G(그리고 뒤의 O도) 가 모든 memory를 대상으로 하는 것이 아니라 선정된 subset, 즉 유의미한 topic의 memory에 대해서만 작동해야 한다. 뒤의 실험에서 이를 다룬다&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;O,R&lt;/script&gt; component : O component는 memory를 읽고 어떤 memory가 관련되어있는지를 계산한다. R component는 이를 통해 나온 O를 토대로 최종 response를 한다 R은 output O에 대한 RNN decoder일 수 있다. 우리의 가정은 ‘memory에 대한 선택이 없다면 이 RNN의 성능이 좋지 못할 것이다’이다.&lt;/p&gt;

&lt;h2 id=&quot;3-a-memnn-implementation-for-text&quot;&gt;3 A MemNN Implementation for Text&lt;/h2&gt;

&lt;p&gt;메모리 network를 neural network에 적용했다해서 MemNN. text로 된 input, output을 가지고 간단한 implementation을 해보았다.&lt;/p&gt;

&lt;h3 id=&quot;31-bacis-model&quot;&gt;3.1 Bacis Model&lt;/h3&gt;

&lt;p&gt;I가 input을 받아 embedding을 한다. 이 input이 fact를 나타내는 문장과 질문을 하는 문장이라 해보자.(뒤에 input이 word-based sequence인것도 다룬다). 가장 간단한 G를 생각해보면, 임베딩된 text가 다음 메모리 슬롯에 저장될 것이다. 즉 새로운 메모리 슬롯만을 업데이트하고 이전 메모리는 건들지 않는것이다. 좀더 복잡한 방식의 G는 다음 섹션에서 다룬다.&lt;/p&gt;

&lt;p&gt;inference의 핵심은 O,R에 있는데, O는 input x에 대해 유의미한 k개의 메모리를 선정하여 output feature을 만든다. 우리는 k를 2로 선정하였다. 즉 여러 문장과 질문이 input으로 들어온다면, 그 질문에 도움될만한 2개의 메모리, 여기서는 한문장-&amp;gt;한 메모리 슬롯이니 2개의 문장을 고르는 것이다.&lt;/p&gt;

&lt;p&gt;k=1일때, 가장 관련잇는 memory(supporting memory라 표현한다) &lt;script type=&quot;math/tex&quot;&gt;o_1&lt;/script&gt;은 다음과 같이 정의할 수 있다.
&lt;script type=&quot;math/tex&quot;&gt;o_1=O_1(x,\boldsymbol m)=argmax s_O(x,m_i), \forall i&lt;/script&gt;
이때 &lt;script type=&quot;math/tex&quot;&gt;s_O&lt;/script&gt;는 input sentence(여기서는 예시가 문장이었으니)x와 &lt;script type=&quot;math/tex&quot;&gt;m_i&lt;/script&gt; 쌍의 match를 점수매기는 함수이다. 어떻게 이를 계산하는지는 조금 뒤에 설명한다.&lt;/p&gt;

&lt;p&gt;k=2일 경우, 2번째 관련있는 memory &lt;script type=&quot;math/tex&quot;&gt;o_2&lt;/script&gt;는 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;o_2=O_2(x,\boldsymbol m)=argmax s_O([x,m_{o_1}],m_i), \forall i&lt;/script&gt;
즉 다음 관련잇는 memory는 이전 메모리들과 input과의 &lt;strong&gt;list&lt;/strong&gt;와의 match로써 평가한다.(bag-of-word model을 사용했다. 즉, 단순히 &lt;script type=&quot;math/tex&quot;&gt;s_O(x,m_i)+s_O(m_{o_1},m_i)&lt;/script&gt;을 최대화 하는 값을 찾는것과 같다. 다른 형태로 고려할수도 있을 것이라고만 언급햇다..) 이 경우 &lt;script type=&quot;math/tex&quot;&gt;R&lt;/script&gt;로 들어가는 최종 output은 &lt;script type=&quot;math/tex&quot;&gt;[x,m_{o_1},m_{o_2}]&lt;/script&gt;이다.&lt;/p&gt;

&lt;p&gt;이를 통해 최종 &lt;script type=&quot;math/tex&quot;&gt;R&lt;/script&gt;이 response를 만든다. 이때 RNN을 사용할 수 있을 것이다. 또한, single word으로 response가 제한되는 경우(예를 들어 Q:사과는 어딧어? A:부엌.)에 대해서 &lt;script type=&quot;math/tex&quot;&gt;[x,m_{o_1},m_{o_2}]&lt;/script&gt;의 조합을 평가하기 위해서 다음과 같은 &lt;strong&gt;rank&lt;/strong&gt;를 사용할 수 있을 것이다.
&lt;script type=&quot;math/tex&quot;&gt;r=argmax_{w\in W}s_R([x,m_{o_1},m_{o_2}],w)&lt;/script&gt;
&lt;script type=&quot;math/tex&quot;&gt;W&lt;/script&gt;는 dictionary에 있는 모든 단어이고, &lt;script type=&quot;math/tex&quot;&gt;s_R&lt;/script&gt;은 match를 점수매기는 함수이다. 결국 앞에 했던 &lt;script type=&quot;math/tex&quot;&gt;S_O&lt;/script&gt;와 비슷하게, dic에 있는 모든 단어 중 list &lt;script type=&quot;math/tex&quot;&gt;[x,m_{o_1},m_{o_2}]&lt;/script&gt;에 가장 적절하게 매칭될만한 단어를 찾는 것이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/37249968-efdb67b6-24e9-11e8-8356-14786fabebfb.PNG&quot; alt=&quot;memory1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;다음은 예제질문이다. input question &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;=’Where is the milk now?’였을때 &lt;script type=&quot;math/tex&quot;&gt;O&lt;/script&gt;는 이에 대해 모든 memory를 점수매긴다. 이 경우 input이 sentence였으니, 지금까지 들어온 sentence들과 input &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;와 가장 관련있는 메모리를 &lt;script type=&quot;math/tex&quot;&gt;m_{o_1}&lt;/script&gt;으로써 내보낼 것이다. (ex &lt;script type=&quot;math/tex&quot;&gt;m_{o_1}&lt;/script&gt;=’Joe left the milk’) 그리고 &lt;script type=&quot;math/tex&quot;&gt;[x,m_{o_1}]&lt;/script&gt; 에 대해 가장 관련있는 &lt;script type=&quot;math/tex&quot;&gt;m_{o_2}&lt;/script&gt;를 찾을 것이다. 예를들어 &lt;script type=&quot;math/tex&quot;&gt;m_{o_2}&lt;/script&gt;=’Joe travelled to the office’(우유를 방치하기 전 가장 최근에 간 장소) 따라서 &lt;script type=&quot;math/tex&quot;&gt;R&lt;/script&gt;은 &lt;script type=&quot;math/tex&quot;&gt;s_R([x,m_{o_1},m_{o_2}],w)&lt;/script&gt;에 따라 ‘office’를 출력할 것이다.&lt;/p&gt;

&lt;p&gt;그럼 적절한 match를 평가하는 적절성 평가함수 &lt;script type=&quot;math/tex&quot;&gt;s_O,s_R&lt;/script&gt;은 어케 정의하느냐, 우리는 두 함수에 대해 다음과 같이 동일한 정의를 사용하였다
&lt;script type=&quot;math/tex&quot;&gt;s(x,y)=\Phi_x(x)^TU^TU\Phi_y(y)&lt;/script&gt;
이때 &lt;script type=&quot;math/tex&quot;&gt;U&lt;/script&gt;는 n X D의 embedding matrix이다. n은 임베딩 dimension, D는 feature의 수를 의미한다. &lt;script type=&quot;math/tex&quot;&gt;\Phi_x,\Phi_y&lt;/script&gt;는 D차원 feature space로 매핑된 text의 embedding feature representation이다. 가장 간단한 매핑은 bag of words이다. 이 경우 &lt;script type=&quot;math/tex&quot;&gt;D=\lvert W\lvert&lt;/script&gt;. 우리는 dictionary내의 모든 word가 3개의 representation을 갖는다는 의미에서 &lt;script type=&quot;math/tex&quot;&gt;D=3\lvert W\lvert&lt;/script&gt;를 사용하였다. (&lt;script type=&quot;math/tex&quot;&gt;W&lt;/script&gt;는 dictionary에 있는 모든 단어)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;결국 x와 y의 내적인데…내적으로 유사도를 구하는것과 비슷한 개념으로 이해하였다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;training&quot;&gt;Training&lt;/h4&gt;

&lt;p&gt;train은 fully supervised방식으로 하였다. 즉, input에 대한 desired reponse가 있고, 그 input에 대한 관련있는 &lt;strong&gt;메모리sentence역시 라벨링&lt;/strong&gt; 되어있다. 즉, 다음의 최적값을 알고있다&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;o_1=O_1(x,\boldsymbol m)=argmax s_O(x,m_i), \forall i&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;o_2=O_2(x,\boldsymbol m)=argmax s_O([x,m_{o_1}],m_i), \forall i&lt;/script&gt;

&lt;p&gt;training은 &lt;strong&gt;margin ranking loss&lt;/strong&gt;와 SGD를 통해 이루어 진다. 즉 &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;와 그에 대한 true response &lt;script type=&quot;math/tex&quot;&gt;r&lt;/script&gt;, supporting sentence &lt;script type=&quot;math/tex&quot;&gt;m_{o_1},m_{o_2}&lt;/script&gt;를 알고 있을때 Loss func은 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/37249975-f173b60a-24e9-11e8-90ed-59a47cae8675.PNG&quot; alt=&quot;memory2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이때 &lt;script type=&quot;math/tex&quot;&gt;\bar f,\bar {f'}, \bar r&lt;/script&gt;은 모두 잘못된 답이다. 즉, 실제답과의 차이가 각각 모두&lt;script type=&quot;math/tex&quot;&gt;\gamma&lt;/script&gt;이상 만큼 나는것을 목표로 하는 것이다. 실제 답에 대한 score를 더 키우고자 학습하려 할 것이다. 이를 최소화하도록 GD를 사용하여 &lt;script type=&quot;math/tex&quot;&gt;s_O&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;s_R&lt;/script&gt;의 parameter  &lt;script type=&quot;math/tex&quot;&gt;U_O,U_R&lt;/script&gt;을 조정한다. SGD를 사용하여 모든 traing set에 대해 &lt;script type=&quot;math/tex&quot;&gt;\bar f,\bar {f'}, \bar r&lt;/script&gt;를 계산한게 아니라 sample로써 &lt;script type=&quot;math/tex&quot;&gt;\bar f,\bar {f'}, \bar r&lt;/script&gt;를 계산했다.&lt;/p&gt;

&lt;p&gt;또한 RNN을 사용한 &lt;script type=&quot;math/tex&quot;&gt;R&lt;/script&gt;단계에서는 언어모델에서 자주 사용하는 log likelihood을 사용하였다. (가운데 잘 이해 안되는 부분이 있는데, 전문을 옮긴다 we replace the last term with the standard log likelihood used in a language modeling task, where the RNN is fed the sequence [x, o1, o2, r].) test단계에서는, [x,o_1,o_2]이 주어졌을때 max likelihood인 r을 반환한다.&lt;/p&gt;

&lt;p&gt;다음의 섹션에서 좀더 확장된 모델을 다룬다.&lt;/p&gt;

&lt;h3 id=&quot;32-word-sequence-as-input&quot;&gt;3.2 Word Sequence as Input&lt;/h3&gt;

&lt;p&gt;input이 sentence level이 아닌 word level이고, fact statement와 question이라는 segmentation이 되지 않은 경우를 생각해보자. 즉 QA에선, 누가 사실에 대한 ‘설명’인지, 누가 ‘질문’인지도 모르는 경우다.이 경우 segmentation function을 추가로 학습시켜야 한다. 즉 segmented되지 않은 word들의 seq들의 끝을 계속 input으로 받아 break point를 찾아내는 함수이다. segmentation이 발생하여 지금까지의 seq가 segment라는 신호가 오면 이 seq를 memory에 저장한다. segmentatoin func는 다음의 형식을 취한다
&lt;script type=&quot;math/tex&quot;&gt;seg(c)=W^T_{seg}U_S\Phi_{seg}(c)&lt;/script&gt;
&lt;script type=&quot;math/tex&quot;&gt;U_S\Phi_{seg}(c)&lt;/script&gt;는 이전에 나왔던 형태로, feature map과 embedding matrix이다 . &lt;script type=&quot;math/tex&quot;&gt;W_{seg}&lt;/script&gt;는 embedding space를 classify할 수 있는 vector이고, &lt;script type=&quot;math/tex&quot;&gt;c&lt;/script&gt;는 bag of word로 표현된 seq of input words이다. 저 classifier를 어떻게 학습햇는지는, 다음과 같다.&lt;/p&gt;

&lt;p&gt;fully supervised setting이기에, 역시나 supervised 학습을 할 수 있다. 예를 들어 ‘Where is Bill?’이라는 Q에 대해 ‘Bill is in the Kitchen’이 supporting seq라는 것을 아니까, 해당 seq에서 fire를 하는 것이다.(‘Bill is in’ 같이 unfinished문장에서 fire를 안하고)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/37249969-f015c78a-24e9-11e8-92bf-c8ba17a3e766.PNG&quot; alt=&quot;memory8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;모든 supporting segment(&lt;script type=&quot;math/tex&quot;&gt;f&lt;/script&gt;)에 대해선 &lt;script type=&quot;math/tex&quot;&gt;\gamma&lt;/script&gt; 이상의 확신을 하고, unsupporting(&lt;script type=&quot;math/tex&quot;&gt;\bar f&lt;/script&gt;)에 대해선 &lt;script type=&quot;math/tex&quot;&gt;-\gamma&lt;/script&gt;이하를 반환해야 하는 loss func이다.&lt;/p&gt;

&lt;p&gt;만약 특정 margin &lt;script type=&quot;math/tex&quot;&gt;\gamma&lt;/script&gt;에 대해 &lt;script type=&quot;math/tex&quot;&gt;seg(c)&gt;\gamma&lt;/script&gt;라면 이seq &lt;script type=&quot;math/tex&quot;&gt;c&lt;/script&gt;를 segment로 간주한다.&lt;/p&gt;

&lt;p&gt;이후의 과정은 같다.&lt;/p&gt;

&lt;h2 id=&quot;33-efficient-memory-via-hashing&quot;&gt;3.3 Efficient Memory via Hashing&lt;/h2&gt;

&lt;p&gt;만약 메모리가 매우 크다면 &lt;script type=&quot;math/tex&quot;&gt;o_1=O_1(x,\boldsymbol m)=argmax s_O(x,m_i), \forall i&lt;/script&gt;와 같은 형태로 메모리를 선택하는 것이 expensive할 것이다. 따라서 우리는 lookup과정에서 hassing trick(&lt;a href=&quot;https://en.wikipedia.org/wiki/Hash_table#Collision_resolution&quot;&gt;참고&lt;/a&gt;)를 사용할 것이다. input &lt;script type=&quot;math/tex&quot;&gt;I(x)&lt;/script&gt;를 하나 혹은 여러개의 bucket에 hashing을 한다. 그 후 same bucket에 있는 메모리 &lt;script type=&quot;math/tex&quot;&gt;m_i&lt;/script&gt;에 대해서만 score를 매긴다. hasing은 다음 2가지 방법으로 한다. 1) hashing word, 2) clustering word embedding. 1번의 경우, word dictionary만큼의 bucket을 만든다. 그리고 input sentence를 그것과 관련있는 word의 bucket에 hashing한다. 그러나 1번의 문제는 &lt;script type=&quot;math/tex&quot;&gt;I(x)&lt;/script&gt;에 한번이라도 등장을 해야 해당 메모리가 고려될 것, 즉 매우 sparse하다는 것이다. 2번은 이를 클러스터링으로써 보완해준다. 임베딩 메트릭스 &lt;script type=&quot;math/tex&quot;&gt;U_O&lt;/script&gt;를 학습시키고 난 후, 워드벡터&lt;script type=&quot;math/tex&quot;&gt;(U_O)_i&lt;/script&gt;들을 K-means 클러스터링 해준다. 즉, K개의 bucket으로 분류한다. 그리곤 given sentence가 해당 bucket의 word를 포함하고 있는 경우 각 bucket에 hash한다. 비슷한 단어의 word vector는 함께 클러스터링  될것이므로 memory도 함께 처리할 수 있다. 이때 K를 정하는 것은 speed-accuracy trade-off의 문제이다&lt;/p&gt;

&lt;h2 id=&quot;34-modeling-write-time&quot;&gt;3.4 Modeling Write Time&lt;/h2&gt;

&lt;p&gt;여기부터 설명이 점점 이상해진다.&lt;/p&gt;

&lt;p&gt;우리의 모델을, ‘언제’ 메모리 slot이 쓰여졌는지를 고려할 수 있도록 확장할 수 있다. 이는 ‘프랑스의 수도는 어딘가요?’와 같은 fixed fact에 대해 답할때는 중요한것이 아니지만, 앞의 milk예시 처럼 story에 관한 질문일 경우 중요한 요소가 된다.&lt;/p&gt;

&lt;p&gt;경험적으로 우리는 다음과 같은 해결책을 찾았다. 기존의 scoring function &lt;script type=&quot;math/tex&quot;&gt;s_O(x,y)=\Phi_x(x)^TU^TU\Phi_y(y)&lt;/script&gt;의 형식에서, 다음과 같은 3개의 인자를 받는 함수로 변화하였다.
&lt;script type=&quot;math/tex&quot;&gt;S_{O_t}(x,y,y')=\Phi_x^TU_{O_t}^TU_{O_t}(\Phi_y(y)-\Phi_y(y')+\Phi_t(x,y,y'))&lt;/script&gt;
앞에는 똑같은 형식인데,(물론 U는 위에랑 아래가 같은애는 아니다) 뒤의 형식이 다르다. 이때 y’는 또다른 memory로 이해할 수 있다. &lt;script type=&quot;math/tex&quot;&gt;\Phi_t(x,y,y')&lt;/script&gt;는 0,1의 값을 가지는 3개의 feature를 사용하는데, 각각 x가 y보다 큰지, x가 y’보다 큰지, y가 y’보다 큰지를 나타낸다. (즉 다른 &lt;script type=&quot;math/tex&quot;&gt;\Phi&lt;/script&gt;들도 3차원이 되고, 이 &lt;script type=&quot;math/tex&quot;&gt;\Phi_t(x,y,y')&lt;/script&gt;를 사용하지 않을때는 전부 0값이 된다). 만약 &lt;script type=&quot;math/tex&quot;&gt;S_{O_t}(x,y,y')&gt;0&lt;/script&gt;이라면 모델이 y를 더 선호하게 되고 &lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
S_{O_t}(x,y,y')&lt;0 %]]&gt;&lt;/script&gt;이라면 모델이 y’을 더 선호하게 된다. 이렇게 해당 식을 모든 메모리i (&lt;script type=&quot;math/tex&quot;&gt;i=1,...,N&lt;/script&gt;)에 대해 반복하여 winning memory를 계속 갱신한다.&lt;/p&gt;

&lt;h2 id=&quot;35-modeling-previously-unseen-words&quot;&gt;3.5 Modeling Previously Unseen Words&lt;/h2&gt;

&lt;p&gt;사람 역시 새로운 단어를 접하게 된다. 예를 들어 반지의 제왕에서 ‘Boromir’라는 단어를 처음 접하게 되었을때, 언어모델이 이를 어떻게 처리해야할까? 이상적으로는 하나의 예문만을 보고 동작을 해야할것이다. 가능한 한가지 방법은 주변의 단어들로 그 위치의 단어를 예측하고, new word가 그와 비슷한 단어일 것이라 생각하는 것이다. 우리는 이 아이디어를 우리의 네트워크 &lt;script type=&quot;math/tex&quot;&gt;S_O, S_R&lt;/script&gt;과 결합하였다.&lt;/p&gt;

&lt;p&gt;구체적으로 input으로 들어오는 모든 단어에 대해 함께 등장하는, 즉 왼쪽의 단어와 오른쪽의 단어를 bag of word로 저장하였다. unknown word도 이런 feature들로 표현될 수 있다. 따라서 feature representation D를 기존의 &lt;script type=&quot;math/tex&quot;&gt;3\lvert W\lvert&lt;/script&gt;에서 &lt;script type=&quot;math/tex&quot;&gt;5\lvert W\lvert&lt;/script&gt;로 확장하였다. (각각 unknown bag에 대해 &lt;script type=&quot;math/tex&quot;&gt;\lvert W\lvert&lt;/script&gt;이 추가되었다). training에서, 각 step의 d%마다 droupout의 형태로 해당 단어를 n차원 임베딩 단어가 아닌 unknown단어라 치부하여 context를 통해 대신 표현하였다. 이런 방식으로 new word를 다루는 방식을 학습하게 하였다….&lt;script type=&quot;math/tex&quot;&gt;S_O&lt;/script&gt;의 phi를 5W로 확장했다는 건 알겠는데.. 그래서 결국 missing 3W는 어떻게 한건지….?&lt;/p&gt;

&lt;h2 id=&quot;36-exact-matches-and-unseen-words&quot;&gt;3.6 Exact Matches and Unseen Words&lt;/h2&gt;

&lt;p&gt;임베딩 모델은 n차원이라는 적은 차원으로 인해 word match를 효과적으로 할 수 없다. 하나의 해결책은 x,y의 pair를 점수매기는 것이다
&lt;script type=&quot;math/tex&quot;&gt;\Phi_x(x)^TU^TU\Phi_y(y)+\lambda\Phi_x(x)^T\Phi_y(y)&lt;/script&gt;
즉 bag of word끼리의 매칭 score를 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;와 함께 추가하는 것이다. (이게 왜 효과가 있는지는 잘..설명조차 없…)&lt;/p&gt;

&lt;p&gt;또다른 방법은 n차원을 그대로 유지하지만 feature representation D를 matching feature로 확장하는 것이다(D는 feature의 수를 의미한다)matching feature란 단어가 x와 y에 동시에 등장한 것을 의미하는 것이다. 메모리y의 어떤 단어가 x와 겹친다면 그 matching feauture를 1로 만든다. (결국 위의 feature map들끼리의 내적과 거의 같은 의미인듯하다) 즉, x에 대해 conditon이 부여되어 구성된 &lt;script type=&quot;math/tex&quot;&gt;\Phi_y&lt;/script&gt;를 통해  &lt;script type=&quot;math/tex&quot;&gt;\Phi_x(x)^TU^TU\Phi_y(y,x)&lt;/script&gt;로써 match score를 매기는 것이다. unseen word역시 비슷한 방식으로 모델링될 수 있다. 이는 feature space를 &lt;script type=&quot;math/tex&quot;&gt;8\lvert W\lvert&lt;/script&gt;로 키운다. &lt;script type=&quot;math/tex&quot;&gt;\lvert 5W\lvert&lt;/script&gt;에 기존 representation의 크기인 &lt;script type=&quot;math/tex&quot;&gt;3\lvert W\lvert&lt;/script&gt;이 추가되서 인듯..하다&lt;/p&gt;

&lt;h2 id=&quot;experiment&quot;&gt;Experiment.&lt;/h2&gt;

&lt;p&gt;생략. 부가적인설명없이 표랑 잘 답변한 예시만 다닥다닥… RNN, LSTM보다 잘했다뿐…&lt;/p&gt;

&lt;h2 id=&quot;conclusion-and-future-work&quot;&gt;Conclusion and Future work&lt;/h2&gt;

&lt;p&gt;MemNN for text를 더 발전시켜야 한다. 더 어려운 QA나 open-domain에 대해작동하는것 등. QA를 위한 추론을 위해서 multi-hop을 해야하는 task, 더 많은 구조와 더 많은 동사, 명사를 가진 복잡한 data에 대한 작동. 대부분의 data set이 Q,A만 있고 우리가 한것 처럼 supporting fact에 대한 라벨은 없으므로 보다 완화된 supervised도 고려되어야 한다. 이는 우리가 소개한 MemNN보다 더 뛰어난 형태일 것이며 이밖에도 여러 variant들이 있을 수 있을 것이다.&lt;/p&gt;

&lt;hr /&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;참고 : 인공지능을 위한 머신러닝 알고리즘 11강 메모리 네트워크&lt;/td&gt;
      &lt;td&gt;T아카데미. 설명짱짱 친절하다. end-to-end MMn에 대한 설명도 함께 한다.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;https://www.youtube.com/watch?v=vDQf7lcenfI&lt;/p&gt;
</description>
        <pubDate>Sun, 11 Mar 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/03/11/Memory-Networks-paper-review.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/03/11/Memory-Networks-paper-review.html</guid>
        
        <category>Deep Learning</category>
        
        <category>NLP</category>
        
        
        <category>딥러닝</category>
        
      </item>
    
      <item>
        <title>[ISL] 8장 -Tree-Based Methods(Bagging, RF, Boosting)이해하기</title>
        <description>
&lt;p&gt;드디어, regression과 classification을 위한 tree-based 방법을 다룬다. 이 방법은 예측변수의 전체 공간을 단순한 여러 영역으로 계층화(stratifying), 혹은 분할(segmenting)하는 방법이다. 후에 예측을 할때에는 해당 영역의 training date의 평균값이나 최빈값으로 값을 예측한다. 예측변수의 공간을 나누는 방식이 tree형식으로 나타내질 수 있기에 이러한 방법들을 decision tree방법이라 부른다.&lt;/p&gt;

&lt;p&gt;tree-based 방법은 단순하고 설명력이 좋으나, 기존의 6,7장에서 다룬 supervised learning보다 예측력이 좋지 못하다. 따라서 이번 장에선 tree를 확장시킨 &lt;strong&gt;bagging, random forests, boosting방법&lt;/strong&gt;을 소개한다.(!) 이들은 여러개의 tree를 만들어 이를 결합하는 방식인데, 이렇게 하여 예측정확도의 엄청난 상승을 거둘 수 있다.&lt;/p&gt;

&lt;h2 id=&quot;81-the-basics-of-decision-trees&quot;&gt;8.1 The Basics of Decision Trees&lt;/h2&gt;

&lt;p&gt;Decision tree는 회귀나 분류문제 모두에 사용된다. 우선 회귀문제부터 다뤄보도록 하자.&lt;/p&gt;

&lt;h3 id=&quot;81-1-regression-trees&quot;&gt;8.1-1 Regression Trees&lt;/h3&gt;

&lt;p&gt;예시 데이터로, 야구선수들의 메이저리그경력(Years)과 지난 시즌 안타수(Hits)로 연봉(Salarys)를 예측하는 문제를 생각해보자. regression tree는 간단하게 다음과 같은 그림으로 작동을 한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580558-a94bc34e-1860-11e8-9d46-31b0511711b9.PNG&quot; alt=&quot;tree1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위에서 부터 몇개의 spliting rule에 따라 자료들을 나눈다. 예를 들어 메이저리그Year가 4.5년보다 적으면 왼쪽으로 보내는 식이다. 이때 [Years &amp;lt; 4.5]인 사람들의 salary의 예측값은 단순히 training data에서  [Years &amp;lt; 4.5]인 사람들의 평균값으로 예측한다. Year가 4.5년보다 큰 사람들은 오른쪽으로 보내져 2번째 갈림길인 Hits&amp;lt;117.5에 도달하여 나뉘어 진다.&lt;/p&gt;

&lt;p&gt;결국, 위의 tree모델은 전체 player를 3영역으로 나누게 되는 것이다. [Years &amp;lt; 4.5]인 player들, [Years &amp;gt; 4.5 &amp;amp; Hits &amp;lt; 117.5]인 player들, [Years &amp;gt; 4.5 &amp;amp; Hits &amp;gt; 117.5]인 player들. 이를 그림으로 표현하면 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580557-a90419ae-1860-11e8-8beb-26f10243e225.PNG&quot; alt=&quot;tree2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;각각의 영역의 예측값은 그곳에 속하는 data들의 salary평균이다. 이때 위의 나무그림을 기준으로, 최종적으로 나눠진 각각의 node(아래 그림에선 &lt;script type=&quot;math/tex&quot;&gt;R_1,R_2,R_3&lt;/script&gt;)은 terminal nodes, 혹은 tree의 leaf라고 불리고, 그 전까지의 갈림길(node)들은 internal node라고 불린다.&lt;/p&gt;

&lt;p&gt;위의 결과를 통해, 메이저리그에서의 Salary는 Year에 큰 영향을 받는것을 알 수 있다. 즉, 경력이 별로 없는 선수라면 안타(Hits)를 많이 기록해도 Salary에 영향을 거의 미치지 못한 것이다. 이와 같이 Decision tree는 설명력의 측면에서 강점을 가지고 있다. 결과로 나온 나무 그림만으로도 시각적 설명이 가능하다.&lt;/p&gt;

&lt;h4 id=&quot;prediction-via-stratification-of-feature-space&quot;&gt;Prediction via Stratification of Feature Space&lt;/h4&gt;

&lt;p&gt;위와 같은 regression tree는 다음 2단계를 거쳐 진행된다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;모든 설명변수(&lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_p&lt;/script&gt;)가 포함된 공간을 &lt;script type=&quot;math/tex&quot;&gt;J&lt;/script&gt;개의 ‘겹치지 않는’ 영역으로 분할한다.&lt;/li&gt;
  &lt;li&gt;각 영역에서는 그곳에 속하는 training data의 평균을 통해 &lt;strong&gt;일관된 예측값&lt;/strong&gt;을 반환한다.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;그럼, 어떻게 &lt;script type=&quot;math/tex&quot;&gt;J&lt;/script&gt;개의 영역을 쪼갤까? 영역은 다양한 형태로 쪼갤수 있겠지만, 해석의 편의를 위해 위의 그림과 같이 box형태로 쪼갠다. 구체적으로는, &lt;strong&gt;RSS를 최소화하는 방향으로&lt;/strong&gt; box를 쪼갠다.&lt;/p&gt;

&lt;p&gt;각 box(&lt;script type=&quot;math/tex&quot;&gt;R_1,..,R_J&lt;/script&gt;)에서의 예측으로 인한 잔차들을 줄여주는 것이다. 이는 식으로 나타내면 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;\sum_{j=1}^J\sum_{i\in R_j}(y_i-\hat y_{R_J})^2&lt;/script&gt;
그러나, 모든 가능한 box들의 조합을 구하고 RSS를 계산하는 것은, 불가능하다. (Year&amp;lt;2,Hits&amp;lt;102.01,..,같은 무한한 box조합이 존재할것이다. 변수가 많아질수록 더더욱.) 따라서 실제로는, top-down, greedy 방식을 사용한다. 즉, 위에서 부터 기준을 만들되, 기준을 만들때 앞일은 고려대상에서 제외하고, 당장의 RSS를 최소화하는 것을 목표로(greedy) 기준을 만드는 것이다. 이를 recursive binary splitting이라고도 부른다. (물론, 미래의 관점에서 이는 최선의 수가 아니었을 수도 있다. 그러나 이것이 실현가능한 수이다.)&lt;/p&gt;

&lt;p&gt;첫번째 기준, 즉 아직 모든 data가 분할되지 않고 한 영역에 있을때를 생각해보자. 그때 우리는, 각각의 &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_p&lt;/script&gt;에 대해서 분할점을 고려하고, 그 중 RSS를 최소화하는 특정 변수&lt;script type=&quot;math/tex&quot;&gt;X_j&lt;/script&gt;의 분할점을 고를 수 있을 것이다. 첫번째 분할만을 고려한다는 점에서 이는 훨씬 수월한 작업이 된다. 이를 식으로 나타내면, 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580556-a8bbc154-1860-11e8-9706-3d75fda4d2d8.PNG&quot; alt=&quot;tree3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;특정 분할점 s를 찾는다. 어떤 기준으로?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580555-a87d0ebe-1860-11e8-893f-2a19145310eb.PNG&quot; alt=&quot;tree4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그렇게 분할하였을때 RSS가 최소인 분할점으로.&lt;/p&gt;

&lt;p&gt;그 후 만들어진 2개의 영역 중 하나를 다시 RSS를 최소화하는 기준으로 recursive binary로 쪼개고, 이를 통해 만들어진 3개의 영역중 하나를 쪼개는 식이다. 이는 미리 설정해둔 stopping criterion을 충족할때까지 반복될 수 있다. stop criterion은 각 leaf안에 최소 5개의 data는 있어야 한다는 것 등이 있다.&lt;/p&gt;

&lt;p&gt;최소 기준만을 가지고 적합을 한 큰 tree의 예시는 다음과 같다. 그림을 잘 보면 알겠지만, [Years &amp;lt; 4.5]가 나왔어도 같은 변수기준인 [Years &amp;lt; 3.5]가 아래에 다시 등장하기도 한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580563-aa4a1566-1860-11e8-935b-1c27a964762a.PNG&quot; alt=&quot;tree4.1&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;tree-pruning&quot;&gt;Tree Pruning&lt;/h4&gt;

&lt;p&gt;위의 방식은 training data에는 잘 적합할 수 있으나, overfit의 위험이 있다. 지나치게 세분화된 tree는 train set에서만의 특징마저 반영 해버릴 수 있기 때문이다. 이는 결과적으로 test set에서는 좋지 못한 성능을 냄을 나타낸다. 따라서 split을 제한하여 약간의 bias가 생기더라도 variance가 높지 않은, ‘지나치게 세분화되지 않은 tree’를 만들고자 한다.&lt;/p&gt;

&lt;p&gt;이를 위한 한가지 방법은, 각 split을 통해 줄어드는 RSS가 특정 임계치를 넘을때에만 split을 해주는 전략이 될 수 있다. 그러나, 간혹 이전 split에서는 RSS가 많이 줄지 않았어도 다음 split에서는 RSS가 대폭 주는 경우도 있기에, 이는 근시안적인 방법으로 좋지 못하다. (예를들어, node2에서는 RSS가 10%줄었지만 node2,node3까지 하였을 경우 RSS가 40%주는 경우)&lt;/p&gt;

&lt;p&gt;따라서 더 나은 방법은, 아주 큰 tree &lt;script type=&quot;math/tex&quot;&gt;T_0&lt;/script&gt;을 만든 후 이를 적절한 subtree를 얻기위해 &lt;strong&gt;잘라내는&lt;/strong&gt;(prune) 방식이다. 이를 pruning이라 한다. 그렇다면 어떤 기준으로 prune을 해야할까? 우리의 목표는 낮은 test error를 갖는 subtree를 찾는 것이지만, 이를 위해 모든 subtree를 CV를 해보는 것은 불가능하다. 역시나, 너무나 많은 subtree가 가능하다. 따라서 몇개의 subtree들만을 추려 고려대상으로 삼는 방법을 쓴다.&lt;/p&gt;

&lt;p&gt;Cost complexity pruning이란 방법이 이를 가능하게 하는 방법인데, 각 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;에 대해 다음의 식을 최소화하는 subtree를 구하는 것이다.
&lt;script type=&quot;math/tex&quot;&gt;\sum_{m=1}^{\lvert T\lvert}\sum_{x_i\in R_m}(y_i-\hat y_{R_m})^2-\alpha\lvert T\vert&lt;/script&gt;
여기서 &lt;script type=&quot;math/tex&quot;&gt;\lvert T\vert&lt;/script&gt;는 terminal node의 수를 말하는 것이다. 식을 보면, &lt;strong&gt;1)&lt;/strong&gt; 각 terminal node안에서의 RSS를 줄여주는 loss term과 &lt;strong&gt;2)&lt;/strong&gt;지나치게 많은 terminal node들이 있지 않도록, 즉 complexity를 줄여주는 penalty term이 있는 형태임을 알 수 있다. 이는 Lasso의 형태와 비슷하다. 둘의 비율은 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;로써 조절 할 수 있는데, 이 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;를 cross-validation을 통해 구하면 되는 것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;위의 식을 좀더 직관적으로 이해해보자면, 새로운 split을 함으로써 생기는 RSS의 ‘이득’이 &lt;script type=&quot;math/tex&quot;&gt;\alpha \lvert T\lvert&lt;/script&gt;라는 penalty보다 더 크지 못하다면 split을 안하는 형태라고 생각할 수 있다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이를 최종적으로 정리하면, 다음과 같다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;recursive binary splitting(즉 top-down, greedy방식)을 통해 큰 tree를 적합한다. 이때의 유일한 stop기준은 node안에 최소 기준보다 적은 수의 data가 남는 것이다.&lt;/li&gt;
  &lt;li&gt;앞의 과정에서 만들어진 큰 tree에 cost complexity pruning을 한다. 이때의 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;는 K fold cross-validation을 통해 이루어 진다.&lt;/li&gt;
  &lt;li&gt;cross-validation은 다음의 과정을 통해 이루어 진다. training data를 K개의 fold로 나눈다
    &lt;ul&gt;
      &lt;li&gt;한개씩 fold를 뺀 모든 K개의 data set에 대해 1번의 적합을 한다&lt;/li&gt;
      &lt;li&gt;각 K개의 data set을 통해 나온 tree들에 여러 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;값에 따라 cost complexity pruning을 하고, 그때의 error를 평균내어 validation error로 최적의 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;를 정한다.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;3번에서 정해진 최적의 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;값을 통해 1번에서 전체 데이터를 통해 만든 tree에 pruning을 한다.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580553-a7dc3f5c-1860-11e8-981f-ac215c63663c.PNG&quot; alt=&quot;tree5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이는 Cross-validation을 해본 그림이다. 실제로는 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;로써 pruning을 하지만, &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;와 terminal node수 간에는 1-1관계에 있기에 tree size로 나타내었다.&lt;/p&gt;

&lt;h3 id=&quot;81-2-classification-trees&quot;&gt;8.1-2 Classification Trees&lt;/h3&gt;

&lt;p&gt;classification tree는 반응변수가 질적변수라는 것외에 크게 다를 것이 없다. regression에서는 각 영역의 평균으로 반응변수를 예측했다면, classification문제에서는 &lt;strong&gt;가장 많이 등장한 클래스&lt;/strong&gt;로 예측을 한다. 단순히 평균을 내는것이 아니라 가장 많이 등장한 클래스로 분류를 하고 나머지 클래스는 무시해버린 격이 되기 때문에, 분류에서는 단순히 예측값 뿐 아니라 &lt;strong&gt;해당 영역에 있던 다른 클래스의 비율&lt;/strong&gt;에도 관심이 있다.&lt;/p&gt;

&lt;p&gt;classification tree는 만들어질때, 역시나 recursive binary splitting을 이용하여 적합하나 기준이 RSS가 아니라 classfication error rate이다. 가장 많이 등장한 클래스로 예측을 하였으니, error rate는 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580571-abd5d6ae-1860-11e8-8090-d309368077e8.PNG&quot; alt=&quot;tree6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;영역m에서 여러 k클래스들의 비율 중 1-(가장 많이 등장한 것의 비율) 이다. 그러나 바로 전에 논의하였듯이, 이는 다른 클래스의 비율을 고려 안했기에 충분히 민감한 기준이 되지 못한다. 따라서 실제에서는 다음의 두 척도가 대신 사용된다.&lt;/p&gt;

&lt;h5 id=&quot;gini-index&quot;&gt;Gini index&lt;/h5&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580570-ab98df92-1860-11e8-808b-c5f6761bc46e.PNG&quot; alt=&quot;tree7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;첫째로, Gini index(지니 불순도)는 전체 K클래스를 모두 고려하여, 클래스의 분산을 계산한다. 특정 k클래스의 &lt;script type=&quot;math/tex&quot;&gt;\hat p_{mk}&lt;/script&gt;만이 1에 가까울 수록 gini index의 값이 작아질 것을 알 수 있다. 따라서 이는 ‘불순도’를 나타내는 개념이다.&lt;/p&gt;

&lt;h5 id=&quot;entropy&quot;&gt;entropy&lt;/h5&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580568-ab48a554-1860-11e8-8bea-b1d60ab53a8b.PNG&quot; alt=&quot;tree8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;정보이론에서 많이 활용되는 entropy의 개념이다. &lt;script type=&quot;math/tex&quot;&gt;\hat p_{mk}&lt;/script&gt;이 &lt;script type=&quot;math/tex&quot;&gt;0\le\hat p_{mk}\le1&lt;/script&gt;이기에, &lt;script type=&quot;math/tex&quot;&gt;0\le\hat p_{mk} log(\hat p_{mk})&lt;/script&gt;이다. 이 역시 특정 k클래스의 &lt;script type=&quot;math/tex&quot;&gt;\hat p_{mk}&lt;/script&gt;만이 1에 가깝고 나머지는 0에 가까울 수록 값이 작아질 것을 알 수 있다. Gini index와 같은 특성을 판별해 내는 것이다. 사실 수학적으로 둘은 매우 유사한 지표이다.&lt;/p&gt;

&lt;p&gt;recursive binary splitting에서, 이 둘은 단순한 classification error rate보다 더 민감한 지표이기 때문에 splitting기준으로 사용된다.&lt;/p&gt;

&lt;p&gt;해당 기준으로 tree가 다 완성된 후, &lt;strong&gt;Pruning에서는&lt;/strong&gt;, classification error나 gini index, entropy 3기준이 모두 활용될 수 있으나 예측의 정확도를 위해 &lt;strong&gt;classificaion error&lt;/strong&gt;가 주로 사용된다.&lt;/p&gt;

&lt;p&gt;다음은 classification tree의 예시이다. (변수들의 의미는 크게 중요하지 않다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580566-aafe65e8-1860-11e8-9d41-4340c3a32871.PNG&quot; alt=&quot;tree9&quot; /&gt;&lt;/p&gt;

&lt;p&gt;오른쪽 아래의 node, [RestECG &amp;lt; 1] 를 보면, 이상한점을 알 수 있다. node의 양 갈래의 예측이 모두 Yes인 것이다. 둘다 Yes 라면 왜 굳이 나눈걸까? 이는 node의 purity(순수한 정도) 때문이다.  [RestECG &amp;lt; 1]의 오른쪽 leaf에는, 9개의 자료가 모두 Yes이고, 왼쪽 leaf에는 7/11이 Yes였다. 따라서 실제 예측을 할때에도,  [RestECG &amp;lt; 1]의 오른쪽으로 배정된 test data는 더욱 확실하게 Yes라고 할 수 있고 왼쪽으로 배정된 test data는 낮은 확실성을 갖고 예측을 할 수 있게 되는 것이다.  node[RestECG &amp;lt; 1]는 classification error에는 차이가 없지만, GIni index나 entropy의 기준에서는 차이가 있다.(!) 이러한 이유로 후자를 사용하는 것이다.&lt;/p&gt;

&lt;p&gt;추가로, 질적변수의 경우도 역시나 node로 활용될 수 있는데, 위의 예시의 경우 [ChestPaint : a]의 node가 그 예이다. ChestPaint가 a클래스이면 오른쪽 leaf, 아니면 왼쪽 leaf로 가는 식이다.&lt;/p&gt;

&lt;h3 id=&quot;81-3-tree-versus-linear-models&quot;&gt;8.1-3 Tree Versus Linear Models&lt;/h3&gt;

&lt;p&gt;Tree based model은 기존의 3,4장에서 다루었던 보다 더 전통적인 방법들과는 좀 다르게 생겼음을 알 수 있다. 그렇다면, 이 들중 누가 더 좋은 모델일까? 답은 역시 &lt;strong&gt;그때 그때 다르다&lt;/strong&gt;. 만약 진짜 관계선이 선형이라면, 선형회귀가 잘 작동할 것이고 regression tree는 그만큼 명확한 선형관계를 잡아내지 못할 것이다. (애초에 regressoin tree는 해당영역의 ‘평균값’, 즉 x축의 평행선으로 예측을 하기에, 수많은 계단식 선이 나온다.) 그러나 실제 관계가 많은 non-linear이고 복잡한 관계를 가졌다면, decision tree가 전통적인 모델보다 뛰어날 것이다. 다음은 실제 decisoin boundary가 linear일 경우와 아닐 경우의 binary classification의 단순한 예시 그림이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580564-aa987d96-1860-11e8-941f-9c05f1443e1c.PNG&quot; alt=&quot;tree10&quot; /&gt;&lt;/p&gt;

&lt;p&gt;예측력 외에도, 설명력이나 시각화를 위해 tree모델이 선호되는 경우도 있다.&lt;/p&gt;

&lt;h3 id=&quot;81-4-advantages-and-disadvantages-of-trees&quot;&gt;8.1-4 Advantages and Disadvantages of Trees&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Tree model은 설명력이 아주 뛰어나다. 심지어, linear regression보다도 뛰어나다.&lt;/li&gt;
  &lt;li&gt;전통적인 방법에 비해 좀더 사람의 의사결정과 닮았다.&lt;/li&gt;
  &lt;li&gt;시각화하기 좋다. (역시나 설명력의 측면)&lt;/li&gt;
  &lt;li&gt;더미 변수를 만들지 않고도, 양적변수와 질적변수를 모두 다룰 수 있다.&lt;/li&gt;
  &lt;li&gt;그러나, 이 책에서 다룬 다른 방법들에 비해 &lt;strong&gt;예측 정확도가 좋지는 못하다&lt;/strong&gt;.(prune을 한다해도, 여전히 overfit의 한계를 완벽하게 벗어나지 못했기 때문이다.)&lt;/li&gt;
  &lt;li&gt;추가로 tree는 ‘non-robust’하다. 즉, 데이터의 작은 변화에도 tree의 최종 예측값이 크게 변동할 수 있다. 즉, variance가 크다&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;그러나 decision tree&lt;strong&gt;들&lt;/strong&gt;을 모아 활용하는 방식인 bagging, random forest, boosting을 통해서는 예측 정확도가 뛰어나가 향상된다.&lt;/p&gt;

&lt;h2 id=&quot;82-bagging-random-forest-boosting&quot;&gt;8.2 Bagging, Random Forest, Boosting&lt;/h2&gt;

&lt;p&gt;Bagging, Random Forest, Boosting은 tree들을 building block으로 활용한 모델이다.&lt;/p&gt;

&lt;h3 id=&quot;82-1-bagging&quot;&gt;8.2-1 Bagging&lt;/h3&gt;

&lt;p&gt;5장에서 소개했던 bootstrap이 이 곳에서 활용된다. 앞에서 소개되었던 decision tree는 &lt;strong&gt;high variance&lt;/strong&gt;로 인한 약점을 가지고 있었다. (variance가 높다는 것은 다른 데이터셋에 따라 모델이 심하게 변동한다는 것을 의미한다.) Bootstrap aggregation, 줄여서 Bagging은 이런 &lt;strong&gt;Variance를 줄여주기 위한&lt;/strong&gt; 목적을 가지고 있다. 특히나 decision tree에서 효율적으로 쓰이기에 이곳에 같이 소개되었다.&lt;/p&gt;

&lt;p&gt;같은 분산 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;를 가지고 있는 서로 독립인 통계량 &lt;script type=&quot;math/tex&quot;&gt;Z_1,..,Z_n&lt;/script&gt;들의 평균, 즉 &lt;script type=&quot;math/tex&quot;&gt;\bar Z&lt;/script&gt;의 분산은 &lt;script type=&quot;math/tex&quot;&gt;\frac{\sigma^2}{n}&lt;/script&gt;이란 것을 알고있다. 물론 독립에 등분산은 현실에선 많지 않지만, 우선 간단화 해보자면, &lt;strong&gt;평균을 취하는 것은 분산을 감소시킨다&lt;/strong&gt;. 따라서 분산을 감소시키는, 그럼으로써 궁극적으로는 예측력을 높이는 자연스런 결론은 &lt;strong&gt;모집단의 많은 데이터 셋에 적합&lt;/strong&gt;하여 여러개의 예측 모델을 만들고, 그 모델의 &lt;strong&gt;예측결과를 평균내는것&lt;/strong&gt;일 것이다.&lt;/p&gt;

&lt;p&gt;그러나 당연히 현실에서는 모집단에서 무수히 많은 데이터셋을 추출하는 것이 불가능하다. 대신, 5장에서 다루었던, 주어진 training set에서 무수히 많은 B번의 반복추출로 무수히 많은 data set을 만들어내는, Bootstrap을 진행하여 B개의 여러 모델을 만들수 있다. 이들을 평균냄으로써, 위의 논의를 따라가는 최종 결과물을 얻을 수 있을 것이다. 이것이 &lt;strong&gt;B&lt;/strong&gt;ootstrap하여 합친다(&lt;strong&gt;agg&lt;/strong&gt;regat&lt;strong&gt;ing&lt;/strong&gt;한다), 즉 Bagging이다.&lt;/p&gt;

&lt;p&gt;Bagging은 여러 regression 방법들의 variance를 줄여줄 수 있지만, 특히나 high Variance로 골치를 앓고 있던 decision tree에서 유용하게 사용된다. bootstrap을 통해 B개의 training set을 만들고, 이에 대해 B개의 tree를 만드는것이다. 이때, tree들은 &lt;strong&gt;prune을 하지 않는다.&lt;/strong&gt; 따라서 low bias이지만, 매우 높은 variance를 가지고 있는 모델이다. 이들을 최종적으로 평균내줌으로써, variance를 줄여주는 것이다. (물론 Bootstrap을 통해 만들어진 data set들은 그 구성도 매우 비슷하여, 모델들간의 covaraince도 높아진다! 따라서 위에서 논의한 ‘독립인’통계량의 분산 처럼 완벽히 분산을 1/n한 결과가 나오지 않는다. 뒤에서 다룰 것이다!)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;독립이 아닐 경우&lt;/p&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;Var[(Z_1+..+Z_n)/n]=\frac{1}{n^2}\left\{Var(Z_1)+...+Var(Z_n)+\sum\sum Cov(Z_i,Z_j)\right\}&lt;/script&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;=\frac{1}{n^2}\left\{n\sigma^2+\sum\sum Cov(Z_i,Z_j)\right\}&lt;/script&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;=\frac{\sigma^2}{n}+\frac{1}{n^2}\left\{\sum\sum Cov(Z_i,Z_j)\right\}&lt;/script&gt;

  &lt;p&gt;따라서 각 통계량(여기선 model)간의  공분산을 줄이는 것 역시 관건이다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;out-of-bag-error-estimation&quot;&gt;Out-of-Bag Error Estimation&lt;/h4&gt;

&lt;p&gt;Bagging을 통해서는 각 Bootstrap을 하며 복원추출에 뽑히지 않은 데이터들(보통 2/3정도가 뽑힌다고 한다.)이 자동으로 validation set이 되어 Cross-validation을 하지 않아도 test error를 추정할 수 있다. 이 뽑히지 않은 데이터를 Out-of-bag(OOB)이라 부른다.&lt;/p&gt;

&lt;p&gt;특정 데이터(&lt;script type=&quot;math/tex&quot;&gt;x_i&lt;/script&gt;)가 뽑히지 않은, 전체 B개중 약 B/3개의 모델들이 특정데이터(&lt;script type=&quot;math/tex&quot;&gt;x_i&lt;/script&gt;)에 대한 예측을 하고, 이를 평균낸다. 이런 식으로 모든 데이터에 대해 예측을 하여 OOB MSE나, classification error를 구할 수 있다. 물론 cross-validation이 더욱 정확한 test error추정을 가능하게 하지만, 데이터가 충분히 많고 충분히 많은 B번의 Bootstrap의 경우 OOB 역시 비슷한 성능을 내기에, 별도의 CV를 진행하지 않는다는 점에서 이점이 있다. (그러나 왠만하면 CV를 하자…)&lt;/p&gt;

&lt;h4 id=&quot;variable-importance-measures&quot;&gt;Variable Importance Measures&lt;/h4&gt;

&lt;p&gt;여러개의 나무를 합하면서, 예측 정확도는 올라갔지만 대신 기존의 decision tree가 가지고 있던 해석력을 잃었다. 더이상 하나의 나무그림으로 의사결정의 절차를 표현할 수 없어졌기 때문이다. 따라서 bagging은 해석력을 희생하여 많은 예측력을 얻은 것이라 볼 수 있다.&lt;/p&gt;

&lt;p&gt;그러나 이전만큼의 해석력은 아니지만, RSS나 Gini index를 통하여 전반적인 &lt;strong&gt;예측변수들의 중요도&lt;/strong&gt;를 확인할 수 있다. 예를 들어 회귀문제의 경우, &lt;strong&gt;모든 B개의 나무에 대해&lt;/strong&gt; 각 변수에서의 split으로 인해 &lt;strong&gt;RSS가 감소한 정도&lt;/strong&gt;를 측정하여, 이를 평균을 낸다.(!) 해당 변수로 인해 RSS가 많이 감소하였으면, 이는 중요한 변수임을 의미하게 된다. 마찬가지로 분류의 경우 Gini index의 감소량을 측정한다.&lt;/p&gt;

&lt;p&gt;다음은 앞에서 본 classification 문제에서 bagging을 사용하였을 경우의 변수 중요도이다. 이는 각각 Gini index의 평균 감소량을 통해 정렬된 것이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580562-aa0ca988-1860-11e8-92f4-4b2e57841cba.PNG&quot; alt=&quot;tree11&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;82-2-random-forests&quot;&gt;8.2-2 Random Forests&lt;/h3&gt;

&lt;p&gt;앞에서도 언급하였지만, Bootstrap을 통해 만든 데이터들은 그들간에 correlated된 정도가 높다. 비슷한 데이터로 만들어진 모델들은 서로 비슷한 모델일 것이다. (split기준이 비슷하고 등등..) 이는 모델의 높은 covariance를 의미하고, 따라서 bagging은 의도한 만큼 Variance가 줄어들지 못한다.&lt;/p&gt;

&lt;p&gt;따라서, Random Forest는 tree들을 &lt;strong&gt;decorrelate&lt;/strong&gt;해주고자 약간의 트릭을 사용한다. 똑같이 bootstrap된 데이터를 통해 나무들을 만들지만, 각 split을 자를때, 전체 p개의 예측변수 중 &lt;strong&gt;랜덤하게 선택된 m개의 변수만을 고려&lt;/strong&gt;하여 그 중에서 split 기준을 만든다. 또 다음 split을 만들때는 새롭게 랜덤하게 선택된 m개의 변수만을 고려하여 선택을 한다. 이때, &lt;script type=&quot;math/tex&quot;&gt;m \approx \sqrt p&lt;/script&gt;로 주로 지정한다.&lt;/p&gt;

&lt;p&gt;이로써 random forest는 각 split에서 가능한 변수들의 반도 다 안쓰는 것이다. 얼핏 이상하게 들릴지 모르지만, 여기에는 다 이유가 있다. 만약 한가지 예측변수가 매우 강력한 예측변수이고, 나머지는 적절하게 강력한 예측변수라고 해보자. 그렇다면 bagging을 통해 만들어진 tree들은, (비록 bootstrap으로 약간씩 다름에도 불구하고) 거의 모든 tree들이 가장 강력한 그 하나의 변수를 top split으로 삼고 있을 것이다. 즉, &lt;strong&gt;매우 비슷해 보이는 bagged tree들&lt;/strong&gt;이 만들어 질것이다. 이미 언급하였듯이, highly correlated 된 통계량들을 평균내는 것은 그렇지 않은 경우에서 평균내는것 만큼의 큰 variance의 감소를 내지 못한다.&lt;/p&gt;

&lt;p&gt;이를 극복하고자 random forest는 일부러 split에서 몇개(m개)만을 고려하는 것이다. 이로써 몇몇 split에는 해당 강력한 변수가 고려대상에도 들어가지 않게되고, 다른 예츠변수들이 고려될 기회를 얻는 것이다. 이로써 tree들은 decorrelated된 효과를 갖게되고, 평균을 취해서 variance를 줄여주고자 하는 의도에 더욱 부합하게 된다.&lt;/p&gt;

&lt;p&gt;언급하였듯이 &lt;script type=&quot;math/tex&quot;&gt;m \approx \sqrt p&lt;/script&gt;으로 주로 지정한다. 변수들중 많은 수의 변수가 correlated되어 있는 경우 더 작은 수의 m이 더 유효할 수 있다. (그러나 왠만하면 &lt;script type=&quot;math/tex&quot;&gt;m \approx \sqrt p&lt;/script&gt;을 사용하자.)&lt;/p&gt;

&lt;p&gt;마지막으로 예시 데이터에 대한 Bagging과 Randomforest, 그리고 그들의 OOB error에 대한 그림이다. 예상한 대로 Bagging보다 Randomforest가 더 좋은 성능을 보였다. 그리고, tree의 갯수가 어느정도 커지면 error율이 수렴을 하는 그림을 보인다. 이는 covaraince의 존재로, 해당 방법으로 얻을 수 있는 성능향상의 한계치를 나타내준다. 즉, 나무의 갯수는 충분한 정도 이상을 늘릴 필요는 없다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580561-a9c519ec-1860-11e8-8110-00a10c1285a3.PNG&quot; alt=&quot;tree12&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;덧. 원래 decision tree는 질적변수를 더미화하지 않아도 되지만, python의 scikit-learn에선 현재 더미화를 시켜 input으로 넣어줘야만 작동이 되게 되어있다. 이 경우 질적변수의 카테고리가 많지 않은 경우 문제가 없지만, 카테고리가 많은 경우 수백개의 더미변수들이 생겨나버려 1) 차원이 커지고, 2) 각 변수들도 ‘그 더미변수의 클래스인지’ ‘아닌지’만을 나타내는 매우 &lt;strong&gt;sparse한 변수&lt;/strong&gt;가 되버려, 다른 양적변수들에 비해 필연적으로 중요하게 고려되지 못하게 된다.(비록 원래 중요한 변수였더라도!) 따라서 질적변수의 카테고리가 엄청나게 많을경우, 섣부른 더미화+RF적합은 위험할수 있다. 이때는 질적변수를 더미화하지 않고도 처리할수 있는 H2O를 써보는것도 좋다. &lt;a href=&quot;https://roamanalytics.com/2016/10/28/are-categorical-variables-getting-lost-in-your-random-forests/&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;82-3-boosting&quot;&gt;8.2-3 Boosting&lt;/h3&gt;

&lt;p&gt;이번엔 decision tree를 업그레이드 시킬 수 있는 다른 방법인 Boosting에 대해 알아보자. 미리 개념에 대해 말해보자면, Boosting은 강력하지 않으나 보완에 초점을 맞춘 약한 모델(Weak leaner)를 결합해서 정확하고 강력한 모델(Strong Learner)를 만드는 것을 통틀어 의미한다. boosting은 회귀나 분류를 위한 다른 방법들에도 사용이 될 수 있지만 여기서는 decision tree에 국한하여 다뤄본다.&lt;/p&gt;

&lt;p&gt;bagging은 bootstrap을 통해 생긴 여러 개별적인 데이터셋에 대하여 각각 개별적인 decision tree를 적합하는 방법이였다. 이때, 각 tree가 만들어지는 과정은 다른 tree들과는 관계가 없다. 그러나 Boosting은, 관계가 있다.(!) Boosting은 Bagging과 비슷한 방식으로 작동하지만, tree들이 &lt;strong&gt;순차적으로 만들어진다&lt;/strong&gt;는 차이점이 있다. 구체적으로, 각각의 tree는 이전 tree의 정보를 이용하여 만들어진다. 따라서 Boosting은, &lt;strong&gt;bootstrap sampling을 이용하지 않는다&lt;/strong&gt;. 대신 각각의 tree는 원래의 training data에서 (이전의 tree를 토대로) 수정된 training data set에 적합을 한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;수정된 training data set이 조금 애매한 표현이지만, 이는 Boosting 기법마다 다음 함수에서 적합할 training data 다르게 구하기 때문이다. AdaBoost 같은 경우는 전체 데이터 중 이전 모델이 틀린 관측치의 가중치를, boosting tree같은 경우 이전모델의 residual을 업데이트하여 적합한다.( AdaBoost 참고는 ESL) &lt;strong&gt;부스팅은 잘못 분류된 개체들에 집중하여 새로운 분류규칙을 만드는 단계를 반복하는 방법&lt;/strong&gt; 이라는 것만 기억하면 된다. bagging 과 boosting의 차이를 그림으로 쉽게 보여준 &lt;a href=&quot;https://blog.naver.com/muzzincys/220201299384&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;수정된 원래의 data set에 적합을 한다는게 무슨뜻일까? 이 말은, 다음 모델을 적합할때 바로 원래의 data set &lt;script type=&quot;math/tex&quot;&gt;Y&lt;/script&gt;에 적합을 하는게 아니라, 현재 모델이 잡지 못한, 현재모델과 Y와의 차이인 &lt;strong&gt;residual에 적합&lt;/strong&gt;을 한다는 것이다. 단계별로 좀더 자세히 알아보자.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;다음은 residual을 통해 모델이 잘 못잡는 data에 집중을 한 형태를 보여주고 있다. 그러나 이는 gradient boost에서 gradient를 만드는 loss가 L2, 즉 &lt;script type=&quot;math/tex&quot;&gt;c(y_i-\hat y_i)^2&lt;/script&gt;의 형태인 경우에 한정한 이야기이다. 즉, gradient boost의 근본적인 원리는 아니고 쉽게 이해할수잇는 한 갈래인것. gradient boost tree는 엄청난 &lt;a href=&quot;http://xgboost.readthedocs.io/en/latest/model.html&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;우리의 최종 예측값 &lt;script type=&quot;math/tex&quot;&gt;\hat f(x)&lt;/script&gt;를 우선 빈 값(0)으로 둔다. (즉, &lt;script type=&quot;math/tex&quot;&gt;\hat f(x)=0&lt;/script&gt;) 첫번째 실행의 경우 residual &lt;script type=&quot;math/tex&quot;&gt;r_i=y_i&lt;/script&gt;이다.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;for &lt;script type=&quot;math/tex&quot;&gt;b=1,2,..,B&lt;/script&gt; 만큼 다음을 반복한다.&lt;/p&gt;

    &lt;ul&gt;
      &lt;li&gt;
        &lt;p&gt;미리 지정한 &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;개 만큼의 split을 가지고 있는 tree를 예측변수X와 잔차&lt;script type=&quot;math/tex&quot;&gt;r&lt;/script&gt;의 쌍 &lt;script type=&quot;math/tex&quot;&gt;(X,r)&lt;/script&gt;에 적합하여, tree &lt;script type=&quot;math/tex&quot;&gt;\hat f^b&lt;/script&gt;를 만든다. 첫번째 실행의 경우 기존의 (&lt;script type=&quot;math/tex&quot;&gt;X,Y&lt;/script&gt;)에의 적합과 같다.&lt;/p&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;새로운 tree &lt;script type=&quot;math/tex&quot;&gt;\hat f^b&lt;/script&gt;를 미리 지정해둔 반영비율&lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;만큼 반영해준다. 다음과 같이 표현할 수 있다.&lt;/p&gt;

        &lt;script type=&quot;math/tex; mode=display&quot;&gt;\hat f(x) \leftarrow \hat f(x) +\lambda \hat f^b(x)&lt;/script&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\hat f(x)&lt;/script&gt;에도 새로운 tree를 더해주었으니, residual에도 그 영향을 빼주어 계산한다. (단순하게 업데이트된 &lt;script type=&quot;math/tex&quot;&gt;\hat f(x)&lt;/script&gt;의 잔차를 나타낸 것이다.)&lt;/p&gt;

        &lt;script type=&quot;math/tex; mode=display&quot;&gt;r_i \leftarrow r_i -\lambda\hat f^b(x_i)&lt;/script&gt;
      &lt;/li&gt;
      &lt;li&gt;
        &lt;p&gt;2번 과정을 반복하여, 업데이트되는 residual &lt;script type=&quot;math/tex&quot;&gt;r_i&lt;/script&gt;에 계속 적합을 한다. B번만큼.&lt;/p&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;이를 충분히 큰 수 B만큼 반복하면, 최종 모델은 2-2번에서 모든 tree들을 반영비율을 곱해 만들어진 모델이 된다. 즉 다음과 같다.&lt;/p&gt;

    &lt;script type=&quot;math/tex; mode=display&quot;&gt;\hat f(x)=\sum_{b=1}^B\lambda\hat f^b(x_i)&lt;/script&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;이를 보면 알 수 있지만, 처음에는 원래의 데이터 Y에 적합을 하지만, 그 이후에는 원래의 데이터 Y가 아닌 이전tree의 &lt;strong&gt;잔차에 적합&lt;/strong&gt;을 하고 있다. 따라서 이는 천천히 배우는(slowly learning)의 방법이다. classification tree의 경우도 비슷한 원리로 적용될 수 있으나, 조금 더 복잡하다. 여기서는 다루지 않는다.&lt;/p&gt;

&lt;p&gt;각각의 tree는 terminal node가 몇개 없는 크기가 매우 작은 tree일 수도 있다. 이는 hyper parameter &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;로 지정해준다. Boosting tree에는 다음과 같은 3개의 hyper paramter가 있다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tree의 갯수 &lt;script type=&quot;math/tex&quot;&gt;B&lt;/script&gt;&lt;/strong&gt; (split의 갯수가 아니다! 몇개의 tree를 만들지, 즉 몇번의 step을 돌지를 의미하는 파라미터). Boosting은 Variance를 줄이는데에 초점을 맞춘 bagging과 달리 bias를 조금씩 줄여나가고자 하는 방식이기에, &lt;strong&gt;&lt;script type=&quot;math/tex&quot;&gt;B&lt;/script&gt;가 클 경우 overfit이 될 수 있다.&lt;/strong&gt; Tree의 갯수 &lt;script type=&quot;math/tex&quot;&gt;B&lt;/script&gt; 역시 Cross-validation을 통해서 선택한다&lt;/li&gt;
  &lt;li&gt;각 모델을 그대로 더하는 것이 아니라, &lt;strong&gt;반영비율 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;&lt;/strong&gt;를 곱해주었다. 이를 &lt;strong&gt;shrinkage parameter&lt;/strong&gt;라고 불렀다. 이는 사실 각 step에서 배운 것을 얼마나 반영할지, 즉 learning rate와 비슷한 개념이다. 보통 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;는 0.01이나 0.001을 사용한다. &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 작으면 최적의 성능을 보이기 위해 더 큰 수의 &lt;script type=&quot;math/tex&quot;&gt;B&lt;/script&gt;가 필요할 것이다. (한번의 step에서 학습하는 비율이 적으니까.)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;각 tree내에서 split의 갯수 &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;&lt;/strong&gt;. 즉 boosting의 &lt;strong&gt;complexity&lt;/strong&gt;를 조절해주는 지표이다.(complexity가 높은 모델-&amp;gt;flexible한 모델-&amp;gt;variance는 크고 bias는 작고.)  Boosting은 이미 bias를 줄이는데에 목표를 두어 설계된 방법이기에, 큰 complexity를 필요로 하지 않는다. 역시나 overfit의 위험이 있기 때문이다. 때때로, &lt;script type=&quot;math/tex&quot;&gt;d=1&lt;/script&gt;, 즉 &lt;strong&gt;하나의 분류기준만이 있는 것이 제일 좋을때도&lt;/strong&gt; 있다. 이는 각 tree가 하나의 분류기준, 즉 하나의 변수기준만을 포함했다는 점에서, &lt;strong&gt;additive model&lt;/strong&gt;의 맥락에서 생각할 수도 있다. 이러한 맥락에서, &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;는 &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;개의 변수를  고려하게 되기 때문에 &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;를 interaction의 깊이라고 생각할 수도 있다. (선형회귀의 &lt;script type=&quot;math/tex&quot;&gt;X_1X_2&lt;/script&gt;항 처럼 여러 변수를 고려하는 tree가지가 만들어지기 때문.)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;다음은 random forest의 예시에 사용되었던 데이터에 boosting tree를 적합한 그림이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36580559-a98295fe-1860-11e8-832c-26bbfd1a96dd.PNG&quot; alt=&quot;tree13&quot; /&gt;&lt;/p&gt;

&lt;p&gt;사실 세 선모두 표준편차를 고려하면 유의미하게 다르지 않지만, 그래도 depth &lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;가 1인 모델이 더 잘하였다는 점이 눈에 띈다. Boosting은 이전 모델의 실수를 기반으로 만들어지는 모델이기에, 각각의 개별 tree는 작은 tree여도 충분한 경우가 많다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;여기서는 Boosting tree를 다루었지만, weak을 결합하여 strong을 만드는 boosting의 개념은 여러가지로 적용될 수 있다. 심지어는 Gradient에 적용될 수도 있는데, 목표와의 차이를 Loss function을 통해 정해주고 그로써 정량화된 목표와의 차이, Gradient를 토대로 함수자체를 update해주는 것이다. 대표적으로 Loss function이 L2(&lt;script type=&quot;math/tex&quot;&gt;\frac{1}{2}(y-f_i)^2&lt;/script&gt;)인 경우, 기울기는 &lt;script type=&quot;math/tex&quot;&gt;y-f_i&lt;/script&gt;이다. 이를 고치는 것을 다음 모델의 타겟으로 넘기는 것이다. 모델을 적합하고, 다시 잔차에 다른 모델을 적합하고, 다시 그 잔차에 모델을 적합하고…이러한 방식이 L2를 Loss로 설정한 경우의 Gradient Boosting이다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;p&gt;참고 :&lt;/p&gt;

&lt;p&gt;쩌는 슬라이드 : https://www.slideshare.net/freepsw/boosting-bagging-vs-boosting&lt;/p&gt;
</description>
        <pubDate>Fri, 23 Feb 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/02/23/ISL-Tree-Based-Methods_ch8.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/02/23/ISL-Tree-Based-Methods_ch8.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[ISL] 7장 -비선형모델(Local regression, Smoothing splines, GAM) 이해하기</title>
        <description>
&lt;p&gt;지금까지는 linear model들에 대해 다뤄왔다. standard linear model은 모델의 단순성으로 인해 해석과 추론이 쉽다는 장점이 있으나, 예측력이라는 중요한 부분에서 한계를 가진다. 선형모델은 현실의 문제에 선형성 가정을 하는 것이고, 쉽게 예상 가능하다시피 이는 몇몇의 경우 터무니 없는 가정이 되기도 하기 때문이다. 6장에서의 Lasso와 Ridge, PCR등을 통해 선형모델의 variance를 줄이는 방법을 다루웠으나, 이 역시 ‘선형’ 모델이라는 것에는 변함이 없다. 따라서 이번에는, 해석력은 가능한 잃지 않으며 &lt;strong&gt;선형가정을 완화시킬 수 있는 방법들&lt;/strong&gt;에 대해 다뤄보겠다. 이 장에 다룰 내용들을 미리 간략하게 소개하자면 다음과 같다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Polynomial regression은 기존의 변수의 다차항(&lt;script type=&quot;math/tex&quot;&gt;X^2,X^3&lt;/script&gt;등)을 추가하여 non-linear data에 적합을 할 수 있도록 선형모델을 확장한다&lt;/li&gt;
  &lt;li&gt;Step function은 변수를 &lt;script type=&quot;math/tex&quot;&gt;K&lt;/script&gt;개의 부분으로 나누어, 질적변수(즉, constant)를 만들어낸다. 이는 piecewise constant function(후에 자세히 설명)을 적합하는 효과를 같는다.&lt;/li&gt;
  &lt;li&gt;Regression splines은 위의 두 방식의 확장으로, 전체 &lt;script type=&quot;math/tex&quot;&gt;X&lt;/script&gt;를 똑같이 &lt;script type=&quot;math/tex&quot;&gt;K&lt;/script&gt;개의 범주로 나누되 각 범주내에서 다항적합을 하는 것이다. 이때 다항적합은 양 옆의 범주의 다항함수와 매끄럽게(smoothly) 연결되도록 한다는 제약이 있다. 적당한 범주로 나눌 경우, regression spline은 매우 유연한 적합을 가능하게 한다.&lt;/li&gt;
  &lt;li&gt;Smoothing splines는 regression splines과 비슷하지만, smooth penalty를 포함한(뒤에 자세히 설명한다) SSE식을 최소화하는 방식으로 적합을 한다.&lt;/li&gt;
  &lt;li&gt;Local regresson은 spline방식과 유사하지만 각 범주가 &lt;strong&gt;겹칠수 있다&lt;/strong&gt;는 점에서 다르다. 이러한 방식으로 더욱 유연한 적합을 가능하게 한다.&lt;/li&gt;
  &lt;li&gt;Generalized additive model은 위의 방식들을 &lt;strong&gt;여러개의 예측변수들&lt;/strong&gt;에 적용할 수 있게 하는 방식이다.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;위의 순서대로 앞에선 우선 예측변수가 1개인 경우(&lt;script type=&quot;math/tex&quot;&gt;X_1&lt;/script&gt;)에 대해 다룰 것이고, 이를 뒷부분에 가서 여러 변수들(&lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_p&lt;/script&gt;)로 확장할 것이다.&lt;/p&gt;

&lt;h2 id=&quot;71-polynomial-regression&quot;&gt;7.1 Polynomial Regression&lt;/h2&gt;

&lt;p&gt;non linear한 데이터에 적합하는 가장 기본적인 방식은 다항식을 추가하는 것이었다. 다항회귀를 식으로 나타내면 다음과 같다
&lt;script type=&quot;math/tex&quot;&gt;y_i=\beta_0+\beta_1x_i+\beta_2x_i^2+..\beta_dx_i^d+\epsilon_i&lt;/script&gt;&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\epsilon&lt;/script&gt;에도 i가 들어가 있다. 선형회귀에서는 모든 &lt;script type=&quot;math/tex&quot;&gt;\epsilon_i&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;N(0,1)&lt;/script&gt;로 동일하다 가정했기에 없던 것이고, 원래는 이렇게 표현. 물론 이경우도 mean0의 가정은 (주로)유효하다. 평균이 0인 수많은 다른 분포를 가질 수 있기에 i로 구분해서 쓴다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;각 계수들은 단순히 least square로 적합을 하면 된다. 이는 3장에서도 다뤘었지만, 이는 새로운 예측변수로써 다차항을 넣은것과 같다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;두번째 예측변수&lt;script type=&quot;math/tex&quot;&gt;X_2&lt;/script&gt;로써 단순히 &lt;script type=&quot;math/tex&quot;&gt;X_1&lt;/script&gt;을 제곱한 &lt;script type=&quot;math/tex&quot;&gt;X_1^2(=X_2)&lt;/script&gt;를 넣어주었다 보면 된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;일반적으로 3,4차항 이상까지는 포함시키지 않는다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36205902-62ddbbda-1188-11e8-9af7-b41190172a16.PNG&quot; alt=&quot;nonlin1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;왼쪽 그림의 파란 선은 Wage~Age의 자료에 대해 4차적합을 한것이고, 점선은 예측값의 분산을 통해 구한 신뢰띄(여기선 &lt;script type=&quot;math/tex&quot;&gt;\pm2*SE&lt;/script&gt;로 하였다)이다.  예측값, 즉 &lt;script type=&quot;math/tex&quot;&gt;\hat f(x_0)&lt;/script&gt;의 분산은 단순회귀에서 와 동일한 방식으로 구할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\hat f(x_0)=\hat\beta_0+\hat\beta_1x_i+\hat\beta_2x_i^2+\hat\beta_3x_i^3&lt;/script&gt;라고 하면 각 &lt;script type=&quot;math/tex&quot;&gt;\hat\beta_j&lt;/script&gt;의 variance와  각 쌍들간의 covariance를 구하면 된다. 이를 각 점에 대해 구하고 선으로 이은것이다.&lt;/p&gt;

&lt;p&gt;그림에서 wage이 소득 250을 기준으로 2개의 다른 집단, 즉 ‘고소득층’과 ‘저소득층’으로 유의미하게 나뉘어진다는 것을 알았다고 하자. 이 경우 역시나 다음과 같은 식으로 다항로지스틱 적합을 할수도 있다. 
&lt;script type=&quot;math/tex&quot;&gt;Pr(y_i&gt;250\lvert x_i)=\frac{exp(\beta_0+\beta_1x_i+\beta_2x_i^2+..\beta_dx_i^d)}{1+exp(\beta_0+\beta_1x_i+\beta_2x_i^2+..\beta_dx_i^d)}&lt;/script&gt;
이를 통해 적합된 확률(로지스틱의 경우 확률을 반환하였다는 것을 상기)이 오른쪽 그래프에 나와있다. 고소득층에 대한 데이터가 79개로 적었기에 95%신뢰구간이 매우 넓게 나왔다.&lt;/p&gt;

&lt;h2 id=&quot;72-step-functions&quot;&gt;7.2 Step Functions&lt;/h2&gt;

&lt;p&gt;다항함수를 사용하는 것은 예측변수의 &lt;strong&gt;전체&lt;/strong&gt; 구간에 non-linear형태를 부여하는 것이다. 반면 step function에서는 전체 X를 &lt;strong&gt;몇개의 구간으로&lt;/strong&gt; 나눈다. 그리고, 그 구간마다 일정한 &lt;strong&gt;상수&lt;/strong&gt;를 부여하는 것이다. 이는 사실 연속형인 반응변수Y를 몇개의 &lt;strong&gt;범주형 변수로&lt;/strong&gt; 바꿔서 부여하는것과 같다.&lt;/p&gt;

&lt;p&gt;사실상 구간을 나눠서 계산하는것과 같지만, 이를 식으로 나타내면 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486473-6c31826e-1716-11e8-8267-ecf2eef8dcd6.PNG&quot; alt=&quot;nonlin2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;전체 X를 K개의 범주로 나누고 각 범주에 대해 상수를 부여한것이다. 각 범주에 들어가면 1이고 나머지가 0이된다는 점에서 질적변수때 다루었던 dummy variable과 동일하게 이해해도 된다. intercept인 &lt;script type=&quot;math/tex&quot;&gt;\beta_0&lt;/script&gt;을 설정하였으므로 &lt;script type=&quot;math/tex&quot;&gt;C_0(x_i)&lt;/script&gt;가 들어가지 않았다. 이때 &lt;script type=&quot;math/tex&quot;&gt;\beta_0&lt;/script&gt;는 &lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
(X&lt;c_1) %]]&gt;&lt;/script&gt;인 데이터의 Y값의 평균이되고 나머지 &lt;script type=&quot;math/tex&quot;&gt;\beta_j&lt;/script&gt;는 (&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
c_j&lt;X&lt;c_{j+1} %]]&gt;&lt;/script&gt;)에 속한 데이터의 평균과 &lt;script type=&quot;math/tex&quot;&gt;\beta_0&lt;/script&gt;과의 차를 의미하게 된다.(질적변수 적합과 같은 맥락으로 이해하면 된다.) 이 식의 계수들 역시 &lt;strong&gt;least square로 적합하여&lt;/strong&gt; 구한다. 또한, 역시나 다음과 같은 식으로 logistic regressoin model에 적합을 할수도 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486467-6ba3d734-1716-11e8-9607-65ce3cf44892.PNG&quot; alt=&quot;nonlin3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이를 통해 적합한 두 그림은 다음과 같다. 3장에서 더미변수에 대한 variance를 구할 수 있듯이 같은 방식으로 신뢰구간을 구할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486470-6bdab43e-1716-11e8-9d22-1b5b4a728843.PNG&quot; alt=&quot;nonlin3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그러나, 왼쪽 그림을 보면 구간을 &lt;strong&gt;어떻게 자르느냐&lt;/strong&gt;에 따라 제대로 작동하지 못할 수 있음을 알 수 있다. 첫번째 구간의 경우 명확한 증가추세인데 이를 제대로 구간지어주지 않아 해당 추세를 반영해주지 못한 것이다. 한편 step function은 생물통계학이나 전염병학에서 자주 사용되는데, 주로 5살로 그룹을 지어 나눈다고 한다.&lt;/p&gt;

&lt;h2 id=&quot;73-basis-functions&quot;&gt;7.3 Basis Functions&lt;/h2&gt;

&lt;p&gt;사실, 앞서 다룬 polynomial과 piecewise-constant regression은 &lt;strong&gt;basis function&lt;/strong&gt;의 특별한 형태라고 할 수 있다. basis function는 다음과 같은 식으로 나타낼 수 있다.&lt;br /&gt;
&lt;script type=&quot;math/tex&quot;&gt;y_i=\beta0+\beta_1b_1(x_i)+\beta_2b_2(x_i)+..+\beta_Kb_K(x_i)+\epsilon_i&lt;/script&gt;
Step function과 비슷한 형태인데, &lt;script type=&quot;math/tex&quot;&gt;x_i&lt;/script&gt;에 대한 &lt;strong&gt;여러 함수들&lt;/strong&gt;로 식을 표현하는 것이다.&lt;/p&gt;

&lt;p&gt;이때 각 함수 &lt;script type=&quot;math/tex&quot;&gt;b_k(x_i)&lt;/script&gt;가 어떠한 형태일지(1차항만인지 2차항도 포함한 형태인지 등)는 물론 분석자가 미리 정해놓는다. 다양한 &lt;script type=&quot;math/tex&quot;&gt;b_k(x_i)&lt;/script&gt;의 형태에 따라 basis function은 여러가지 개념을 포함할 수 있다. &lt;script type=&quot;math/tex&quot;&gt;b_j(x_i)=x_i^j&lt;/script&gt;라고 설정하면 polynomial regression(&lt;script type=&quot;math/tex&quot;&gt;y_i=\beta_0+\beta_1x_i+\beta_2x_i^2+..\beta_dx_i^d+\epsilon_i&lt;/script&gt;)이 되는것이고, &lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
b_j(x_i)=I(c_j&lt;x_i&lt;c{j+1}) %]]&gt;&lt;/script&gt;라면 piecewise constant function(&lt;script type=&quot;math/tex&quot;&gt;y_i=\beta_0+\beta_1C_1(x_i)+\beta_2C_2(x_i)+..\beta_KC_K(x_i)+\epsilon_i&lt;/script&gt;)이 되는 것이다. 또한 이 &lt;script type=&quot;math/tex&quot;&gt;b_i(x_i)&lt;/script&gt;를 각각의 예측변수라고 생각하면, standard linear model로도 생각할 수 있다. 따라서 회귀계수의 standard error, F-통계량 등 3장에서 다루었던 모든것을 역시나 적용할 수 있다. 다음으로는 basis function에서 대표적인, regression splines를 보겠다.&lt;/p&gt;

&lt;h2 id=&quot;74-regression-spines&quot;&gt;7.4 Regression Spines&lt;/h2&gt;

&lt;p&gt;앞서 살펴본 polynomial regression과 piecewise constant regression을 확장한 유연한 형태의 basis function을 살펴보자&lt;/p&gt;

&lt;h3 id=&quot;74-1-piecewise-polynomials&quot;&gt;7.4-1 Piecewise Polynomials&lt;/h3&gt;

&lt;p&gt;전체 X의 범위에 고차항의 다항적합을 하는 것이 아닌, 몇개의 범주의 범위에 (비교적) 낮은 차수의 적합을 따로따로 하는 것이 piece wise polynomial regression이다. 예를 들어, 각 범주마다 &lt;script type=&quot;math/tex&quot;&gt;y_i=\beta_{0,k}+\beta_{1,k}x_i+\beta_{2,k}x_i^2+\beta_{3,k}x_i^3+\epsilon_i&lt;/script&gt;를 적합하는 것이다. (이때 물론 각 회귀계수는 각 범주마다 다르다. 이를 명시하고자 0,k라고 표현했다) 각 범주가 바뀌는 지점을 knots라고 부른다.&lt;/p&gt;

&lt;p&gt;예를 들어 knot가 상수c라는 지점에서의 단하나 뿐이라면, piecewise cubic polynomial식은 다음과 같다. (cubic은 3차라는 뜻이다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486465-6b6fe564-1716-11e8-8f1f-3b634091f6f4.PNG&quot; alt=&quot;nonlin4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
(x&lt;c) %]]&gt;&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;(x\ge c)&lt;/script&gt;의 2개의 subset에 두번의 다항적합을 한것이라 보면 된다. 역시 각 계수들은 least sqaure로 적합한다. 이때, 모델의 자유도는 추정할 계수들의 수, 즉 4개씩 2범주이므로 df=8이 된다.&lt;/p&gt;

&lt;p&gt;그러나, 해당 조건만으로는 다음과 같은 모델이 만들어진다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486460-6ae9f17a-1716-11e8-8c02-8ce4b3531244.PNG&quot; alt=&quot;nonlin5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Age=50이라는 knot에서 선이 전혀 연결되지 않는 비합리적인 모델이 만들어져버린다. 49.999..세까지는 Wage가 110달러이다가, 50세가 된 직후 160달러가 될수는 없기 때문이다. 이에 따라 추가적인 방법이 사용된다.&lt;/p&gt;

&lt;h3 id=&quot;74-2-constraints-and-splines&quot;&gt;7.4-2 Constraints and Splines&lt;/h3&gt;

&lt;p&gt;Age=50에서 wage가 갑자기 50가까지 뛰는 것은 비합리적이다. 위의 그림처럼 비합리적인 모델이 나오지 않게 하기 위해, 각 적합된 곡선이 서로 연결(continuous)되어야 한다는 제약을 추가한다. 이에 따라 50부근의 선들을 연결해주었다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;어떻게 해당 제약을 줄 수 있을까? 뒤에서 truncated power basis function부분에 나온다. 여기서는 ‘연속’만의 제약이기에, &lt;script type=&quot;math/tex&quot;&gt;h(x,50)=(x-50)_{+}&lt;/script&gt;의 제약이 들어갈 것이다. 뒤에 나올 truncated power basis function부분을 읽고 돌아와보면 이해가 가능하다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486456-6aaebe84-1716-11e8-8d93-9e9ae6b9838c.PNG&quot; alt=&quot;nonlin6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그러나 여전히 V자형의 꺾인 선이 비합리적으로 보인다. (지금은 완만한 V자이지만, 해당 제약만을 가지곤 급변하는 V자형태의 함수가 나올 수도 있다.)&lt;/p&gt;

&lt;p&gt;이에따라, 2개의 새로운 제약을 추가한다. Age=50이라는 knots에서, &lt;strong&gt;1차미분, 2차미분이 가능해야&lt;/strong&gt; 한다는 것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(왜 2차까지 일까? 사람의 눈에 매끄럽게 보이기 위해선 d-1차까지 continuous derivative, 즉 연속이고 미분가능해야 한다고 한다.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이는 Age=50이라는 점에서 continous뿐 아니라 매끄러워야 한다는 제약을 추가한 셈이다. 이의 결과는 다음과 같이 매끄러운 연결된 선이 나온다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486453-6a70c4a8-1716-11e8-8295-6d69ee02806c.PNG&quot; alt=&quot;nonlin7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;각각의 제약은, 자유도(degree of freedom)을 하나 잃게 된다는 것을 의미한다(!) 따라서 맨 위의 piecewise cubic에서는 자유도가 8(추정하고자 하는 회귀계수의 수)이었지만, 3개의 제약(knots에서 1.continous여야 한다, 2. 1차미분 가능하다, 3. 2차미분 가능하다.)으로 인해, Cubic Spline의 함수는 자유도가 5이다. 해당 경우 K개의 knot에 따른 자유도는 (4+K)일 것이다. (&lt;script type=&quot;math/tex&quot;&gt;\because 4*(K+1)-3K&lt;/script&gt;)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;d&lt;/script&gt;차 적합을 하며 &lt;script type=&quot;math/tex&quot;&gt;K&lt;/script&gt;개의 knots가 있는 regressoin spline의 경우 &lt;script type=&quot;math/tex&quot;&gt;(d+1)*(K+1)-(d)K&lt;/script&gt;의 자유도를 갖는다 보면 된다. K개의 knot가 있으니 구간은 K+1개로 나뉘고, 각 knot마다 ‘연속 + d-1차까지 미분가능’ 이라는 제약이 들어간다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;위의 결과를 일반화하면, d차의 spline적합은 &lt;strong&gt;1)&lt;/strong&gt; 각 piecewise에서 d차 다항적합을 하고, &lt;strong&gt;2)&lt;/strong&gt; 각 knot에서 &lt;strong&gt;(d-1)차까지의 미분이 가능&lt;/strong&gt;, 즉 매끄럽게 연속적이어야 한다는 제약이 붙는다.&lt;/p&gt;

&lt;h3 id=&quot;74-3-the-splines-basis-representation&quot;&gt;7.4-3 The Splines Basis Representation&lt;/h3&gt;

&lt;p&gt;그럼, 대체 어떻게 d차 적합을 하면서도 d-1차까지의 미분이 가능하다는 제약을 달성할 수 있을까?&lt;/p&gt;

&lt;p&gt;이는 앞에서 다루었던 Basis function의 형태를 통해 알 수 있다. K개의 knots가 있는 cubic spline도 역시 적절한  &lt;script type=&quot;math/tex&quot;&gt;b_1,..,b_{K+3}&lt;/script&gt;가 선택된다면 다음과 같이 basis function의 형태로 표현할 수 있다.
&lt;script type=&quot;math/tex&quot;&gt;y_i=\beta0+\beta_1b_1(x_i)+\beta_2b_2(x_i)+..+\beta_{K+3}b_{K+3}(x_i)+\epsilon_i&lt;/script&gt;
그럼 cubic(3차) spline을 어떻게 저렇게 표현할 수 있을까? 가장 대표적이고 직접적인 방법으로는 &lt;script type=&quot;math/tex&quot;&gt;x,x^2,x^3&lt;/script&gt;만을 가지고 있는 삼차 다항식에서 각 knot마다 truncated power basis function을 추가하는 것이다.&lt;/p&gt;

&lt;p&gt;truncated power basis function(절단 멱 기저함수…그냥 영어로 표현하자)는 다음과 같이 정의된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486452-6a3dbbda-1716-11e8-849c-932761aa4ee1.PNG&quot; alt=&quot;nonlin8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\xi&lt;/script&gt;는 knot를 의미한다. 즉 &lt;script type=&quot;math/tex&quot;&gt;\xi&lt;/script&gt;에서 2차 미분(‘d-1’차 미분) 까지 미분이 가능함을 의미한다. 따라서 K개의 knots가 있을때 이를 다음과 같이 표현하게 된다. 조금 전에 나왔던 식과 비교해서 이해하면 된다.
&lt;script type=&quot;math/tex&quot;&gt;Y=\beta0+\beta_1X+\beta_2X^2+\beta_3X^3+\beta_4h(X,\xi_1)+..+\beta_{K+3}h(X,\xi_K)+\epsilon_i&lt;/script&gt;&lt;/p&gt;
&lt;blockquote&gt;
  &lt;p&gt;사실 truncated power basis function의 형태를 보면 알수 있지만 단순히 knot뒤에 새로운 식(여기서는 &lt;script type=&quot;math/tex&quot;&gt;\beta(x-\xi)^3&lt;/script&gt;)이 점차 추가되는 형태이다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;따라서 K개의 knots가 있을때의 cubic spline적합은,  &lt;script type=&quot;math/tex&quot;&gt;X,X^2,X^3,h(X,\xi_1),...,h(X,\xi_K)&lt;/script&gt;의 &lt;strong&gt;K+3개의 예측변수를 가지고 least square적합을 한 것&lt;/strong&gt;이 된다. 물론 절편항도 필요하니(위의 식에서 &lt;script type=&quot;math/tex&quot;&gt;\beta_0&lt;/script&gt;부터 시작한거) 총 &lt;strong&gt;K+4개의 회귀계수를 추정&lt;/strong&gt;해야 한다. 이러한 이유로 K개의 knots가 있는 cubic spline에서 자유도가 K+4개 인것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;least square적합에 대해 좀더 설명해보자면, &lt;script type=&quot;math/tex&quot;&gt;X,X^2,X^3,h(X,\xi_1),...,h(X,\xi_K)&lt;/script&gt;는 모두 정했으니 이제 &lt;script type=&quot;math/tex&quot;&gt;\beta_j&lt;/script&gt;들의 수치를 정하면 되는데, 이는 
&lt;script type=&quot;math/tex&quot;&gt;\sum_{i=1}^n(y_i-\beta_0-\sum_{j=1}^{K+3}\beta_jb_j(x))^2&lt;/script&gt;
이렇게 구한다는 의미이다. &lt;a href=&quot;http://www.stat.cmu.edu/~ryantibs/advmethods/notes/smoothspline.pdf&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;그러나 이렇게 구한 cubic spline은 양 끝단 에서 예측의 신뢰구간이 넓어지게 된다. 즉, 예측의 정확도가 떨어지는 것이다. 사실 양끝단의 경우 모델의 분산이 커지는 것은 어느 모델이든 통용되지만, 이 경우 non-linear적합을 하고자 하였으므로 그 분산이 더 커지게 된다.(flexibility가 클수록 Variance도 크다는것 상기). 다항적합의 경우 양끝단에서 모형이 지나치게 급변하는 것은 고질적인 문제이다. 따라서 데이터의 양끝단, 즉 가장 왼쪽의 knot보다도 왼쪽에 있는 데이터와, 가장 오른쪽끝쪽에 있는 knot보다 오른쪽에 있는 데이터의 경우 &lt;strong&gt;선형 적합&lt;/strong&gt;을 하여 이러한 문제를 완화하고자 하기도 한다. 이를 &lt;strong&gt;Natural Cubic Spiline&lt;/strong&gt;이라 부른다. 아래의 그림을 보면, natural cubic spline의 경우가 양끝단에서 신뢰구간의 범위가 비교적 더 좁아졌음을 알 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486451-6a084090-1716-11e8-9a75-7bd49379e59f.PNG&quot; alt=&quot;nonlin9&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이 경우 양 끝단에선 3차적합이 아닌 1차적합을 하기에, 각각 자유도 2씩을 잃어 K+4-2X2, 즉 K의 자유도를 갖게 된다.&lt;/p&gt;

&lt;h3 id=&quot;74-4-choosing-the-number-and-location-of-the-knots&quot;&gt;7.4-4 Choosing the Number and Location of the Knots&lt;/h3&gt;

&lt;p&gt;그렇다면 가장 중요한 문제인, 어디에, 또 몇개의 knot를 설정해야 하는지의 문제가 남았다. knot를 무수히 많이 설정하면 모델이 지나치게 flexible해지는 것은 자명한 일이다. 따라서 데이터가 빠르게 변동하는, 그래서 flexible한 형태가 필요해 보이는 지점에선 많은 knot를 배정하고, 상대적으로 안정되보이는 지점에선 적은수의 knot를 지정하는 방식을 사용할 수 있을 것이다.&lt;/p&gt;

&lt;p&gt;해당 방법 역시 좋은 접근이 될 수 있지만, 예측 변수가 많아질 수록 어느부분에서 flexible한 함수가 필요할지 직관적으로 알기 힘들때가 많다. 따라서 좀더 알고리즘적으로 적용될 수 있는 방식을 알아보자. 적정한 degrees of freedom을 설정하고 그에 따라 &lt;strong&gt;균등한 qunatile&lt;/strong&gt;에 knot를 배정하는 것이다. 다음 그림은, 자유도5를 지정한 경우의 그림이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486450-69cc894c-1716-11e8-8a56-0e81c3dac086.PNG&quot; alt=&quot;nonlin10&quot; /&gt;&lt;/p&gt;

&lt;p&gt;자유도 4를 지정한 경우 natural cubic의 knot는 5개이다. 따라서 boundary knot 2개를 제외하고, 3개의 knot들이 quantile에 따라 자동으로 생긴것을 볼 수 있다. 즉, 25th, 50th, 75th quantile들이 knot로써 배정된 것이다. 이렇게 함으로써, 자료들이 많은 부분에선 많은 knot들을 배정하여 그 자료들이 잠재적으로 가질수 있는 non-linear형태를 반영하고, 자료들이 많지 않은 부분에선 적은 수의 knot들을 배정하려는 전략을 어느정도 달성하게 된다. &lt;a href=&quot;https://stats.stackexchange.com/questions/7316/setting-knots-in-natural-cubic-splines-in-r&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(이때의 자유도 4는 intercept를 제외한 것이라, 이전에 다뤘던 개념대로면 자유도5이다.)&lt;/p&gt;

  &lt;p&gt;(또한, boundary knot는 우리가 관심있는 데이터의 범위를 지정해주기 위한 것을, 논의되지 않았으나, 여기선 df와 knot수의 관계보다는 df를 지정해주어 해당되는 knot수를 quantile에 맞추어 자동배정해준다는 사실에 주목하자.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;그럼 결국 몇개의 knot들을 설정할지, 즉 자유도를 몇으로 설정할지를 정해야 하는데, 이는 역시나 앞에서 나왔던 Cross-validation으로 결정한다. CV를 통해 본 CV error값이 가장 낮은 자유도의 갯수를 사용하는 것이다.&lt;/p&gt;

&lt;h3 id=&quot;74-5-comparison-to-polynomial-regression&quot;&gt;7.4-5 Comparison to Polynomial Regression&lt;/h3&gt;

&lt;p&gt;많은 경우 regression spline이 다항회귀보다 좋은 결과를 가져오는데, flexible하기 위해선 지나치게 차수를 높여가야 하는 반면에(&lt;script type=&quot;math/tex&quot;&gt;X^{15}&lt;/script&gt;차까지 있는 다항회귀를 생각해보자) regression spline은 차수는 유지하면서 knot의 수를 늘림으로써 flexibility를 늘릴 수 있기 때문이다. 따라서 대부분의 경우 regressoin spline이 더욱 &lt;strong&gt;안정된 추정&lt;/strong&gt;을 가능하게 한다. 다음은natural cubic spline과 15차항 적합을 한 다항회귀를 비교한 그림이다. 15차항 적합은 지나친 flexibility로 인해 끝쪽에서 회귀선이 비합리적으로 요동치는 것을 볼 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486449-6991b966-1716-11e8-9be7-9deee4766b52.PNG&quot; alt=&quot;nonlin11&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;75-smoothing-splines&quot;&gt;7.5 Smoothing Splines&lt;/h2&gt;

&lt;h3 id=&quot;75-1-an-overview-of-smoothing-splines&quot;&gt;7.5-1 An Overview of Smoothing Splines&lt;/h3&gt;

&lt;p&gt;smoothing spline은 좀더 근본적인 개념에서 접근을 한 방식이다. 우리가 원하는 함수는, 관측된 데이터에 잘 맞는, 즉 &lt;script type=&quot;math/tex&quot;&gt;RSS=\sum_{i=1}^n(y_i-g(x_i))^2&lt;/script&gt;를 최소화 하는 함수 &lt;script type=&quot;math/tex&quot;&gt;g(x_i)&lt;/script&gt;일 것이다. 그러나 만약 함수g에 아무런 제약이 없다면, RSS를 최소화하자는 목표만으로는 모든 관측된 데이터 완벽하게 적합하는 n-1차 식이 만들어져 버릴 것이다.(선형회귀와 헷갈리지 말자. 선형회귀는 함수g의 형태를 &lt;script type=&quot;math/tex&quot;&gt;(\beta_0+\beta_1x_i)&lt;/script&gt;로 제한하였다.) 따라서 우리는, &lt;strong&gt;1)&lt;/strong&gt; RSS를 작게 만들면서도 &lt;strong&gt;2)&lt;/strong&gt; 어느정도의 smooth를 가지는 함수 &lt;script type=&quot;math/tex&quot;&gt;g(x_i)&lt;/script&gt;를 찾는 것을 목표로 해야한다.&lt;/p&gt;

&lt;p&gt;함수 g의 smooth를 보장하는 방식은 여러개가 있지만, 대표적으로 다음의 식을 최소화함으로써 찾는 방법이 있다.
&lt;script type=&quot;math/tex&quot;&gt;\sum_{i=1}^n(y_i-g(x_i))^2+\lambda \int g''(t)^2dt&lt;/script&gt;
위 식의 앞부분은 우리가 아는 RSS이며 이때 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;는 양수인 하이퍼파라미터이다. 위 식을 최소화하도록 하는 함수g가 바로 smoothing spline인 것이다.&lt;/p&gt;

&lt;p&gt;식을 보면서 느낌이 왔겠지만, 이는 &lt;strong&gt;“Loss+Penalty”&lt;/strong&gt;의 형태를 가진 식이다. 6장의 Ridge와 Lasso에서도 이미 한번 접하였다. &lt;strong&gt;데이터에 잘 적합하도록 하는 Loss&lt;/strong&gt;와, &lt;strong&gt;지나치게 변동이 크지 않도록 하는 Penalty&lt;/strong&gt;가 합해진 것이다.&lt;/p&gt;

&lt;p&gt;그럼 왜 &lt;script type=&quot;math/tex&quot;&gt;g''(t)^2&lt;/script&gt;일까? 일차도함수의 경우 t에서의 기울기를 의미하고, 이차도함수의 경우 그 기울기의 변화를 의미한다. 따라서 2차도함수는 얼마나 급격하게 변하는지(roughness)를 의미하는 것으로 받아들일 수 있는 것이다. (직선의 경우 2차도함수값은 0이라는 것이 위의 내용을 이해하는데 도움을 준다.) 이차도함수값의 ‘절대값’이 크다면(기울기가 급격하게 줄어드는것도 roughness니까, ‘-‘도 고려해야 한다) 이는 t지점에서 함수가 꾸불꾸불하다는 것을 의미한다. 따라서 이차도함수에 &lt;strong&gt;제곱&lt;/strong&gt;을 해준다.&lt;/p&gt;

&lt;p&gt;이를 모든 t의 범위에 대해 &lt;script type=&quot;math/tex&quot;&gt;\int&lt;/script&gt;를 해줌으로써, 전체 t의 범위에서의 &lt;script type=&quot;math/tex&quot;&gt;g'(t)&lt;/script&gt;의 변화량을 의미할 수 있다. 즉 식 &lt;script type=&quot;math/tex&quot;&gt;\lambda \int g''(t)^2dt&lt;/script&gt;은 함수g를 smooth하게 되도록 만드는 역할을 한다. 당연히 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;값이 커질수록 g는 더욱 smooth하게 될것이다.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 0이라면 모든 데이터를 지나가는 함수g가 만들어질것이고, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 무한히 크다면 g는 굴곡이 전혀 없는, 즉 선형이 될것이고, 이 경우 g는 &lt;strong&gt;선형회귀와 같아진다&lt;/strong&gt;. 또 적당한 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;값에 대해서는 적당히 train data에도 적합되면서 적당한 smooth정도를 가지고 있는 함수가 만들어질 것이다. 따라서 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;는 bias-variance trade-off의 정도를 조절하는 값이라 볼 수 있다.&lt;/p&gt;

&lt;p&gt;사실, 해당 값을 최소화하는 함수는 &lt;script type=&quot;math/tex&quot;&gt;x_1,..,x_n​&lt;/script&gt;에서 2차미분이 가능한 knot를 갖으며 양 끝단에선 linear한, 즉 natural cubic spline과 같게 된다.(받아들이자) 위의 조건을 가진 natural cubic spline과 완전히 값까지 똑같은 함수가 나오는 것이 아니고, 이의 &lt;strong&gt;shrink된 버전의 함수&lt;/strong&gt;가 나온다. 얼마나 shrinkage될 것인지를 &lt;script type=&quot;math/tex&quot;&gt;\lambda​&lt;/script&gt;로써 정하는 것이다. 즉, Smoothing spline은 &lt;strong&gt;모든 input에 대해 knot를 가지고 있는 natural cubic spline&lt;/strong&gt;을 &lt;strong&gt;shrinkage penalty&lt;/strong&gt;를 hyperparameter &lt;script type=&quot;math/tex&quot;&gt;\lambda​&lt;/script&gt;를 통해 조절해서 variance를 줄여주는 모델로도 볼 수 있는 것이다.(!)&lt;/p&gt;

&lt;h3 id=&quot;75-2-choosing-the-smoothing-paramter-lambda&quot;&gt;7.5-2 Choosing the Smoothing Paramter $\lambda$&lt;/h3&gt;

&lt;p&gt;smoothing spline이 ‘모든’ &lt;script type=&quot;math/tex&quot;&gt;x_i&lt;/script&gt;에서 knots를 갖는 natural cubic spline이라면, 이는 너무 큰 degrees of freedom, 즉 너무 큰 flexibility를 갖는 것이 아닐까? 그러나 여기서 새로운 개념인 effective degrees of freedom, 즉 실질적인 자유도가 등장한다. smoothing spline에서는 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 smooth 정도를 조절해주므로, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;에 따라 실질적인 &lt;strong&gt;effective degrees of freedom&lt;/strong&gt;이 변화한다. 구체적으로, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 0에서 &lt;script type=&quot;math/tex&quot;&gt;\infty&lt;/script&gt;까지 변할때 effective degrees of freedom(&lt;script type=&quot;math/tex&quot;&gt;df_\lambda&lt;/script&gt;로 표현한다.)은 n에서 2까지 변한다.&lt;/p&gt;

&lt;h4 id=&quot;갑자기-왠-effective-degrees-of-freedom&quot;&gt;갑자기 왠 effective degrees of freedom?&lt;/h4&gt;

&lt;p&gt;왜 기존의 자유도가 아닌 effective degrees of freedom을 사용하는것일까?&lt;/p&gt;

&lt;p&gt;기존의 자유도는 자유로운 parameter의 갯수로써, 계수들의 수를 의미했었다. smoothing spline은 n개의 parameter를 가지고 있으므로 명목상 n의 자유도를 가지고 있지만, 이 n개의 parameter들이 이미 shrink되도록 &lt;strong&gt;constrain&lt;/strong&gt;을 받고 있다. 따라서 같은 n개의 parameter이더라도 shink의 정도에 따라 flexibility가 다르기에, 이를 따로 표현해주고자 하는 것이다.&lt;/p&gt;

&lt;p&gt;effective degrees of freedom은 어떻게 구할까? 이는 선형대수적인 개념이 들어가게 된다. 간략하겐 다음과 같은 과정을 통해 구할 수 있다.
&lt;script type=&quot;math/tex&quot;&gt;\hat g_\lambda=\boldsymbol S_\lambda \boldsymbol y&lt;/script&gt;
여기서 &lt;script type=&quot;math/tex&quot;&gt;\hat g&lt;/script&gt;는 &lt;script type=&quot;math/tex&quot;&gt;x_1,..,x_n&lt;/script&gt;까지에 대해 적합된 &lt;strong&gt;n개의 적합값&lt;/strong&gt;이다.  &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol S_\lambda&lt;/script&gt;는 y를 적합값으로 표현하는 n X n의 matrix이다.  이때, &lt;script type=&quot;math/tex&quot;&gt;df_\lambda=tr(\boldsymbol S_\lambda)&lt;/script&gt;이다. 즉 대각원소들의 합이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;matrix notation으로 표현하면 선형회귀에서 처럼 적합값을 y에 대한 식으로 나타낼 수 있는데, 이때
&lt;script type=&quot;math/tex&quot;&gt;\hat \beta=(G^TG+\lambda\Omega)^{-1}G^Ty&lt;/script&gt;
로 나타낼 수 있다. 따라서 적합값은 &lt;script type=&quot;math/tex&quot;&gt;g(x)^T\hat \beta=g(x)^T(G^TG+\lambda\Omega)^{-1}G^Ty&lt;/script&gt;로 나타낼 수 잇고, 이를 정리하여 &lt;script type=&quot;math/tex&quot;&gt;S_{\lambda}&lt;/script&gt;라고 notation한 것이라 볼 수 있다. 보다 자세한 설명은 &lt;a href=&quot;https://www.hds.utc.fr/~tdenoeux/dokuwiki/_media/en/splines.pdf&quot;&gt;참고&lt;/a&gt;의 54쪽.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;lambda를-정해보자&quot;&gt;$\lambda$를 정해보자&lt;/h4&gt;

&lt;p&gt;regression spline가 다르게 smoothing spline은 모든 관측치 &lt;script type=&quot;math/tex&quot;&gt;x_i&lt;/script&gt;에 knot를 두기에 knot의 갯수나 위치를 지정할 문제가 사라진다. 그러나, 여기선 shrink의 정도인  &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 몇으로 할것인지의 문제가 남아있다. 이는 역시나, Cross-validation을 통해 구할 수 있다. 놀랍게도, smoothing spline에서 LOOCV는 다음과 같은 한번의 적합을 통해서 구할 수 있다. 식의 맨 오른쪽 등식을 보자.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486448-695c0e2e-1716-11e8-8e66-47d147911bce.PNG&quot; alt=&quot;nonlin12&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이는  마치 least square에서 LOOCV가 leverage statistics를 통해 한번에 구할 수 있던 식과 매우 유사하다. least square에서의 LOOCV식 상기&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486446-691fc89c-1716-11e8-9626-7111fccd111f.PNG&quot; alt=&quot;nonlin13&quot; /&gt;&lt;/p&gt;

&lt;p&gt;참고로 위 식은 least square에서 통용될 수 있기에, 앞서 다루었던 regression spline이나 least square적합을 이용하는 다른 basis function의 LOOCV에도 사용될 수 있다.&lt;/p&gt;

&lt;p&gt;다시 smoothing spline으로 돌아와, LOOCV를 통해 적정한 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;값을 결정할 수 있다. &lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486445-68adb23e-1716-11e8-88eb-6949dedc59ab.PNG&quot; alt=&quot;nnonlin1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위 그림은 임의로 지정한 큰effective degrees of freedom, 즉 df=16의 선과 LOOCV를 통해 정한 선의 차이를 보여주고 있다.(smoothing spline에서는 degrees of freedom이 아닌 effeictive degrees of freedom을 쓴다! 기존의 df는 어차피 둘다 같다.) 이때, LOOCV를 통해 결정된 6.8df가 거의 차이가 없으면서도 덜 꼬불꼬불한 선을 나타냄을 알 수 있다.&lt;/p&gt;

&lt;h2 id=&quot;76-local-regression&quot;&gt;7.6 Local Regression&lt;/h2&gt;

&lt;p&gt;Local regression은 말그대로 ‘지역적인’ regression이다. 즉, 각 특정 target point &lt;script type=&quot;math/tex&quot;&gt;x_0&lt;/script&gt;에서 그 &lt;strong&gt;근처의 관측자료&lt;/strong&gt;들만을 토대로 적합을 시켜 flexible한 적합을 하고자 하는 접근방식이다.&lt;/p&gt;

&lt;p&gt;특정 target point &lt;script type=&quot;math/tex&quot;&gt;x_0&lt;/script&gt;에서 Local Regression의 대표적인 적합방식은 다음과 같다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;전체 데이터중 &lt;script type=&quot;math/tex&quot;&gt;x_0&lt;/script&gt;에서 가까운 k개의 자료 &lt;script type=&quot;math/tex&quot;&gt;x_i&lt;/script&gt;들을 모은다. (&lt;script type=&quot;math/tex&quot;&gt;s=k/n&lt;/script&gt;으로 전체의 &lt;script type=&quot;math/tex&quot;&gt;s&lt;/script&gt;%만큼 모은다고 표현하기도 한다.)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;가까운 k개의 자료(nearest neighbor)들만이 가중치를 갖고, 나머지는 가중치가 0이 되도록 가중치 &lt;script type=&quot;math/tex&quot;&gt;K_{i0}=K(x_i,x_0)&lt;/script&gt;을 설정한다.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;앞서 언급한 가중치를 곱해주는, weighted least square regression을 한다. 이를 식으로 나타내면 다음의 식을 최소화하는 &lt;script type=&quot;math/tex&quot;&gt;\hat \beta_0&lt;/script&gt;과 &lt;script type=&quot;math/tex&quot;&gt;\hat \beta_1&lt;/script&gt;을 구하는 것이다.
&lt;script type=&quot;math/tex&quot;&gt;\sum_{i=1}^nK_{i0}(y_i-\beta_0-\beta_1x_i)^2&lt;/script&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;최종적으로 &lt;script type=&quot;math/tex&quot;&gt;x_0&lt;/script&gt;에서의 적합값은 &lt;script type=&quot;math/tex&quot;&gt;\hat f(x_0)=\hat \beta_0+\hat \beta_1x_0&lt;/script&gt;이 된다.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;이를 모든 point에 대해 반복하는 것이다. 다음의 그림은 Local regression을 통해 적합한 그림이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486444-68763e58-1716-11e8-9082-f707b793c96f.PNG&quot; alt=&quot;nnonlin2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;각각의 x수준에서의 적합값을 찾기위해, 전체의 s부분 만큼의 점들을 골라내고,(그림에서 빨간점으로 표시) 이들을 가까운 순서대로 weight를 부여해서, (그림에서 노란색 종모양 그림으로 표시) 해당 x수준에서의 적합값을 만드는 것이다. 그림에선 x=0.05와 x=0.45의 두 값만을 계산하였지만, 이를 가능한 모든 x수준에 대해 계산하는 것이다. 각 적합값을 구할때마다 traing data가 필요하기에, memory based 방식이라고도 지칭된다.&lt;/p&gt;

&lt;p&gt;이때 위의 알고리즘에서, 2번에서의 가중치 &lt;script type=&quot;math/tex&quot;&gt;K_{i0}&lt;/script&gt;는 각 &lt;script type=&quot;math/tex&quot;&gt;x_0&lt;/script&gt;에 따라 달라질 수도 있고, 3번에서의 least square식이 linear regressoin식이 아니라 다항식일수도 있는 등 여러 변화를 줄 수 있다. 그러나 이중 가장 중요한 차이를 불러오는 변화는, 역시나 얼만큼의 nearest neighbor를 볼것인지, 즉 s가 몇%인지에 따른 변화이다. 작은 수준의 s는 전체 중 작은 부분만을 보는것, 즉 더욱더 지역적인 regression이 될것이고 더욱 꾸불꾸불한 선이 나올 것이다. 반대로 큰 s값은 거의 전체의 데이터를 다 보는 선을 만들어 낼것이다. 역시나 적절한 s는 Cross-validation을 통해 찾는다.&lt;/p&gt;

&lt;p&gt;local regression은 여러 방식으로 사용되는데, 여러개의 변수가 있는 경우, 특히 다른 변수에서는 전역적이지만, 시간변수는 국소적인 경우 최근에 들어온 데이터를 처리할때 사용된다.(시간에 한해서만 local 적합을 하여 적합값을 만든다) 또한 여러 변수가 있을때는 단순히 다차원에서의 nearest neighbor를 모아서 그 데이터로 다중회귀를 하면된다. 그러나 3장의 Nearest-neighbor regression에서와 마찬가지로 차수가 &lt;strong&gt;3,4차 이상으로 갔을때&lt;/strong&gt;는 &lt;script type=&quot;math/tex&quot;&gt;x_0&lt;/script&gt;에 유의미하게 가까운 nearest neighbor를 찾기가 힘들기에 성능이 안좋아지게 된다.&lt;/p&gt;

&lt;h2 id=&quot;77-generalized-additive-models&quot;&gt;7.7 Generalized Additive Models&lt;/h2&gt;

&lt;p&gt;지금까지는 예측변수가 하나인 경우의 non linear한 적합을 해보는, 단순 선형회귀의 확장을 다루었다. 그러나 해당 논의는 변수가 여러개일 때도 가능하다. 이번에는 변수가 여러개, 즉 다중선형회귀에 대한 확장을 다뤄보자.&lt;/p&gt;

&lt;p&gt;Generalized Additive Models(GAM)은 기존의 선형모델에서 &lt;strong&gt;가법성은 유지하면서도&lt;/strong&gt; 각 변수에 non-linear한 적합을 가능하게 하는 방법이다. 이는 기존의 선형모델이 그렇듯이 역시나 질적변수와 양저견수에 모두 적합이 가능하다. 우선 양적변수일때의 GAM에 대해 알아보자.&lt;/p&gt;

&lt;h3 id=&quot;77-1-gams-for-regression-problems&quot;&gt;7.7-1 GAMs for Regression Problems&lt;/h3&gt;

&lt;p&gt;다항회귀를 확장하는 방식은 다음과 같은 원래의 식
&lt;script type=&quot;math/tex&quot;&gt;y_i=\beta_0+\beta_1x_{i1}+..+\beta_px_{ip}+\epsilon_i&lt;/script&gt;
에서 단순한 선형결합 &lt;script type=&quot;math/tex&quot;&gt;\beta_jx_{ij}&lt;/script&gt;가 아닌 비선형(그러나 동시에 smooth한) 함수 &lt;script type=&quot;math/tex&quot;&gt;f_j(x_{ij})&lt;/script&gt;를 넣는 것이다. 즉 다음과 같이 변한다. 
&lt;script type=&quot;math/tex&quot;&gt;y_i=\beta_0+f_1(x_{i1})+..+f_p(x_{ip})+\epsilon_i&lt;/script&gt;
(&lt;script type=&quot;math/tex&quot;&gt;\beta_j&lt;/script&gt;가 왜 사라졌을까 할 수 있지만, 함수형태이므로 상수배인 &lt;script type=&quot;math/tex&quot;&gt;\beta&lt;/script&gt; 역시 흡수할 수 있다.)&lt;/p&gt;

&lt;p&gt;여전히, 각 변수 &lt;script type=&quot;math/tex&quot;&gt;x_{ij}&lt;/script&gt;을 각각의 함수 &lt;script type=&quot;math/tex&quot;&gt;f_j&lt;/script&gt;에 부과하고 있으므로, 가법적인 모형(additive model)은 유지하고 있다. (쉽게 말해 &lt;script type=&quot;math/tex&quot;&gt;x_1x_2&lt;/script&gt; 와 같은 항이 존재하지 않는다는 것이다.) 따라서 각각의 Y에 대한 각각의 예측변수들의 기여를 ‘더하여’ 표현했다는 점에서 가법적인 모형이라 표현한다. 각 변수 &lt;script type=&quot;math/tex&quot;&gt;x_{ij}&lt;/script&gt;에 대해 별도로 &lt;script type=&quot;math/tex&quot;&gt;f_j&lt;/script&gt;가 계산되고, 이들의 기여를 더하는 것이다. 이때 &lt;script type=&quot;math/tex&quot;&gt;f_j&lt;/script&gt;는 모수적으로 어떠한 형태를 지정하고 분석을 진행할 수도 있고, 비모수적으로 특정형태를 가정하지 않고 진행을 할 수도 있다.&lt;/p&gt;

&lt;p&gt;GAM은 지금까지 1차원 변수에 대해 다룬 여러 방법들을 building block으로써 활용하여 가법적인 모델을 만들수 있게 해준다. 예를 들어 다음과 같은 식을 만들 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486442-6813e230-1716-11e8-87e4-8d805c123973.PNG&quot; alt=&quot;nnonlin3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;여기서 year, age는 양적변수이고 education은 질적변수이다. 앞의 두 변수는 natural spline을 이용하여 적합을 하고, education은 더미화를 시켜 constant로 적합을 하였다. 그 결과는 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486441-67db6478-1716-11e8-9d33-42c2c4f39ac0.PNG&quot; alt=&quot;nnonlin4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이 역시 적절한 basis function에서 basis represntation으로 나타낼 수 있는데, 이렇게 &lt;script type=&quot;math/tex&quot;&gt;f_j&lt;/script&gt;을 basis function으로 표현이 가능한 형태로 설계한 경우 least square로 적합하여 값을 찾을 수 있다. 기존의 가법적인 선형모델과 마찬가지로 해석 또한 가능한데, 왼쪽 그래프는 우상향이므로, age와 education이 고정된 상태에서 year의 증가는 wage의 증가와 관계가 있다고 할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486440-677b4962-1716-11e8-92c0-7df0b1099d76.PNG&quot; alt=&quot;nnonlin5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;해당 그림은 natural spline이 아닌 smoothing spline으로 적합한 그림인데, 이 경우는 least square적합을 할 수 없기에 좀더 까다롭다.(penalty term으로 인해 basis function으로 표현이 불가능하다) 이때는 다른 예측 변수들을 고정시킨 채 순서대로 변수들을 업데이트 시키는 backfitting이라는 방법을 사용한다. 이는 각 변수를 적합할때 해당 변수를 제외한 나머지 변수들의 partial residual에 적합을 통해서 가능하다. backfitting에 대한 자세한 설명은 &lt;a href=&quot;https://en.wikipedia.org/wiki/Backfitting_algorithm&quot;&gt;참고1&lt;/a&gt; &lt;a href=&quot;https://web.stanford.edu/class/stats202/content/lec17.pdf&quot;&gt;참고18쪽&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;X_3&lt;/script&gt;에서의 partial residual이란 &lt;script type=&quot;math/tex&quot;&gt;r_i=y_i-f_1(x_{i1})-f_2(x_{i2})&lt;/script&gt;이다. 만약 &lt;script type=&quot;math/tex&quot;&gt;f_1&lt;/script&gt;과 &lt;script type=&quot;math/tex&quot;&gt;f_2&lt;/script&gt;를 알고 있다면 남은 잔차, 즉 partial residual에 대해 &lt;script type=&quot;math/tex&quot;&gt;X_3&lt;/script&gt;를 비선형회귀 적합을 하여 &lt;script type=&quot;math/tex&quot;&gt;f_3&lt;/script&gt;을 구할 수 있을 것이다. 이를 각 &lt;script type=&quot;math/tex&quot;&gt;f_j&lt;/script&gt;가 수렴할때까지 반복하여 업데이트한다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;위의 두 그림은 거의 차이가 없다. 사실 대부분의 경우, natural spline과 smoothing spline은 거의 결과차이가 없다. 또한, GAMs에서 위의 두 방식이 아닌 다른 방식을 사용해도 물론 된다.&lt;/p&gt;

&lt;h4 id=&quot;pros-and-cons-of-gams&quot;&gt;Pros and Cons of GAMs&lt;/h4&gt;

&lt;p&gt;GAM의 장단점에 대해 요약해보자.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;기존의 선형적합에서는 할 수 없던 비선형적합을 자동적으로 할 수 있게 한다. 고로 각 변수를 일일이 변형해줄 필요 없다.&lt;/li&gt;
  &lt;li&gt;비선형적합인 만큼 예측력이 높다.&lt;/li&gt;
  &lt;li&gt;가법적인 모델이므로 다른 변수들이 고정되어 있을때의 한 변수의 영향을 알수도 있다. 고로 추론의 측면에서도 강점이 있다.&lt;/li&gt;
  &lt;li&gt;&lt;script type=&quot;math/tex&quot;&gt;X_j&lt;/script&gt;에 대한 함수, 즉 &lt;script type=&quot;math/tex&quot;&gt;f_j&lt;/script&gt;의 smooth정도가 어느정도인지를 degrees of freedom으로 간단하게 나타낼 수 있다.&lt;/li&gt;
  &lt;li&gt;그러나 가법적인 모델이라는 점에서 중요한 상호작용을 잡아낼 수 없다는 단점이 있다. (&lt;a href=&quot;https://stats.stackexchange.com/questions/260175/what-does-the-additive-assumption-mean&quot;&gt;가법성이란&lt;/a&gt;) 그러나 선형회귀에서 가법성을 덜어내고 확장하였듯이, 인위적으로 interaction항을 넣어주어 &lt;script type=&quot;math/tex&quot;&gt;f_{jk}(X_j,X_k)&lt;/script&gt;와 같은 상호작용 함수를 적합할 수도 있다. 그러나 이에 대한 적합벙법은 다루지 않겠다.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;77-2-gams-for-classificatino-problems&quot;&gt;7.7-2 GAMs for Classificatino Problems&lt;/h3&gt;

&lt;p&gt;GAMs는 반응변수Y가 질적변수일때도 사용이 가능하다. 편의를 위해 Y가 0과 1의 값을 가진다 하자. 4장에서와 마찬가지로 특정 X가 주어졌을때 Y가 1일 확률을 &lt;script type=&quot;math/tex&quot;&gt;p(X)=Pr(Y=1\lvert X)&lt;/script&gt;라고 표현할 것이다. Logistic regression에서 다음과 같은 식으로 모델을 설계했던 것을 상기하자.
&lt;script type=&quot;math/tex&quot;&gt;log({\frac{p(X)}{1-p(X)}})=\beta_0+\beta_1X_1+...+\beta_pX_p&lt;/script&gt;
좌변의 ‘로짓’, 즉 &lt;script type=&quot;math/tex&quot;&gt;Pr(Y=0\lvert X)&lt;/script&gt;분의 &lt;script type=&quot;math/tex&quot;&gt;Pr(Y=1\lvert X)&lt;/script&gt;인 오즈의 로그형태가 예측변수 X들과 선형결합의 관계를 가지고 있다. 이를 non-linear관계로 확장하는 자연스런 방법은 다음과 같을 것이다.
&lt;script type=&quot;math/tex&quot;&gt;log({\frac{p(X)}{1-p(X)}})=\beta_0+\beta_1f_1(X_1)+...+\beta_pf_p(X_p)&lt;/script&gt;
이것의 logistic regression의 GAM버젼이다. 질적변수일때도 이전에 논의했던 GAM의 장점과 단점을 동일하게 갖는다.&lt;/p&gt;

&lt;p&gt;예시로 나왔던 Wage 데이터에, 수입이 250넘을지로 다시한면 분류문제를 적합시켜보았다. 이때, GAM은 다음과 같은 적합이 될것이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486481-6d718bd8-1716-11e8-99c2-ae9f6b6c91d4.PNG&quot; alt=&quot;nnonlin6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이때 &lt;script type=&quot;math/tex&quot;&gt;p(X)&lt;/script&gt;는 특정 year, age, education이 주어졌을때 wage&amp;gt;250일 확률, 즉 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486480-6d3776b4-1716-11e8-9760-a0f1501874ea.PNG&quot; alt=&quot;nnonlin7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;식을 보면 알 수 있지만 year의 경우 단순 선형적합을 하였다. 추가로, age의 &lt;script type=&quot;math/tex&quot;&gt;f_2&lt;/script&gt;는 자유도5의 sommthing spline을, &lt;script type=&quot;math/tex&quot;&gt;f_3&lt;/script&gt;은 setp function을 적용하였다. 각각의 적합결과는 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36486478-6cdb5122-1716-11e8-8b79-93d05e22e4bb.PNG&quot; alt=&quot;nnonlin8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;additive model의 특성으로 역시나 각 변수들의 영향을 개별적으로 볼 수 있는데, 구체적으로는 year가 다른 변수들에 비해 income에 영향을 거의 미치지 않는다는 것을 볼 수 있다.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;참고&lt;/p&gt;

&lt;p&gt;전반적인 이론 : http://www.stat.cmu.edu/~ryantibs/advmethods/notes/smoothspline.pdf&lt;/p&gt;

&lt;p&gt;이론2: https://www.hds.utc.fr/~tdenoeux/dokuwiki/_media/en/splines.pdf&lt;/p&gt;

&lt;p&gt;backfitting참고 : https://web.stanford.edu/class/stats202/content/lec17.pdf&lt;/p&gt;
</description>
        <pubDate>Wed, 14 Feb 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/02/14/ISL-Moving-Beyond-Linearity_ch7.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/02/14/ISL-Moving-Beyond-Linearity_ch7.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[ISL] 6장 -Lasso, Ridge, PCR이해하기</title>
        <description>
&lt;p&gt;지금까지는, 회귀문제에서 다음과 같은 함수를 구하고자 하였다.
&lt;script type=&quot;math/tex&quot;&gt;Y=\beta_0+\beta_1X_1+..+\beta_pX_p+\epsilon&lt;/script&gt;
이러한 함수를 주로 ‘least square’로 구하여 적합하였다. 이는 선형모델이고, 7장(generalized linear model)과 8장에서 더욱 non-linear한 모델들을 배울 것이지만, 선형모델은 약간의 확장만으로 non-linear 모델과 놀라울 정도로 경쟁력을 갖고 있다. 이번장에선, 전통적인 least square(OLS라고 부른다)가 아닌 &lt;strong&gt;다른 적합 방법&lt;/strong&gt;으로 &lt;strong&gt;linear model을 개선&lt;/strong&gt;시키는 여러 방법에 대하여 다뤄볼 것이다.&lt;/p&gt;

&lt;h3 id=&quot;왜-안-least-square요&quot;&gt;왜 안 least square요??&lt;/h3&gt;

&lt;p&gt;OLS는 우리의 가정, 즉 1) 오차의 평균이 0, 2) 오차의 분산이 모든 x의 단위에서 등분산, 3) 오차가 서로 uncorrelated인 경우 linear한 모델 중 최적의 모델이다.(iid일 필요도 없다! 자세한 설명은 &lt;a href=&quot;https://en.wikipedia.org/wiki/Gauss%E2%80%93Markov_theorem&quot;&gt;BLUE&lt;/a&gt;) 심지어, 앞장에서 했듯이 오차의 분포가 정규분포일 경우, OLS estimator는 또 다른 강력한 방법인 maximum likelihood estimator와 ‘동일’한 결과를 내게 된다.&lt;/p&gt;

&lt;p&gt;이 전까지 least square의 범용성을 보았을때 왜 least square가 아닌 방법을 사용한다는 것인지 당황할 수 있다. 그 이유는 간단하다. 몇몇 경우에, 전통적인 least square보다 &lt;strong&gt;더 좋은 예측 정확도&lt;/strong&gt;와 &lt;strong&gt;더 좋은 해석력&lt;/strong&gt;을 보이기 때문이다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;예측정확도 : 가정된 분포가 어느정도 맞다면, least square는 상당히 좋은 low bias의 추정을 할 것이다. 언제? &lt;strong&gt;변수의 갯수 &lt;script type=&quot;math/tex&quot;&gt;p&lt;/script&gt;보다 총 자료갯수 &lt;script type=&quot;math/tex&quot;&gt;n&lt;/script&gt;이 ‘훨씬’ 더 많다면&lt;/strong&gt;. 그러나 n이 p보다 눈에 띄게 많지 않다면(보통 3배)  least square는 훨씬 큰 변동성을 갖게 되고, 결과적으로 주어지지 않았던 새로운 자료에 대하여 예측을 잘 못하는 overfitting의 결과를 낳게 된다. 혹은 변수갯수 p가  n보다 더 많다면, 더이상 least square의 유일한 해가 없게된다. 즉, Variance가 무한이 되는, 아예 쓸 수 없는 방법이 되버린다.&lt;/li&gt;
  &lt;li&gt;해석력 : least square는 실제 Y의 함수이해에 큰 관계가 없는 변수를 없애주지 못한다. 즉, 해당 변수의 계수&lt;script type=&quot;math/tex&quot;&gt;\beta_i&lt;/script&gt;가 0이 되어야 함에도 least square가 자동으로 0을 찾기는 매우 어렵다.(그래서 앞장에서는 해당 검정들을 시행하였다.) 이번 장에서는 이런 중요한 변수를 &lt;strong&gt;자동으로&lt;/strong&gt; 선택해줄 수 있는 방법을 다룰 것이다(!)&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  &lt;p&gt;왜 n&amp;lt;p일 경우 해를 구할 수 없다 하는 것일까?&lt;/p&gt;

  &lt;p&gt;3장에서 다항선형회귀일 경우 OLS를 통한 회귀계수의 추정을 다음과같은 matrix 연산으로 계산함을 언급했다.
&lt;script type=&quot;math/tex&quot;&gt;\boldsymbol{\hat \beta}=(\boldsymbol X^T\boldsymbol X)^{-1}\boldsymbol X^T\boldsymbol Y&lt;/script&gt;
이때 &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol X&lt;/script&gt;는 &lt;script type=&quot;math/tex&quot;&gt;(n*p)&lt;/script&gt;의 matrix이다. 위 식은 &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol X^T\boldsymbol X&lt;/script&gt;의 inverse matrix가 존재해야 해가 나오는데, p&amp;gt;n인 경우 X는 모든 열(또는 행)이 선형독립이 아닌, 즉 full rank가 아닌 matrix이다. (&lt;a href=&quot;https://en.wikipedia.org/wiki/Rank_(linear_algebra)&quot;&gt;참고&lt;/a&gt;) 따라서 &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol X^T\boldsymbol X&lt;/script&gt;역시 full rank가 아니고, 이는 비가역행렬, 즉 위 식을 풀 수가 없게됨을 의미한다. (&lt;script type=&quot;math/tex&quot;&gt;rank(\boldsymbol X^T\boldsymbol X)=rank(\boldsymbol X)&lt;/script&gt;)&lt;/p&gt;

  &lt;p&gt;추가로, OLS의 가정이 맞고, 실제 모회귀선이 linear일 경우, &lt;script type=&quot;math/tex&quot;&gt;bias=0&lt;/script&gt;이고 &lt;script type=&quot;math/tex&quot;&gt;variance=p*\frac{\sigma^2}{n}&lt;/script&gt;이다. 즉, 변수 p가 늘어날 수록 모델의 variance가 커진다. &lt;a href=&quot;http://www.stat.cmu.edu/~ryantibs/advmethods/notes/highdim.pdf&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;그럼-어떤-방법을-쓰나요&quot;&gt;그럼 어떤 방법을 쓰나요??&lt;/h3&gt;

&lt;p&gt;이를 해결하기 위한 많은 방법이 있으나 여기서는 가장 대표적인 3가지를 다룬다&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;subset selection : 앞장에도 나왔던 방법. 유의미한 변수들을 골라내고, 이에 대해 least square를 하는 방법.&lt;/li&gt;
  &lt;li&gt;Shrinkage : p개의 &lt;strong&gt;모든&lt;/strong&gt; 변수들로 저합을 한다. 그러나, 이 때의 계수들은 least square에 비하여 더욱 0으로 가고자 하는 경향이 있다. 어떤 shrinkage의 방법을 쓰냐에 따라 다르지만, 어떤 방법들은 정확하게 0으로 추정하기도 하여, 자동적인 변수 선택을 가능하게 한다. regularization이라고도 한다.&lt;/li&gt;
  &lt;li&gt;Dimension Reduction : 큰차원(p차원)의 p개의 예측변수를 M차원으로 projection시키는 것이다. 이를 통해 M개의 linear combination이 나오고, 이를 M개의 예측변수로써 사용하여 least square를 하는 것이다.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;앞으로의 예시는 회귀에 중점을 두고 있지만, 4장의 classification과 같은 다른 방법에도 적용될 수 있다.&lt;/p&gt;

&lt;h2 id=&quot;61-subset-selection&quot;&gt;6.1 Subset selection&lt;/h2&gt;

&lt;h3 id=&quot;611-best-subset-selection&quot;&gt;6.1.1 Best Subset Selection&lt;/h3&gt;

&lt;p&gt;best subset selection은, 가능한 모든 경우의 수의 적합을 해보고 이 중 best 를 찾는 것이다. 다음의 알고리즘을 사용한다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;모든 사이즈에 대해 최적의 적합을 찾아낸다. 즉, 다음과 같다.
    &lt;ul&gt;
      &lt;li&gt;변수k개만 포함한 모든 모델을 적합한다.(&lt;script type=&quot;math/tex&quot;&gt;\begin{pmatrix}p\\k\end{pmatrix}&lt;/script&gt;개)&lt;/li&gt;
      &lt;li&gt;그 중 가장 좋은 모델을 &lt;strong&gt;하나&lt;/strong&gt; 뽑는다. 변수의 갯수가 같으니, 비교는 단순이 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;으로 해도 된다.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;그렇게 뽑힌 각 변수사이즈 내에서의 best model중, 최고의 single best model을 뽑는다. 이때는 평가 기준은 변수의 갯수가 다르니 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;를 사용하지 못하고,CV-error, &lt;script type=&quot;math/tex&quot;&gt;C_p, AIC, BIC,R_{adj}&lt;/script&gt;등이 될 수 있다.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;2번에서 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;를 사용하지 않는 이유는 간단하다. 높은 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;는 low training error를 의미하는 것으로, 변수가 많아질 때마다 그를 토대로 한 training set에 대한 설명력은 높아질수 밖에 없다.(3장 참고) 그러나 우리의 목표는 low test error이므로, 다른 지표를 사용하는 것이다. 다른 지표에 대한 설명은 잠시 뒤에 나온다. 추가로, 위에선 least square의 경우로써 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;를 사용하였지만 로지스틱회귀 같은 경우 deviance로써 계산한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;deviance는 sum of square의 generalized 버젼으로, maximum likelihood로 적합한 모델의 goodness of fit을 측정하기 위한 척도로 많이 사용된다. &lt;a href=&quot;http://www.unc.edu/courses/2006spring/ecol/145/001/docs/lectures/lecture22.htm#deviance&quot;&gt;참고&lt;/a&gt; saturated model과 Reduced model 에 대한 likelihood ratio test에 대한 지표로 보면 된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;그러나 이는 &lt;script type=&quot;math/tex&quot;&gt;2^p&lt;/script&gt;개(넣냐 안넣느냐)의 모든 가능한모델을 적합해야 함을 의미하므로, 예상했겠지만 computation 적으로 매우 힘들다. 심지어 요즘의 computation으로도 p가 40개가 넘어가면 힘들기에, 실질적으론 다음의 방법이 더 많이 사용된다.&lt;/p&gt;

&lt;h3 id=&quot;61-2-stepwise-selection&quot;&gt;6.1-2 stepwise selection&lt;/h3&gt;

&lt;p&gt;계산적 문제 외에도, best subset selection은 여러 모델을 반환해준다는 점에서 p가 커지면 잘못된(overfitting된) 모델을 고르게 될 확률이 커진다는 단점이 있다고 할 수 있다. 따라서 그 대안으로는 stepwise 방법이 사용된다&lt;/p&gt;

&lt;p&gt;이는 3장에서도 소개하였듯이, 다음과 같다. 여기에서는 추가적인 사실만을 덧붙여 제공한다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;전진 선택법 :
    &lt;ul&gt;
      &lt;li&gt;1) 아무 변수도 포함되지 않은 모델에서&lt;/li&gt;
      &lt;li&gt;2) t통계량이 제일 유의한 변수 한개를 넣는다( 기준은? 한 변수에 관해서는 F통계량, t통계량, 오차 제곱합 감소 다 같은 결과를 낸다, 암꺼나로 해도 됨)&lt;/li&gt;
      &lt;li&gt;3)해당 변수를 넣은 상태에서 2번을 계산하여 또 하나를 넣는다. (변수 하나가 기본으로 들어가 있으니 p-value가 달라짐)&lt;/li&gt;
      &lt;li&gt;4) 더이상 중요한 변수가 없으면(t 통계량이 유의한게 없으면) 멈춘다&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;이 경우 변수p가 20개 였다면, best subset 은 1,048,576번의 적합을 해야하지만 전진선택법은 211번의 적합만을 하면 된다. 그러나 한 변수만을 고려했을땐 &lt;script type=&quot;math/tex&quot;&gt;X_1&lt;/script&gt;이 제일 잘 설명하지만 2변수를 고려했을땐 &lt;script type=&quot;math/tex&quot;&gt;X_2,X_3&lt;/script&gt;이 더 잘할 수 있기에, &lt;strong&gt;꼭 best 모델을 찾게 되는것은 아니다&lt;/strong&gt;. 둘이 합쳐짐으로써 낼 수 있는 설명이 기존의 &lt;script type=&quot;math/tex&quot;&gt;X_1&lt;/script&gt;이 들어간 변수2개짜리 모델, 즉 &lt;script type=&quot;math/tex&quot;&gt;X_1,X_2&lt;/script&gt;나 &lt;script type=&quot;math/tex&quot;&gt;X_1,X_3&lt;/script&gt;보다 잘할 수 있다.  그리고 n&amp;lt;p인 경우 처음에는 적합을 할 수 있지만, high dimension단계, 즉 적합하려하는 변수갯수가 전체 데이터n보다 많아지는 단계(n&amp;lt;k)에 들어서면 역시나 각 모델의 유일한 least square 계수를 찾을수 없게 된다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;후진 제거법 :
    &lt;ul&gt;
      &lt;li&gt;1) 모든 변수가 있는 모델에서&lt;/li&gt;
      &lt;li&gt;2) 제일 큰 p-value를 가진 변수를 지움&lt;/li&gt;
      &lt;li&gt;3) 남은 p-1개 변수로 또 p-value계산해서 뺀다&lt;/li&gt;
      &lt;li&gt;4) 더이상 뺄 변수가 없으면 멈춘다&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;이 역시 전진선택법 처럼 &lt;strong&gt;best 모델을 찾는것이 보장되지는 않는다&lt;/strong&gt;. 주로 전진선택법은 보수적인 모델(변수가 덜들어간), 후진제거법은 변수가 많이 들어간 모델을 최종적으로 선택하게 된다. 또한, n&amp;lt;p인 경우, 모든 변수가 들어간 모델 자체를 적합할 수 없다는 점에서 전진선택과 차이가 있다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;전진 단계적 회귀(mixed selection)
    &lt;ul&gt;
      &lt;li&gt;1) 아무 변수도 포함되지 않은 모델에서&lt;/li&gt;
      &lt;li&gt;2) t통계량이 제일 유의한 변수 한개를 넣는다&lt;/li&gt;
      &lt;li&gt;3) 해당 변수를 &lt;strong&gt;넣은 상태에서 p-value를 계산해서&lt;/strong&gt; 유의미 하지 않은 변수를 &lt;strong&gt;지운다&lt;/strong&gt; (이때 들어오기 위한 p-value임계점과 나가는 임계점을 다르게 한다. 보통 어렵게 들어오고(&lt;script type=&quot;math/tex&quot;&gt;\alpha=0.1&lt;/script&gt;) 쉽게 뺀다(&lt;script type=&quot;math/tex&quot;&gt;\alpha=0.1&lt;/script&gt;5) )&lt;/li&gt;
      &lt;li&gt;4) 다시 중요한 순대로 새로운 변수를 넣는다.&lt;/li&gt;
      &lt;li&gt;5) 더이상 넣을 변수도, 뺄 변수도 없으면 멈춤&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;위의 방법이, 사실상 계산적 부담을 덜으면서 가장 best subset selection과 비슷한 모델을 찾아준다.&lt;/p&gt;

&lt;h2 id=&quot;61-3-choosing-the-optimal-model&quot;&gt;6.1-3 Choosing the Optimal Model&lt;/h2&gt;

&lt;p&gt;앞에서 변수의 수가 다른 경우 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;가 test error의 적절한 판단 기준이 될 수 없음을 언급하였다. 따라서, test error를 최소화하는 모델을 고르고자 할때, 우리는 test error를 &lt;strong&gt;추정&lt;/strong&gt;해야 한다. test error를 추정하는 방법은 다음과 같다.  &lt;strong&gt;1)&lt;/strong&gt; training error rate에 overfitting을 고려한 수학적인 보정을 가하여 test error를 간접적으로 추정하는것  &lt;strong&gt;2)&lt;/strong&gt; training set중 몇개를 따로 빼내서 test error를 &lt;strong&gt;직접적으로 추정&lt;/strong&gt;하는 방법(5장에서 다뤘음).&lt;/p&gt;

&lt;h3 id=&quot;c_p-aic-bic-and-adjusted-r2&quot;&gt;$C_p$, AIC, BIC, and Adjusted $R^2$&lt;/h3&gt;

&lt;p&gt;training error rate에 overfitting을 고려한 수학적인 보정을 가하여 test error를 &lt;strong&gt;간접적으로 추정&lt;/strong&gt;하는것으로는 &lt;script type=&quot;math/tex&quot;&gt;C_p&lt;/script&gt;, AIC, BIC, Adjusted &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;이 있다. 이를 이용하면, 변수갯수가 다른 모델들 간의 비교도 가능하게 된다. 식은 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;C_p=\frac{SSE_{R}}{MSE_{F}}-(n-2p)&lt;/script&gt;
책의 수식은 다음과 같다. (notation &lt;script type=&quot;math/tex&quot;&gt;RSS=SSE_R&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;d=p&lt;/script&gt;. 같은 것이다.)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;책의 수식의 &lt;script type=&quot;math/tex&quot;&gt;\hat \sigma^2&lt;/script&gt;와 위의 수식의 &lt;script type=&quot;math/tex&quot;&gt;MSE_F&lt;/script&gt;는 같은걸 지칭한다. 둘다 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;의 추정치라는 뜻.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559440-abb77194-05a2-11e8-926f-fb81a8d2bca5.PNG&quot; alt=&quot;crit1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;SSE_R&lt;/script&gt;은 reduced model(몇개만 넣은 모델)의  SSE, &lt;script type=&quot;math/tex&quot;&gt;MSE_F&lt;/script&gt;는 모든 변수 적합을 통해 구한 MSE, 즉 &lt;script type=&quot;math/tex&quot;&gt;\hat \sigma^2&lt;/script&gt;이다. 변수의 갯수 &lt;script type=&quot;math/tex&quot;&gt;p&lt;/script&gt;가 수식에 들어가 변수의 갯수에 대한 조정을 해주고 있는것을 볼 수 있다. 여기에선 결과만을 제시하지만, &lt;script type=&quot;math/tex&quot;&gt;\hat \sigma^2&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;\sigma&lt;/script&gt;에 대한 unbiased estimator라면, &lt;script type=&quot;math/tex&quot;&gt;C_p&lt;/script&gt;역시 test MSE에 대한 unbiased estimator이다 이 기준에선 &lt;script type=&quot;math/tex&quot;&gt;C_p&lt;/script&gt;가 낮은 모델이, 가장 좋은 모델이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;위 문장에서 irreducible error혹은 모델에 포함되지 못한 분산 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;랑 test MSE랑 헷갈릴수 있는데, 이는 다른 것이다.&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Test-MSE=Var(\hat f({x}_{0}))+[Bias(\hat f({x}_{0}))]^2+Var(\epsilon)&lt;/script&gt;이고  여기서 이다. 자세한 논의는 5장의 Cross-Validation에서 다루었다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;AIC는 maximum likelihood로 적합시킨 모델에 대한 기준이지만, error &lt;script type=&quot;math/tex&quot;&gt;\epsilon&lt;/script&gt;에 정규가정을 하였다면 maximum likelihood와 least square는 같은 결과를 가져온다. &lt;a href=&quot;https://stats.stackexchange.com/questions/133799/numerical-difference-between-sum-of-squared-residuals-and-likelihood?rq=1&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559439-ab68505a-05a2-11e8-87c0-f4985c0f3117.PNG&quot; alt=&quot;crit2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;식을 보면 알 수 있지만, &lt;script type=&quot;math/tex&quot;&gt;AIC&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;C_p&lt;/script&gt;는 상수배이다. 즉, 사실상 같은 의미를 갖는다. &lt;a href=&quot;https://rstudio-pubs-static.s3.amazonaws.com/324771_0bd880964f064c53a70e757d5ef39669.html&quot;&gt;어려운 참고&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;BIC는 Bayesian의 관점에서 계산된 지표이다. 결과를 두고 보았을때는 AIC에서 2가 &lt;script type=&quot;math/tex&quot;&gt;log(n)&lt;/script&gt;으로 바뀐 차이뿐이다. n&amp;gt;7이면 &lt;script type=&quot;math/tex&quot;&gt;log(n)&gt;2&lt;/script&gt;이므로 (&lt;script type=&quot;math/tex&quot;&gt;e^2&lt;/script&gt;는7.38정도이다) &lt;strong&gt;왠만한 경우에 BIC가 더 많은 변수에 더 패널티를 주었다&lt;/strong&gt;고 볼 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559438-ab235554-05a2-11e8-843b-d260d2640468.PNG&quot; alt=&quot;crit3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Adjusted &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;는 다음과 같다. &lt;script type=&quot;math/tex&quot;&gt;C_p, AIC, BIC&lt;/script&gt;가 &lt;strong&gt;낮을 수록 좋은모델&lt;/strong&gt;인 반면 adj &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;는 &lt;strong&gt;높을 수록 좋은 모델&lt;/strong&gt;(test error가 낮은 모델)이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559436-aae3eb12-05a2-11e8-87b1-3197eb1c2772.PNG&quot; alt=&quot;crit4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;식을 보면 알겟지만, SSE와 SST를 각각의 &lt;script type=&quot;math/tex&quot;&gt;df&lt;/script&gt;(n-(d+1)과 n-1)로 나눈 것이다.&lt;/p&gt;

&lt;p&gt;사실, Adj &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;는 매우 널리 쓰이는 지표이지만, &lt;script type=&quot;math/tex&quot;&gt;C_p, AIC, BIC&lt;/script&gt;는 많은 이론적 바탕이 있는 반면 Adj &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;는 큰 통계이론적 배경은 없다.(!)&lt;/p&gt;

&lt;h3 id=&quot;validation-and-cross-validation&quot;&gt;Validation and Cross-Validation&lt;/h3&gt;

&lt;p&gt;5장에서 여러번의 resampling을 통해 test error를 직접적으로 추정해보는 validation 방법을 다루었었다. 놀랍게도 이는, 사실 위에서 다루었던 수학적 보정을 통한 &lt;script type=&quot;math/tex&quot;&gt;C_p, AIC, BIC, adjR^2&lt;/script&gt; 보다 이점이 많은데, 그 이유는 가정을 거의 하지 않고, 또 자유도를 구하기 힘들거나 &lt;script type=&quot;math/tex&quot;&gt;\hat \sigma^2&lt;/script&gt;를 구하기 힘든 여러 경우에도 사용될 수 있기 때문이다.&lt;/p&gt;

&lt;p&gt;과거에는 computation power의 한계로 &lt;script type=&quot;math/tex&quot;&gt;C_p, AIC, BIC, adjR^2&lt;/script&gt;를 선호하였지만, 최근에는 cross-validation 방법이 더욱 많이 쓰이고 있다.&lt;/p&gt;

&lt;p&gt;실제에서는, 다음과 같은 방식이 사용된다. 어떠한 회귀 문제에서, 몇개의 변수를 사용하여 적합할지를 BIC, 4-fold CV, 10-fold CV로 본것이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559434-aaaecefa-05a2-11e8-84df-747db80f12ef.PNG&quot; alt=&quot;crit5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;각각 변수 4개, 6개, 6개를 최적이라고 보았으나, 모든 경우에서 변수 3개까지는 &lt;strong&gt;추정된 test error가 급감&lt;/strong&gt;하였으나 그 후는 크게 변동이 없는 것으로 보인다. 또한, 몇개의 그룹으로 잘랐는지, 혹은 어떻게 기존의 data가 잘렸는지에 따라서 &lt;strong&gt;약간씩 변동할 위험도&lt;/strong&gt; 있다. 즉, 변수6개가 최적의 모델이 아닐 수도 있는 것이다. 이를 해결하기 위해 &lt;strong&gt;&lt;em&gt;one-standard-error rule&lt;/em&gt;&lt;/strong&gt;을 적용한다. 추정된 test MSE의 표준편차standard-error를 구한뒤(sample mean으로 test MSE를 추정하였듯이 표준편차도 구할 수 있다 &lt;a href=&quot;http://www.stat.cmu.edu/~ryantibs/datamining/lectures/18-val1.pdf&quot;&gt;참고18쪽&lt;/a&gt;), 최소 test MSE추정값(예시에선 각각 4,6,6)에서 (1 X standard error) 만큼 떨어진 모델들을 모두 고려하는 것이다. 이는, 추정된 test MSE가 크게 다르지 않은 수준 내에서, 가장 단순한 모델을 고르고자 하는 목적이 있다. 이러한 방법을 사용할 경우, 변수 3개를 택하는 결과가 나오게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;one-standard-error rule에서 standard error를 구하는 식은 다음과 같다.&lt;/p&gt;

  &lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36018629-52bdca82-0d74-11e8-93f6-4002e72220dd.PNG&quot; alt=&quot;one-stand-rule&quot; /&gt;각각 ‘1번째 fold를 빼고 적합한 모델의 CVerror’,..,’k번째 fold를 빼고 적합한 모델의 CVerror’를 의미한다. 단순히 k-fold를 통해 얻은 k개의 자료로 sd를 구했다고 받아들이면 된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;62-shrinkage-methods&quot;&gt;6.2 Shrinkage Methods&lt;/h2&gt;

&lt;p&gt;위에서는 변수를 선택하고 선택된 변수로 least square적합을 하는 방법을 다루었다. 이번에는, &lt;strong&gt;모든 변수&lt;/strong&gt;로 적합을 하되 계수들을 0으로 constrain, 혹은 regularize하는 shrinkage 방법을 다룰 것이다. 이러한 방법은, &lt;strong&gt;추정된 계수들의 변동(variance)을 대폭 줄여준다&lt;/strong&gt;는 강점이 있다.&lt;/p&gt;

&lt;h3 id=&quot;62-1-ridge-regression-&quot;&gt;6.2-1 Ridge Regression (!)&lt;/h3&gt;

&lt;p&gt;3장에서 배웠던 least square는, 다음의 식을 최소화하는 방식으로 계수를 추정하였다. (단순한 차의 제곱들의 합이다)
&lt;script type=&quot;math/tex&quot;&gt;RSS=\sum_{i=1}^n(y_i-\beta_0-\beta_1x_{i1}-..-\beta_px_{ip})^2&lt;/script&gt;
Ridge Regression 역시 least square와 거의 동일한 방식이지만, 최소화하는 식이 조금 다르다. 구체적으론 다음과 같다. 
&lt;script type=&quot;math/tex&quot;&gt;\sum_{i=1}^n(y_i-\beta_0-\beta_1x_{i1}-..-\beta_px_{ip})^2+\lambda\sum_{j=1}^p\beta_j^2=RSS+\lambda\sum_{j=1}^p\beta_j^2&lt;/script&gt;
여기서 &lt;script type=&quot;math/tex&quot;&gt;\lambda(\ge0)&lt;/script&gt;는 &lt;em&gt;tuning parameter&lt;/em&gt;로(hyper parameter라고도 한다), 분석자가 지정한다. 기존의 RSS에서, &lt;strong&gt;(모든 계수의 제곱합) X (지정된 상수 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;)를 최소화 하는 식&lt;/strong&gt;이 더 붙었다. 따라서 계수들이 작아지도록 유도하게 된다. 이로써 ridge regression은 RSS를 최소화함으로써 &lt;strong&gt;데이터에 잘 적합하는 동시에&lt;/strong&gt;, shrinkage penalty라고 불리는 &lt;script type=&quot;math/tex&quot;&gt;\lambda\sum_{j=1}^p\beta_j^2&lt;/script&gt;을 통하여 &lt;strong&gt;계수들(&lt;script type=&quot;math/tex&quot;&gt;\beta_1,..,\beta_p&lt;/script&gt;)이 0으로 가게하려는 shrink의 효과&lt;/strong&gt; 역시 부여하는 것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;머신러닝, 딥러닝에서 많이 쓰이는 L2 regularization term이 덧붙은 것이라 보면 된다. parameter의 크기가 지나치게 커지지 않도록 제한을 걸어주는것.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;해당 식에서 &lt;script type=&quot;math/tex&quot;&gt;\beta_0&lt;/script&gt;은 shrink의 대상에 들어가 있지 않음에 주의해라. &lt;script type=&quot;math/tex&quot;&gt;\beta_0&lt;/script&gt;은 단순히 모든 변수의 계수가 0일때 예측변수들의 평균으로 구하는 것이기에, 이는 shrink의 대상이 아니다.&lt;/p&gt;

&lt;p&gt;이때 두 목표중 어디에 더 치중할 것인지는 분석자가 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 통해 결정한다. &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 0이면 shrinkage의 비중을 0, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 커질 수록 shrinkage효과에 비중을 두는 식이다. 결국 이 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;에 따라 최종적으로 추정되는 계수들도 달라지게 되므로, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 결정하는 것이 매우 중요하다. 이는 cross-validation을 통하여 결정하는데, 조금 뒤에 따로 설명하겠다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559432-aa2f880c-05a2-11e8-98b7-722e3237060e.PNG&quot; alt=&quot;shrink2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;왼쪽 그림은 예시문제에서 각각의 변수(income, limit등등)들의 계수가 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 커져갈때 어떻게 변화하는지를 그린 그래프이다. 가장 왼쪽, 즉 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 0일때는 기존의 least square와 같고, 점차 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;값이 커지면서 계수들이 0으로 가는것을 볼 수 있다. 그러나 Rating의 계수의 값을 보면 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 커질때 잠시 값이 커지기도 한다.&lt;/p&gt;

&lt;p&gt;오른족은 같은 계수들의 값을 이번에는 x축을 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 아닌 &lt;script type=&quot;math/tex&quot;&gt;\frac{\left\|\hat\beta_{\lambda}^R\right\|_2}{\left\|\hat\beta\right\|_2}&lt;/script&gt;이다. 분자는 Ridge regression의 계수들의 L2 norm이고, 분모는 least square의 계수들의 L2 norm이다. L2 norm은 벡터의 크기를 나타내는 방식중 하나인데, 다음과 같이 정의 된다
&lt;script type=&quot;math/tex&quot;&gt;\left\|\boldsymbol\beta\right\|_2=\sqrt{\sum_{j=1}^p\beta_j^2}&lt;/script&gt;
쉽게 다차원에서의 원점과 &lt;script type=&quot;math/tex&quot;&gt;\beta​&lt;/script&gt;의 유클리드 거리라고 생각하면 된다. 이때는 &lt;script type=&quot;math/tex&quot;&gt;\lambda​&lt;/script&gt;가 커지면 x축은 0이 될것이고, &lt;script type=&quot;math/tex&quot;&gt;\lambda​&lt;/script&gt;가 작아지면 x축은 1에 가까워 질 것이다.&lt;/p&gt;

&lt;h4 id=&quot;x들의-표준화&quot;&gt;X들의 표준화&lt;/h4&gt;

&lt;p&gt;기존의 least square에서, 변수의 단위를 c배 조정해주는것(예를 들어 ‘10000’만원 단위였던 것을 ‘1’억원으로 바꾸는것)은 &lt;strong&gt;해당 변수의 계수를 1/c만큼&lt;/strong&gt; 조정하는 효과였다. (변수가 한단위 증가할때 ‘12345’만원 증가하는거나 ‘1.2345’억원 증가하는걸 의미한다.)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Scaling에 관하여. scaling은 각 예측변수들의 scale이 지나치게 다른경우 계수들의 scale을 통일시켜 scale이 작은 변수들의 기여를 제대로 표현하고자(주이유), 또 큰 scale에서 오는 버림오차 등에 대한 위험을 줄이고자(부가이유) 실행한다. 또한 수학적으로는 descent 알고리즘에서 가파른 기울기를 완화시켜주는 의미를 갖는다. 또한 보통 반응변수는 scale대상이 아니다. (&lt;a href=&quot;https://stats.stackexchange.com/questions/111467/is-it-necessary-to-scale-the-target-value-in-addition-to-scaling-features-for-re&quot;&gt;참고&lt;/a&gt;)&lt;/p&gt;

  &lt;p&gt;scaling과 centering의 의의가 잘 정리되어 있는 &lt;a href=&quot;https://stats.stackexchange.com/questions/29781/when-conducting-multiple-regression-when-should-you-center-your-predictor-varia&quot;&gt;사이트&lt;/a&gt;인데, 정리하자면 모든 변수들의 mean을 0으로 만들어 절편항에 대한 의미를 부여하는 것 등의 목적으로 행하는 것이 centering이고, scale의 차이로 인한 계수해석의 어려움을 방지하고자 행하는 것이 scaling이다. 다항회귀가 아닌경우, 두가지 모두 분석 자체에 영향을 미치지 않는다. centering하는것과 scaling이 되는것을 통한 그 밖의 여러 효과가 있으니 참고하면 좋다.&lt;/p&gt;

  &lt;p&gt;추가로, scaling이 되었다고 회귀계수들을 바로 변수들의 중요성으로 보는 것은 위험한데, 이는 각 예측변수들이 서로 correlated되어 있을 경우 각 회귀계수들이 다른 예측변수들에도 영향을 받기때문이다. (참고교재 283쪽)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;그러나 ridge regression은 &lt;script type=&quot;math/tex&quot;&gt;\lambda\sum_{j=1}^p\beta_j^2&lt;/script&gt;이 수식에 들어가 있으므로, 변수 &lt;script type=&quot;math/tex&quot;&gt;X_j&lt;/script&gt;의 scaling이 &lt;strong&gt;&lt;script type=&quot;math/tex&quot;&gt;\beta_j&lt;/script&gt;에만 영향을 미치는게 아니고&lt;/strong&gt;, 또한 다른 변수의 scaling역시 &lt;script type=&quot;math/tex&quot;&gt;\beta_j&lt;/script&gt;에 영향을 미치게 된다. (&lt;script type=&quot;math/tex&quot;&gt;\sum&lt;/script&gt;기호를 통해 모두 연결되어 있다.) 즉 ridge regression에서 &lt;strong&gt;추정되는 계수&lt;/strong&gt;는 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;에만 영향을 받는 것이 아니라 &lt;strong&gt;변수들의 scaling에도 영향&lt;/strong&gt;을 받는 것이다. 따라서 보통 ridge regression전에 모든 변수들을 다음과 같이 표준화를 해주고 진행을 한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559431-a9ee72a4-05a2-11e8-8395-0caa71e3e3d1.PNG&quot; alt=&quot;shrink3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위와 표준화를 해준다는 것은 같은 scale에 있게 한다는 것과 같은 의미이다. 식을 보면 각 변수의 표준편차로 나누어 주고 있다. 따라서 모든 변수들의 표준편차가 1이 된다. 이에 따라 ridge regression이 scaling에 변동하지 않게 된다. 위의 그림은 표준화를 한 경우의 계수이다.&lt;/p&gt;

&lt;h4 id=&quot;왜-ridge-요&quot;&gt;왜 Ridge 요?&lt;/h4&gt;

&lt;p&gt;이제, ridge regression을 이해하긴 했는데, 이걸 왜쓰는 건지 아직 와닿지 않는다. 왜 이런 기법을 쓰는 것일까? 그 해답은 또 &lt;strong&gt;bias-variance trade-off&lt;/strong&gt;에 있다. &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 증가함에 따라, flexibility는 감소하게 되고, 결과적으로 Variance는 감소하고 bias는 증가하게 된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559430-a99ff8d6-05a2-11e8-817a-522b9f71ae25.PNG&quot; alt=&quot;shrink4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위의 그림은 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;에 따른 ridge regression의 bias(검은선)과 variance(초록선)이다. 검은 선을 보면 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 0일때는 bias가 0, 즉 least square의 특징인 unbiased를 잘 보여주고 있다. bias는 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 증가함에 따라 조금씩 올라간다. 그러나 초록선Variance를 보면, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 증가할때마다 더욱 큰폭으로 감소함을 볼 수 있다. &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;라는 &lt;strong&gt;제약&lt;/strong&gt;에 따라 계수들이 shrinkage하게 되어 변동이 크지 않은 모델이 나오는 것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;는 사실 제약으로써, &lt;script type=&quot;math/tex&quot;&gt;\beta&lt;/script&gt; matrix의 &lt;script type=&quot;math/tex&quot;&gt;df&lt;/script&gt;를 줄이게 된다. &lt;a href=&quot;https://onlinecourses.science.psu.edu/stat857/node/155&quot;&gt;어려운 참고&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이에 따라 bias의 제곱과 variance로 이루어져 있는test MSE(분홍선)는 지속적으로 감소해서 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 10조금 넘는 부분에서 최소점을 찍는 것을 볼 수 있다.&lt;/p&gt;

&lt;p&gt;(&lt;script type=&quot;math/tex&quot;&gt;Avg({y}_{0}-\hat f({x}_{0}))^2=Var(\hat f({x}_{0}))+[Bias(\hat f({x}_{0}))]^2+Var(\epsilon)&lt;/script&gt; 상기)&lt;/p&gt;

&lt;p&gt;오른쪽 그림은 같은 상황을 L2 norm으로 제시한 그림이다. 역시나 bias variance의 trade-off를 확인할 수 있다.&lt;/p&gt;

&lt;p&gt;실제 함수가 선형에 가까울때 보통의 &lt;strong&gt;least square방법&lt;/strong&gt;은, unbiased하나 &lt;strong&gt;높은 variance&lt;/strong&gt;를 가진 계수를 추정하게 된다. 이는 데이터가 조금만 바뀌어도 계수들이 크게 변동할 수 있음을 의미한다. 특히, &lt;strong&gt;p&amp;gt;n&lt;/strong&gt;, 즉 설명변수가 많아질때 &lt;strong&gt;least square는 심지어 유일한 해가 없게&lt;/strong&gt; 된다. 이러한 상황에서 ridge regression은 약간의 bias에서의 손해로 variance를 크게 줄여 least square보다 좋은 결과를 가져올 수 있다. 쉽게 말해 설명변수p 보다 데이터의 수n이 적을때, 더욱 덜 flexible한 적합을 하여 &lt;strong&gt;소수의 데이터의 특성에 국한되지 않는&lt;/strong&gt; 모델을 만드는 것이다.&lt;/p&gt;

&lt;p&gt;또한, 특정 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;에서의 계산은 한번만 하면 되기 때문에, ridge regression은 &lt;script type=&quot;math/tex&quot;&gt;2^p&lt;/script&gt;번의 계산을 해야하는 best subset selection보다 computation에서도  큰 강점을 가지고 있다. (사실 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;에 따라서 식이 달라지는 것도 아니기에 여러 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 고려하는 것도 어렵지 않다.)&lt;/p&gt;

&lt;h2 id=&quot;62-2-the-lasso&quot;&gt;6.2-2 The Lasso&lt;/h2&gt;

&lt;h4 id=&quot;ridge-의-단점을-굳이-꼽아보자&quot;&gt;Ridge 의 단점을 굳이 꼽아보자&lt;/h4&gt;

&lt;p&gt;앞에서 다룬 Ridge regression은 특별한 단점을 가지고 있지는 않다. 그러나 변수선택법을 통해 변수를 선택하고 적합을 하는 방식과 다르게 ridge는 특정 패널티 &lt;script type=&quot;math/tex&quot;&gt;\lambda\sum_{j=1}^p\beta_j^2&lt;/script&gt;를 통해 몇몇의 변수의 계수를 0에 가깝게 가게 만든다(물론 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 무한히 크게하면 다 0으로 가지만, 보통은 그렇게 안한다). 이는 예측의 측면에서는 문제가 아니지만, 해석의 측면에서 약점을 가지고 있다 할 수 있다. 예를 들어 10개의 변수중에서, &lt;script type=&quot;math/tex&quot;&gt;X_1,X_3,X_8&lt;/script&gt;이 중요한 변수임을 깨달았다 해보자. 우리는 위 3개의 변수로만 적합을 하고 싶지만, ridge regression은 그 설정상 모든 변수로 적합을 해야하고, 다른 변수의 계수는 0에 가까운 작은 값이지만(예를 들어 0.000283) 완벽한 0이 나오지는 않을 것이다.&lt;/p&gt;

&lt;p&gt;이를 보완하기 위해 고안된 방법이 바로  Lasso이다. Lasso는 다음의 식을 최소화하는 방식으로 계수를 추정한다
&lt;script type=&quot;math/tex&quot;&gt;\sum_{i=1}^n(y_i-\beta_0-\beta_1x_{i1}-..-\beta_px_{ip})^2+\lambda\sum_{j=1}^p|\beta_j|=RSS+\lambda\sum_{j=1}^p|\beta_j|&lt;/script&gt;
식을 보면 알겠지만, ridge regression에서 최소화하려 했던 식과 매우매우 유사하다. 구체적으로 말하자면  &lt;script type=&quot;math/tex&quot;&gt;\beta_j^2&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;|\beta_j|&lt;/script&gt;로 바뀌었을 뿐이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;Ridge regression&lt;/strong&gt;의 식 참고
&lt;script type=&quot;math/tex&quot;&gt;\sum_{i=1}^n(y_i-\beta_0-\beta_1x_{i1}-..-\beta_px_{ip})^2+\lambda\sum_{j=1}^p\beta_j^2=RSS+\lambda\sum_{j=1}^p\beta_j^2&lt;/script&gt;&lt;/p&gt;

&lt;/blockquote&gt;

&lt;p&gt;이를 좀더 통계적으로 말하자면, lasso는 L2 norm을 이용하여 penalty를 준 Ridge와는 달리 L1 norm을 이용하여 penalty를 준 식이다. L1역시 벡터의 크기를 나타내는 기준중 하나인데, 정확한 식은 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;\left\|\boldsymbol\beta\right\|_1={\sum_{j=1}^p|\beta_j|}&lt;/script&gt;
즉, 단순하게 절대값의 합을 해준 방식이다. (L2 norm은 제곱들의 합의 루트였다.) 이때도 모든 &lt;script type=&quot;math/tex&quot;&gt;\beta_j&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;\sum&lt;/script&gt;으로 엮여 있기에, 같은이유로 모든 변수를 scaling해준다.&lt;/p&gt;

&lt;p&gt;계수들이 0의 방향으로 shrink하게 했던 ridge와 달리, Lasso는 적당한 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;만으로 몇몇 계수를 &lt;strong&gt;정확하게 0으로&lt;/strong&gt; 가게 만들 수 있다. 따라서 몇몇 중요하지 않은 변수가 사라진 효과이므로 &lt;strong&gt;해석력에서 ridge보다 강력한 강점&lt;/strong&gt;을 가지고 있다. 물론 ridge와 마찬가지로 Lasso도 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 어떻게 설정할것인지가 매우 중요하다. 이는 뒤에서 cross-validation을 통해 다룬다.&lt;/p&gt;

&lt;p&gt;전체의 변수를 포함하지 않고 몇몇 변수만을 포함한다는 의미에서, Lasso를 &lt;strong&gt;sparse한 model&lt;/strong&gt;이라고도 한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559429-a94d92b2-05a2-11e8-8500-9ac935f7837b.PNG&quot; alt=&quot;lasso&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Ridge에서와 같이 왼쪽은 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;에 따른 계수들의 값이다. &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 0이면 기본적인 least square와 같고, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;가 커지면 계수들이 전부 0이되는 null model(아무 변수도 없는, &lt;script type=&quot;math/tex&quot;&gt;\bar y&lt;/script&gt;를 예측하는 모델)과 같아진다. 그러나, 오른쪽 그림을 보면 ridge와 lasso의 차이가 확연히 드러난다. 계수들이 완만하게 0으로 가며 완벽한 0이 되는 시점은 모든 계수들이 비슷한 시점이었던 위의 Ridge그림과 달리, Lasso는 Rating의 계수만 &lt;strong&gt;끝까지 남아있다가&lt;/strong&gt; 0으로 사라진다. 그 전에는, Student와 Limit변수의 계수들이 남아있다가 사라졌다. 즉, &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;의 수준에 따라 몇몇 변수만 0인 모델, 즉 &lt;strong&gt;몇몇 변수를 제외한 모델을 만들어 낼 수&lt;/strong&gt; 있는 것이다. 이는 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;의 수준에 따라 그 크기가 shrink하긴 해도 0으로 사라지진 않던 Ridge와 구분되는 특성이다.&lt;/p&gt;

&lt;h3 id=&quot;another-formulation-for-ridge-regression-and-the-lasso&quot;&gt;Another Formulation for Ridge Regression and the Lasso&lt;/h3&gt;

&lt;p&gt;L1 norm을 사용하는 Lasso와 L2 norm을 사용하는 Ridge를 여러 식으로 나타내어 다양한 방식으로 이해를 해볼 수 있다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;blockquote&gt;
    &lt;p&gt;(위에서의 식과 아래의 식은 사실 라그랑주 승수로써 나타낸 동일한 식이다!) 다분히 수학적인 부분이지만, 아주 정리가 잘되있는 &lt;a href=&quot;https://datascienceschool.net/view-notebook/0c66f1810445488baf19cac79305793b/&quot;&gt;참고&lt;/a&gt;&lt;/p&gt;
  &lt;/blockquote&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559428-a910e6be-05a2-11e8-94a9-25c9e5c64536.PNG&quot; alt=&quot;lasso1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이 식은 각각 특정 상수 s일때마다 위의 식들과 완벽하게 같은 결과를 의미한다. s가 무한히 크다면 사실상 제약이 없는, 즉 least square를 의미하게 되고 s가 0에 가까워 질수록 큰 제약, 즉 null model이 된다. 즉 어떠한 상수 s보다 해당 &lt;script type=&quot;math/tex&quot;&gt;\sum&lt;/script&gt;들이 작은 제약 안에서, RSS를 최소화하는 것이다. 이는 변수가 2개일때, lasso의 경우 &lt;script type=&quot;math/tex&quot;&gt;\lvert \beta_1\lvert+\lvert\beta_2\lvert\le s&lt;/script&gt;인 &lt;strong&gt;사각형 공간&lt;/strong&gt;에서 RSS를 최소화하는계수를, ridge의 경우 &lt;script type=&quot;math/tex&quot;&gt;\beta_1^2+\beta_2^2\le s&lt;/script&gt;의 &lt;strong&gt;원공간&lt;/strong&gt; 안에서 RSS를 최소화는 계수를 찾는 &lt;strong&gt;기하학적인 해석&lt;/strong&gt;을 가능하게 한다.(!)&lt;/p&gt;

&lt;p&gt;또한, 이러한 형태의 식은 best subset과 ridge, lasso의 관계를 밝혀주기도 하는데, best subset selection은 다음과 같이 나타낼 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559427-a8d6a7b0-05a2-11e8-92cb-110adf18c403.PNG&quot; alt=&quot;lasso3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;해당 식은 best subset의 의미 그대로 몇개의 &lt;script type=&quot;math/tex&quot;&gt;\beta_j&lt;/script&gt;가 0일때 RSS를 최소화하는 지점을 판단하는 것이다. 그러나 이는 best subset의 단점에서 나왔듯이 각 s마다 &lt;script type=&quot;math/tex&quot;&gt;\begin{pmatrix}p\\s\end{pmatrix}&lt;/script&gt;번의 모델을 계산해야 한다는 한계가 있었다. 이러한 점에서, lasso와 ridge는 위의 &lt;strong&gt;best subset selection의 식&lt;/strong&gt;을 실현 가능한 형태로 &lt;strong&gt;대체한 식&lt;/strong&gt;이라고 볼 수도 있다. 물론, lasso가 명확하게 변수를 없앤다는 점에서 best subset과는 더 유사하다.&lt;/p&gt;

&lt;h3 id=&quot;the-variable-selection-property-of-the-lasso&quot;&gt;The Variable Selection Property of the Lasso&lt;/h3&gt;

&lt;p&gt;그럼 왜? Lasso는 몇몇 계수들을 정확하게 0으로 보내는 성질을 갖는 것일까? 그에 대한 해답은 바로 위에서 했던 Lasso와 Ridge의 기하학적인 해석에서 알 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559426-a88e3f02-05a2-11e8-9d7d-8af8ce422077.PNG&quot; alt=&quot;lasso4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\hat \beta&lt;/script&gt;는 least square의 점이고, 빨간 등고선은 같은 RSS의 선이다. 그리고 왼쪽 그림의 초록색 다이아몬드와 오른쪽 그림의 원이 각각 Lasso와 Ridge의 제약, 즉 &lt;script type=&quot;math/tex&quot;&gt;\lvert\beta_1\lvert+\lvert\beta_2\lvert\le s&lt;/script&gt;과 &lt;script type=&quot;math/tex&quot;&gt;\beta_1^2+\beta_2^2\le s&lt;/script&gt;이다. 각각의 방법은 해당 범위 내에서, 가능한 가장 작은 RSS를 갖는 값으로 계수를 추정한다. (&lt;script type=&quot;math/tex&quot;&gt;s&lt;/script&gt;가 충분히 커서 &lt;script type=&quot;math/tex&quot;&gt;\hat \beta&lt;/script&gt;의 점을 포함하게 된다면 앞에서도 나왔듯이 least square와 같은 값을 추정하게 된다.) 즉 추정된 계수는 &lt;strong&gt;해당 제약범위&lt;/strong&gt;와 가장 작은 &lt;strong&gt;RSS등고선이 만나는 지점&lt;/strong&gt;의 값이 될 것이다.&lt;/p&gt;

&lt;p&gt;그림을 보면 알 수 있지만, Lasso의 제약범위는 &lt;strong&gt;사각형 형태&lt;/strong&gt;라서, 한 축, 즉 &lt;strong&gt;다른 계수가 0인 지점&lt;/strong&gt;에서 쉽게 교점이 생긴다. 예시에서는 &lt;script type=&quot;math/tex&quot;&gt;\beta_2&lt;/script&gt;의 축에서 교점이 생겼으므로, &lt;script type=&quot;math/tex&quot;&gt;\beta_1=0&lt;/script&gt;, 즉 &lt;script type=&quot;math/tex&quot;&gt;X_1&lt;/script&gt;을 제외한 모델을 의미하게된다. 반면 Ridge는 제약범위가 &lt;strong&gt;원의 형태&lt;/strong&gt;라서, 한 계수가 정확히 0인, 즉 &lt;strong&gt;축에서 교점이 생기기가 힘들다&lt;/strong&gt;.(!) 이러한 성질은 차원이 높아질때도 유지된다. 변수가 3개, 즉 3차원일때는 Lasso의 제약범위는 다면체가 되고 Ridge의 제약범위는 구가 된다.&lt;/p&gt;

&lt;h3 id=&quot;comparing-the-lasso-and-ridge-regression&quot;&gt;Comparing the Lasso and Ridge Regression&lt;/h3&gt;

&lt;p&gt;몇몇 변수를 아예 0으로 보내 제외시킨 다는 점에서, Lasso가 Ridge보다 해석력에서 좋다는 것은 명확해졌다. 그렇다면 예측의 정확성 측면에서는 어떨까? &lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559425-a85a14e8-05a2-11e8-8e77-ef50adce607d.PNG&quot; alt=&quot;lasso5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;왼쪽 그림은 이전에 Ridge에서 나왔던 test MSE에 대한 그림의 데이터와 같은 자료로 적합한 Lasso의 test MSE이다. 역시나 초록선은 Variance, 검은선은 bias의 제곱, 분홍선은 test MSE이다.&lt;/p&gt;

&lt;p&gt;오른쪽의 Lasso의 성능(실선)과 Ridge의 성능(점선)을 비교한 그림을 보면, 차이가 있음을 알 수 있다. 이때, 서로 다른 정규화를 쓴 두 방법을 비교하기 위해 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;를 x축으로 두었다. 두 방법 모두 bias는 거의 비슷하지만, Ridge의 Variance가 약간더 낮아, 최종적으로 test MSE도 Ridge가 약간 더 낮음을 알 수 있다. 그러나 이 데이터는 45개의 변수가 모두 Y와 관계가 있는 데이터였다. 즉, 특정계수를 0으로 보내도록 설계된 Lasso에게 불리한 데이터의 상황이다.&lt;/p&gt;

&lt;p&gt;그럼, Lasso에게 유리할만한 데이터, 즉 45개의 변수중 실제론 2개의 변수만이 유의한 경우는 어떨까?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559424-a82dcafa-05a2-11e8-8acc-6fa22dbe5223.PNG&quot; alt=&quot;lasso6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;역시나 예상한 대로, 이번엔 Lasso의 test MSE, 즉 실선이 더 낮은 값을 가진다. 즉, Lasso와 Ridge의 성능의 우위는 &lt;strong&gt;데이터의 상황에 따라&lt;/strong&gt; 다르다. 유의미한 변수가 적을때는 Lasso가, 반대의 경우 Ridge가 더 좋은 성능을 보이는 것이다. 물론, 이를 미리 완벽하게 알 수는 없을 것이므로, 역시나 5장에서 소개되었던 cross-validation의 방법이 사용된다.&lt;/p&gt;

&lt;p&gt;정리해보자면, Lasso 역시 Ridge처럼 약간의 bias를 희생하여 기존의 least square보다 Variance측면에서 좋은, 따라서 더욱 좋은 예측을 보이는 모델을 만들어낸다. 또한 Lasso는 계수를 0으로 보내 변수선택의 효과 역시 가져, 해석력 측면에서 강점을 가지게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;또한 Ridge는 shrink할때 일정 비율로 shrink를 하고, Lasso는 shrink할때 일정 상수로 shrink를 하며, 충분히 작을 경우 0으로 줄인다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;62-3-selecting-the-tuning-parameter&quot;&gt;6.2-3 Selecting the Tuning Parameter&lt;/h2&gt;

&lt;p&gt;Lasso와 Ridge에서 중요한 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 몇으로 설정할 것인지에 대한 문제가 남았다. 이는 언급되었듯이, Cross-validation을 통해 이루어 진다. 몇몇의 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt; 값들을 선정하여, 그 값들에 대해 cross-validation을 하고 가장 작은 cross-validation error를 보인 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 선정한다. 최종적으로 다시 모든 데이터(CV에서는 몇개는 hold out했으니)에 대해 해당 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;로 적합을 하는 것이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559712-4fe50d3a-05a3-11e8-8d8b-65832a9a711b.PNG&quot; alt=&quot;lasso8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;해당 그림은 위의 예시에도 나왔던, 45개(p)의 변수 중 2개만이 유의미한 변수를 가진, (단지) 50개(n)의 자료들을 10-fold CV를 통해 Lasso 적합을 해본 것이다. 왼쪽의 점선은 최적의 cross-validation error를 낸 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;지점으로, 오른쪽의 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;에 따른 계수들을 보았을때, 회색으로 표시된 중요하지 않은 변수들을 모두 0으로 보내고 중요한 변수만이 남은 모델을 만들 수 있는 &lt;script type=&quot;math/tex&quot;&gt;\lambda&lt;/script&gt;를 10-fold CV가 아주 잘 잡아내고 있는 것을 확인할 수 있다.&lt;/p&gt;

&lt;h2 id=&quot;63-dimension-reduction-methods&quot;&gt;6.3 Dimension Reduction Methods&lt;/h2&gt;

&lt;p&gt;지금까지 다뤄온 방법들( 몇개의 변수만을 선택하거나, 계수들을 0으로 shrink하게 하는 방법.)은, 각기 다른 방법으로 variance를 줄이기 위한 방법들이었다. 이들은 모두 원래의 변수, &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_p&lt;/script&gt;를 사용한 방식이었다. 그러나 이번에는, &lt;strong&gt;변수 자체를 변환&lt;/strong&gt;하여 적합하는 방법에 대해 다뤄볼 것이다. 이러한 기법을 차원축소 방법(dimension reduction)이라 부른다.&lt;/p&gt;

&lt;p&gt;차원 축소는 다음과 같은 방식으로 이루어 진다. 기존의 p개의 변수&lt;script type=&quot;math/tex&quot;&gt;X_p&lt;/script&gt;가 아닌, 기존의 변수들의 linear combination으로 만들어진 M개의 새로운 변수&lt;script type=&quot;math/tex&quot;&gt;Z_m&lt;/script&gt;를 만들어 낸다. (M&amp;lt;p이다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559711-4fb675e2-05a3-11e8-89b4-b229b7bba271.PNG&quot; alt=&quot;pc1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;예를 들면 &lt;script type=&quot;math/tex&quot;&gt;Z_1=0.7X_1+0*X_2+...+2.4X_p&lt;/script&gt;와 같은 형태로 기존의 p개보다 적은 M개의 변수들을 만들어 내는 것이다. 그리곤 이 ‘M개의 변수로’, 기존에 했던것 그대로 least square를 이용한 적합을 한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559710-4f82fa6e-05a3-11e8-9db8-072b7c0deb37.PNG&quot; alt=&quot;pc2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이를 통해 기존에 p+1개의 계수들을 추정해야 했던 문제가 M+1개의 계수를 추정하는 문제로 바뀐 것이다. 만약, 올바른 &lt;script type=&quot;math/tex&quot;&gt;Z_m&lt;/script&gt;들, 즉 올바른 선형결합을 만드는 &lt;script type=&quot;math/tex&quot;&gt;\phi_{jm}&lt;/script&gt;들이 만들어 졌다면, 이는 기존의 least square보다 더 좋은 성과를 낼 수도 있다.&lt;/p&gt;

&lt;p&gt;그럼 &lt;script type=&quot;math/tex&quot;&gt;\phi_{jm}&lt;/script&gt;에 대해 알아보기 위해, 우선 다음의 식을 봐보자. 변수 변환 후의 적합된 결과, 즉 &lt;script type=&quot;math/tex&quot;&gt;\theta_mz_{im}&lt;/script&gt;들의 합은 정의를 통한 약간의 변형을 통해 다음의 식으로 다시 표현할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559709-4f4bf6ea-05a3-11e8-91b3-54ad3b54b1f5.PNG&quot; alt=&quot;pc3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;잘보이게 노랑색으로 미리 표시하였는데, 마지막 2개의 등식을 보면 다음과 같은 사실을 알 수 있다.
&lt;script type=&quot;math/tex&quot;&gt;\beta_j=\sum_{m=1}^M\theta_m\phi_{jm}&lt;/script&gt;
즉, 차원축소 방법은 계수 &lt;script type=&quot;math/tex&quot;&gt;\beta_j&lt;/script&gt;들에 위와 같은 &lt;strong&gt;제약&lt;/strong&gt;이 있는 기존의 적합의 특별한 케이스 인것이다. 
&lt;script type=&quot;math/tex&quot;&gt;y_i=\beta_0+\beta_1X_1+...+\beta_pX_p=\beta_0+(\sum_{m=1}^M\theta_m\phi_{1m})X_1+..+(\sum_{m=1}^M\theta_m\phi_{pm})X_p&lt;/script&gt;
이미 여러번 다뤘지만, 제약이 없는 상태에서 최적의 계수를 정하는 것보다, 제약이 있는 상태에서 계수를 정하게 되면 &lt;strong&gt;약간의 bias가 생기기 마련&lt;/strong&gt;이다. 그러나, 변수갯수p가 자료의 수n보다 많을때 M«p개의 변수로 차원을 축소하는 것은 &lt;strong&gt;Variance를 눈에 띄게 감소&lt;/strong&gt;시켜 결과적으로 더 좋은 모델을 만들어 낸다. 만약 M=p이고 모든 &lt;script type=&quot;math/tex&quot;&gt;Z_m&lt;/script&gt;이 선형독립(모든 &lt;script type=&quot;math/tex&quot;&gt;Z_m&lt;/script&gt;들이 다른 변수&lt;script type=&quot;math/tex&quot;&gt;Z_{-m}&lt;/script&gt;의 선형결합으로 표현되지 못하는 것. &lt;a href=&quot;https://ko.wikipedia.org/wiki/%EC%9D%BC%EC%B0%A8%EB%8F%85%EB%A6%BD&quot;&gt;참고&lt;/a&gt;)이라면, 이는 제약이 없는것과 같고 기존의 p개 적합과 같은 결과를 낸다.&lt;/p&gt;

&lt;p&gt;차원 축소 방법은 어떠한 줄어든 변수&lt;script type=&quot;math/tex&quot;&gt;Z_m&lt;/script&gt;을 만들고 거기에 적합을 한다. 그러나 &lt;script type=&quot;math/tex&quot;&gt;Z_m&lt;/script&gt;을 어떠한 선형결합으로 만들어 낼 것인지, 즉 &lt;script type=&quot;math/tex&quot;&gt;\phi_{jm}&lt;/script&gt;을 만들어내는 방법은 다양한 방법이 있다. 여기에선, principal components와 partial east square를 다룰 것이다.&lt;/p&gt;

&lt;h3 id=&quot;63-1principal-components-regression&quot;&gt;6.3-1Principal Components Regression&lt;/h3&gt;

&lt;p&gt;Principal components analysis(줄여서 PCA)는 차원 축소의 매우 대표적인 방법이다. 이는 10장에서 더욱 상세히 나오겠지만, 여기서 간략하게 다루어 본다.&lt;/p&gt;

&lt;h4 id=&quot;an-overview-of-principal-components-analysis&quot;&gt;An Overview of Principal Components Analysis&lt;/h4&gt;

&lt;p&gt;PCA에서는 (n X p)의 크기를 가지고 있는 X를 줄이기 위해, 다음과 같은 방식을 사용한다. 데이터들의 &lt;strong&gt;변동(분산)을 가장 잘 나타낼 수 있는&lt;/strong&gt;, first principal component direction을 찾는다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559708-4efea228-05a3-11e8-9897-13ad616a3d91.PNG&quot; alt=&quot;pc4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;어려워 보이지만 그림으로 보면 이해가 훨씬 쉽다. 위의 그림에서 데이터의 분산을 가장 잘 설명해주는 축은, 초록색 선이다. 초록색 선을 그은 후 각 점들을 선위에 찍어 보면(project 시켜보면) 위의 자료로 낼 수 있는 가장 큰 변동을 표현할 수 있을 것이다. (다른 선을 그으면, 찍힌 점들의 분산이 first component direction의 경우에 비해 더 적을것이다.)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;다른 선으로 project를 시켰을 경우, 점들의 분산이 first component direction에 비해 적다!(왼쪽은 다른 direction, 오른쪽은 first PC)&lt;/p&gt;

  &lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36071502-17bd58c8-0f07-11e8-8b61-cf6bc022f45d.PNG&quot; alt=&quot;PCA&quot; /&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;수식으로 나타내자면, 다음과 같다. (pop가 x, ad가 y이다. 이때, 데이터의 중심에 축을 두고자 변수에 centering을 하고 PCA를 진행한다. Centering은 분산에 영향을 미치지 않기에, 결과는 같다)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559727-525d2020-05a3-11e8-8cfa-ae3852ba5ab1.PNG&quot; alt=&quot;pc5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;즉 첫번째 변수 &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;을 만드는 &lt;script type=&quot;math/tex&quot;&gt;\phi_{11}&lt;/script&gt;과 &lt;script type=&quot;math/tex&quot;&gt;\phi_{21}&lt;/script&gt;은 각각 0.839, 0.544인 것이다. 이 수치들은 다음의 식을 maximize하는 방향으로 계산된 것이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559726-521d658e-05a3-11e8-88a0-35386bfc9e4f.PNG&quot; alt=&quot;pc6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이때, 계수로 인해 분산이 무한으로 커지는 것을 막고자 (&lt;script type=&quot;math/tex&quot;&gt;\phi_{11}^2+\phi_{21}^2=1&lt;/script&gt;이라는 제약을 두고 maximize하는 값을 찾는다. 바꿔 말하면 &lt;script type=&quot;math/tex&quot;&gt;\sum_{j=1}^p\phi_{j1}^2=1&lt;/script&gt;이라는 제약이 있다.)&lt;/p&gt;

&lt;p&gt;이렇게 만들어진 첫번째 변수 &lt;script type=&quot;math/tex&quot;&gt;z_{i1}&lt;/script&gt;들은 principal component &lt;strong&gt;score&lt;/strong&gt;라 불리며, 다음의 그림으로 직관적으로 확인할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559724-51e7c136-05a3-11e8-9cdb-d297b9c6b06b.PNG&quot; alt=&quot;pc7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;왼쪽 그림이 앞 project를 시켜주는 그림이고, 오른쪽 그림이 그 결과 만들어진 principal component scores들이다. 쉽게 축을 잡아 그 축이 x축이 되도록 회전하고 1차원으로 압축했다고 보면 된다.&lt;/p&gt;

&lt;p&gt;또 다른, first principal component에 대한 좀더 직관적인 해석은 데이터와 가능한 가깝게 그은 선이라는 것이다. 즉, 그림에서 점선으로 표시된 수직선들의 거리가 최소가 되도록 선을 그은 것이다. 따라서, first principal component에 project된 결과는 projection중 원래의 데이터와 ‘가능한 가장 가까운’ projection 데이터이다.&lt;/p&gt;

&lt;p&gt;오른쪽 그림에서 큰 파란점이 &lt;script type=&quot;math/tex&quot;&gt;(\bar{pop},\bar{ad})&lt;/script&gt;를 의미하고, first principal component score(&lt;script type=&quot;math/tex&quot;&gt;0.839(pop_i-\bar {pop})+0.544(ad_i-\bar{ad})&lt;/script&gt;)는 (centering을 하였기에) 이 점과의 x축 거리, 즉 수평거리를 의미한다. 이를 통해 pop와 ad의 정보를 하나로 표현할 수 있게 되었는데, 예를 들면 &lt;script type=&quot;math/tex&quot;&gt;z_{i1}=-26.1&lt;/script&gt;이라면 pop와 ad 모두 평균(&lt;script type=&quot;math/tex&quot;&gt;\bar{pop},\bar{ad}&lt;/script&gt;)보다 낮은 값이고, &lt;script type=&quot;math/tex&quot;&gt;z_{i1}=18.7&lt;/script&gt;이라면 pop와 ad값이 모두 평균보다 높은 것이라고 할 수 있게 된다.&lt;/p&gt;

&lt;p&gt;두 변수 ad와 pop가 어느정도 선형관계를 가지고 있고, 그 선형관계를 파악하여 정보를 압축하였으므로, first principal component 하나로 ad와 pop의 대부분의 정보를 포함하였다고 할 수 있다. 이는 그림을 통해서도 확인이 가능한데, ad와 pop모두 first principal component와 강한 관계를 보이고 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559723-51ac40f2-05a3-11e8-8a4c-96605c6e4ba9.PNG&quot; alt=&quot;pc8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;지금까지는 첫번째 principal component만을 이야기 하였지만, 사실은 최대 p개의 다른 component를 만들 수 있다. 두번째 component, &lt;script type=&quot;math/tex&quot;&gt;Z_2&lt;/script&gt;는 &lt;strong&gt;1)&lt;/strong&gt; &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;와 &lt;strong&gt;uncorrelated&lt;/strong&gt;되어 있으면서, &lt;strong&gt;2)&lt;/strong&gt;&lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;이 변수들에 대해 (많은 부분을 설명해주었지만) &lt;strong&gt;미처 설명해주지 못한 부분&lt;/strong&gt;을 설명할 수 있는 방향, 즉 &lt;strong&gt;&lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;의 제약 하에서 가장 분산이 큰 방향&lt;/strong&gt;으로 linear combination이 결정된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559708-4efea228-05a3-11e8-9897-13ad616a3d91.PNG&quot; alt=&quot;pc4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;다시 앞의 그림에서, 아까는 설명하지 않았던 파랑 점선이 바로 second principal component이다.  &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;과 &lt;script type=&quot;math/tex&quot;&gt;Z_2&lt;/script&gt;사이는 zero correlation이 라는 것은, 둘이 직교를 한다는 의미이다. (지금은 변수가 2개뿐이라 2개의 component가 최대지만, 더 높은 다차원에서는 직교하는 ‘여러방향’의 선들을 그을 수 있다. 그들 중 가장 variance가 높은 방향의 선을 긋는다는 의미.)&lt;/p&gt;

&lt;p&gt;변수가 2개뿐이므로, 2개의 principal component로 인해 ‘모든 정보’를 포함하게 되었다. (평균에서 &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;방향으로 얼마나 떨어져 있는지, &lt;script type=&quot;math/tex&quot;&gt;Z_2&lt;/script&gt;방향으로 얼마나 떨어져 있는지) 물론, 첫번째 component에서 대부분의 정보를 포함하게 된다. 이는 Figure 6.15의 오른쪽 그림에서 2nd component score 즉 first component에서 부터의 거리를 나타내는 수치가 1st component score보다 눈에 띄게 작다는 것에서도 드러난다. 따라서 2개의 component를 모두 쓰지 않고 first component만을 쓰는, 즉 차원을 축소할 수도 있는것이다. 변수가 현재는 2개였지만, 많은 변수의 경우에도 &lt;strong&gt;이전의 component들&lt;/strong&gt;에 대해 uncorrelated되어 있으면서도 variance가 가장 큰 방향으로 component를 결정할 수 있다.&lt;/p&gt;

&lt;h3 id=&quot;the-principal-components-regression-approach&quot;&gt;The Principal Components Regression Approach&lt;/h3&gt;

&lt;p&gt;앞에서 간략하게 차원 축소 방법인 PCA에 대해 다뤄보았다. PCR은 이 PCA를 통해 만들어진 &lt;strong&gt;M개의 예측변수들&lt;/strong&gt;을 통해 least square적합을 하는 것이다.&lt;/p&gt;

&lt;p&gt;이는, ‘p개의 변수 &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_p&lt;/script&gt;를 가장 큰 variation으로 나타낼 수 있는 direction이  (즉 데이터의 큰 흐름이) Y와 연관이 있는 방향일 것이다.’ 라는 &lt;strong&gt;가정하에서&lt;/strong&gt; 이루어 지는 분석이다. 이 가정이 항상 참이라는 보장은 없다. (전체에선 정말 지엽적인 특성이 실제 Y와의 관계에 중요한 요소였을수도 있으니) 그러나 상당히 많은 경우 좋은 적합을 보여준다. 또한, 해당 가정이 맞다면 대부분의 정보를 담고 있으나 p개만큼 많지는 않은 M개의 새로운 변수를 적합하면서 overfitting을 완화할수도 있게 된다. (n이 p보다 많이 크지 않다면 least square는 변동성이 큰 결과를 내고 overfitting에 취약해진다는것을 상기하자)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559722-51643e88-05a3-11e8-9b6a-7c9c773ae351.PNG&quot; alt=&quot;pc9&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이는 위의 Lasso, Ridge의 예시에서 나왔던 예시 데이터이다. 각각 왼쪽은 45개 변수가 있고 데이터수 n은 50개이다. 이 중 왼쪽은 45개 모두가 유의미한 변수 인 데이터, 오른쪽은 45개중 2개만이 유의미한 데이터이다. X축은 component의 수, 즉 1은 first principal component만으로 적합을 한 경우를 의미한다. 45는 45개의 component로 적합을 한 경우이므로 모든 정보를 다 사용하였으니 기존의 least square와 같은 결과를 갖는다. 차원을 많이 축소할 수록 least square에 비해 bias는 커지고 variance는 줄어드는 것을 확인할 수 있다.&lt;/p&gt;

&lt;p&gt;그림을 보면, 두 경우 모두 특정 component수에서 test MSE가 줄었지만 45개가 유의미한 경우 적당한 component에서 상당한 성능 증가를 보였다. 그러나 45개중 2개만이 유의미한 경우, 즉 전체데이터의 특성이 실제 Y와의 관계에 큰 비중을 차지하지 않는 경우 사실상 component수가 거의 45에 육박하는 것을 볼 수 있다. (사실 두 경우 모두 Ridge와 Lasso보다 test MSE가 높다.)&lt;/p&gt;

&lt;p&gt;이를 통해 알 수 있듯이, PCR은 그 기본가정을 만족하였을때, 즉 &lt;strong&gt;몇몇의 component로 데이터의 variation을 잘 나타낼 수&lt;/strong&gt; 있고, 이것이 &lt;strong&gt;실제 반응변수 Y와 관계가 있을때&lt;/strong&gt; 큰 성능을 발휘한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559721-5123c272-05a3-11e8-9353-01f2b153b9d2.PNG&quot; alt=&quot;pc10&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이는 해당 가정을 만족하는 simulated 된 데이터이다. 왼쪽 그림을 보면, 처음 5개의 component로 데이터를 거의 완벽하게 설명할 수 있고, 따라서 5개의 component로 PCR을 하는 것이 상당한 성능의 증가를 보였다. 이는 오른쪽의 Lasso, Ridge의 적합결과 보다도 (살짝) 더 좋은 성능이다.&lt;/p&gt;

&lt;p&gt;이전의 방법들과 주의할만한 차이점은, PCR은 &lt;strong&gt;변수선택법이 아니다&lt;/strong&gt;라는 것이다. 앞의 &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;이 pop와 ad를 모두 포함한것 처럼, PCR의 M개의 변수들은 &lt;strong&gt;‘모든’ 기존의 p개의 변수가 선형결합으로 포함된&lt;/strong&gt; 변수들이다. 이러한 점에서 PCR은 Lasso보다는 Ridge와 더 관련이 있다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;사실, 수학적으로 PCR은 Ridge의 continuous version이라고도 할 수 있다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;역시나 PCR에서도, 몇개의 component를 사용할 것인지는 주로 cross-validation으로 결정한다. 또한, PCR역시, 높은 variance를 갖는 변수들이 지나치게 주요 component를 선정하는데 영향을 미치게 되므로, PCR component를 계산하기 전에 다음과 같은 식으로 scaling을 해주는 것이 좋다. (Ridge에서 나온 식. 이렇게 함으로써 모든 변수의 표준편차를 1로 만들어준 효과가 된다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559431-a9ee72a4-05a2-11e8-8395-0caa71e3e3d1.PNG&quot; alt=&quot;shrink3&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;63-2-partial-least-squares&quot;&gt;6.3-2 Partial Least Squares&lt;/h3&gt;

&lt;p&gt;앞에서 다룬 PCA는, p개의 변수 &lt;script type=&quot;math/tex&quot;&gt;X_1,..,X_p&lt;/script&gt;의 관계를 잘 나타내는 direction을 찾는 비지도적인(unsupervised) 방법이다. 쉽게 말해 principal component를 고려하는데 Y는 쳐다보지도(supervised하지) 않았다는 의미이다. 이는 앞에서 언급되는 PCR의 단점으로 귀결되는데, 예측변수들의 관계를 가장 잘 설명하는 direction이 &lt;strong&gt;반응변수를 설명하는 예측변수들을 가장 잘 설명하는 direction이 아닐 수 있다&lt;/strong&gt;는 것이다.&lt;/p&gt;

&lt;p&gt;이러한 단점을 보완하고자 PCR의 supervised한 버젼이 partial least squares (혹은 PLS)이다. PLS는 PCR처럼 기존 변수들의 선형결합으로 M개의 새로운 변수 &lt;script type=&quot;math/tex&quot;&gt;Z_1,..,Z_M&lt;/script&gt;을 만들어 least square 적합을 하지만, 이번엔 M개의 변수를 supervised한 방식으로 만들어 낸다. 즉, Y역시 바라봄으로 써 단순히 기존변수들의 관계를 잘 드러내는 변수를 만들어내는 것이 아니라, &lt;strong&gt;반응변수와 관계된 변수들의 관계&lt;/strong&gt;를 잘 드러내려 하는 것이다.&lt;/p&gt;

&lt;p&gt;그럼, PLS는 어떤식으로 만들어질까? 먼저 첫번째 변수 &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;에서의 &lt;script type=&quot;math/tex&quot;&gt;\phi_{j1}&lt;/script&gt;은, 단순히 &lt;script type=&quot;math/tex&quot;&gt;Y\sim X_j&lt;/script&gt;의 &lt;strong&gt;선형적합의 계수들로써&lt;/strong&gt; 만들어진다. 아래의 식 상기.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559711-4fb675e2-05a3-11e8-89b4-b229b7bba271.PNG&quot; alt=&quot;pc1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;즉, &lt;script type=&quot;math/tex&quot;&gt;j=1,..,p&lt;/script&gt; 개의 변수를 각각 하나만 포함하여 Y에 적합을 한 계수들을 사용하는 것이다. &lt;script type=&quot;math/tex&quot;&gt;Y\sim X_j&lt;/script&gt;의 선형적합의 계수는 하나의 변수만 들어 있으므로, 사실 &lt;script type=&quot;math/tex&quot;&gt;Y&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;X_j&lt;/script&gt;의 &lt;strong&gt;상관관계(correlation)와 비례&lt;/strong&gt;한다. 따라서 Y변수와 높은 상관관계에 있는 변수에 더 많은 가중치를 부여하게 된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559720-50e926f8-05a3-11e8-9f81-e4110c7a9d0a.PNG&quot; alt=&quot;pc11&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이는 같은 데이터에 PLS를 적합한 것이다. 점선이 PCR, 초록실선이 PLS이다. 해당 데이터에서 pop가 Y와 상관관계가 더 높았기에, 기울기가 좀더 완만한, 즉 ad를 좀 덜 반영하는 direction을 찾게 되었다. 따라서 당연한 얘기지만 PLS는 PCR만큼 기존의 변수들에 잘 부합하지는 않지만, 반응변수Y를 설명하는데에는 더 뛰어나다.&lt;/p&gt;

&lt;p&gt;2번째 변수는, 각 변수를 &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;에 적합하고 잔차(residual)을 통해 계산한다. 이는 &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;에 의해 설명되지 않은, uncorrelated (혹은 orthogonalized)data를 의미한다. 이 데이터를 가지고, &lt;script type=&quot;math/tex&quot;&gt;Z_1&lt;/script&gt;에서 했듯이 각각을 Y에 적합하여 계수들을 합하는 식으로 &lt;script type=&quot;math/tex&quot;&gt;Z_2&lt;/script&gt;를 만든다. 기본적으로 첫번째 변수가 설명하지 못한 정보를 가장 잘 설명하는 두번째 변수를 만든다는 점에서 PCR과 유사한 작동원리이다.&lt;/p&gt;

&lt;p&gt;PCR과 마찬가지로, PLS역시 변수들을 표준화한 후 계산해야하고, 몇개의 direction을 만들것인지는 cross-validation을 통해 알아본다. 그러나 실제에선 PLS는 supervised라는 점에서 bias는 줄여주지만 그에 상응하여 variance가 높아지기에 PCR이나 Ridge만큼의 성능을 보이지 못하는 경우가 많다. (띄용)&lt;/p&gt;

&lt;h2 id=&quot;64-consideration-in-high-dimension&quot;&gt;6.4 Consideration in High Dimension&lt;/h2&gt;

&lt;h3 id=&quot;64-1-high-dimensional-data&quot;&gt;6.4-1 High-Dimensional Data&lt;/h3&gt;

&lt;p&gt;거의 모든 전통적인 통계기법은 low-dimension, 즉 n이 p보다 훨씬 더 많은 경우를 다루고자 고안된 기법들이다. (여기서 dimension은 ‘p에 관한 dimension’을 의미한다. ) 그러나 모든것이 정보화되는 시대에, 오히려 변수가 더 많아지는 경우도 등장을 하기 마련이다. 극단적인 예로 사람의 DNA를 통한 혈압예측을 하려하면, 유의미한 변수가 몇십만개도 넘을 것이다. 이러한 high-dimension의 문제에서는 전통적인 least square가 제대로 작동하지 못하고 앞서 다루었던 방법들이 빛을 내게 된다. (물론 bias-variance trade-off의 측면에서 overfitting을 방지하고자 n&amp;gt;p인 경우에도 사용되기도 한다.)&lt;/p&gt;

&lt;h3 id=&quot;64-2-what-goes-wrong-in-high-dimensions&quot;&gt;6.4-2 What Goes Wrong in High Dimensions?&lt;/h3&gt;

&lt;p&gt;그럼, 다차원에서는 왜 기존의 통계기법들이 제대로 성능을 발휘하지 못할지를 알아보자. 여기서는 least square를 활용한 회귀문제를 다루고 있지만, 이는 다른 전통적인 통계기법, 예를들어 로지스틱 LDA등에 모두 적용되는 논의이다.&lt;/p&gt;

&lt;p&gt;p가 n보다 많거나 비슷한 경우, least square방법은 모든 변수를 활용하여 데이터에 ‘완벽하게’ 적합한 모델, 즉 residual이 0인 모델을 만들어 버린다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35559717-50a9d390-05a3-11e8-8798-abcbb8fa8c5c.PNG&quot; alt=&quot;dim1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이는 변수가 1개일때의 least square 적합을 나타낸 그림이다. 직관적으로도 알수 있듯이, 모든 자료에 &lt;strong&gt;가능한한&lt;/strong&gt; 적합하고자 하는 기존의 방법은 p&amp;gt;n일 경우 그 데이터에 완벽하게 일치하게 적합을 하고 만다.(해당 그림에선 모수의 갯수가 2인데 자료도 2개인 완벽적합이다.) 데이터를 통해 알수 없던 실재 관계를 알아보고자 하는 통계기법의 목적에서, 이는 좋지 못한 결과이다. 바꿔 말하자면 이는 완벽한 overfitting이다. 즉 p&amp;gt;n의 경우 기존의 least square 방법은 지나치게 flexible한 방법이 된다.&lt;/p&gt;

&lt;p&gt;극단적인 예로 모든 X변수가 Y변수와 관계없는, 사실상 잘못된 변수들을 갖고 있다 하더라도 least square는 변수를 추가할 수록 높은 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;를 낼 것이고, 그에 따라 training MSE는 0으로 수렴하게 될것이다. 실제에서도 몇몇 유의미한 변수에 다른 의미없는 변수를 추가하는것은 bias는 (기대값의 측면에선) 아주아주 조금 낮출 수 있더라도 Variance가 커지게 되므로 지양되어야 한다.&lt;/p&gt;

&lt;p&gt;물론 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;를 조정하여 test MSE를 추정하기 위한 다양한 지표, 즉 &lt;script type=&quot;math/tex&quot;&gt;C_p, AIC, BIC&lt;/script&gt;등이 있지만, high dimension에서는 위의 수식에 필요한 &lt;script type=&quot;math/tex&quot;&gt;\hat \sigma^2&lt;/script&gt;자체를 계산하기 힘들다는 문제가 있다. &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;를 추정하는데 사용되었던 SSE가 high dimension에선 완벽적합이 되어 0이 되버리기 때문이다. (이 경우 adj R같은 경우는 1이 나오게 되버린다.) 따라서 high-dimension에서는 이를 활용하기 힘들다.&lt;/p&gt;

&lt;h4 id=&quot;64-3-regression-in-high-dimensions&quot;&gt;6.4-3 Regression in High Dimensions&lt;/h4&gt;

&lt;p&gt;high dimension에서는, 앞서 다루었던 덜 flexible한 방법들이 강점을 갖게 된다. 얼핏 예측 변수로 사용할것이 더 많은 high dimension은 더 좋은것 아닌가, 라는 생각을 할 수 있다. 물론 추가된 변수가 실제 Y와 높은 관계가 있는 변수라면 적합에 도움이 되겠지만, 추가된 변수가 &lt;strong&gt;반응변수Y와 실제 관계가 별로 없는 변수&lt;/strong&gt;라면 오히려 이를 포함한 모델의 test error는 증가한다. 이러한 noise feature들은 차원은 증가시키면서도 overfitting의 위험은 높이는 작용을 하게 된다. 이렇듯 차원이 증가함으로써 생기는 분석의 어려움을 통틀어 ‘차원의 저주’라고 부른다.&lt;/p&gt;

&lt;h3 id=&quot;64-4-interpreting-results-in-high-dimensions&quot;&gt;6.4-4 Interpreting Results in High Dimensions&lt;/h3&gt;

&lt;p&gt;high dimension을 다룰때는 주의할점이 많다. 분석자는, 변수가 무수히 많으면 그만큼 correlated되 있을 가능성도 많은 것이고, 이는 분석의 안정성을 저해할 수 있다는 것을 인지해야 한다. 예를 들어 수십만개의 예측변수를 가지고 있는 DNA데이터에서 변수선택법을 통해 17개의 변수를 골라 training data를 잘 설명했다 하자. 이는, 실제로도 예측에 좋은 성능을 보일 수는 있겠지만, 17개의 변수가 DNA를 설명하는 best변수라고 말해주는 것은 아니다. train data에서는 우연히 잘 안드러 났으나 17개의 변수와 상관관계가 매우 높은 다른 변수가 실제로 DNA를 설명하기 위한 best변수 였을수도 있는 것이다.&lt;/p&gt;

&lt;p&gt;또한, p&amp;gt;n의 경우 앞에서도 언급되었듯이 기존의 평가지표, 즉 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;이나 MSE를 사용하면 안된다. 별개의 test set이나 Cross validation을 통해 측정된 error를 보고하는 것이 모델의 평가지표로 의미가 있다. 이렇듯, 특히 high dimension에서는 모델의 해석에 유의하여야 한다.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;참고 : ridge regression의 분산 : https://onlinecourses.science.psu.edu/stat857/node/155&lt;/p&gt;

&lt;p&gt;ridge regression의 biased성질 : http://statweb.stanford.edu/~tibs/sta305files/Rudyregularization.pdf&lt;/p&gt;

&lt;p&gt;아주 정리가 잘되있는 라그랑주 : https://datascienceschool.net/view-notebook/0c66f1810445488baf19cac79305793b/&lt;/p&gt;

&lt;p&gt;deviance에 대한 설명 :  https://stats.stackexchange.com/questions/194224/deviance-and-saturated-models&lt;/p&gt;

&lt;p&gt;Lasso, Ridge에 대한 전반적인 설명 : http://www.stat.cmu.edu/~ryantibs/advmethods/notes/highdim.pdf&lt;/p&gt;
</description>
        <pubDate>Wed, 07 Feb 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/02/07/ISL-Linear-Model-Selection-and-Regularization_ch6.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/02/07/ISL-Linear-Model-Selection-and-Regularization_ch6.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[NLP] Show and Tell: A Neural Image Caption Generator 논문 리뷰</title>
        <description>
&lt;p&gt;show and tell 논문 리뷰&lt;/p&gt;

&lt;p&gt;https://arxiv.org/abs/1411.4555&lt;/p&gt;

&lt;h3 id=&quot;abstract&quot;&gt;Abstract&lt;/h3&gt;

&lt;p&gt;CNN을 사용한 Encoding과 RNN을 사용하여 image를 보고 sentence generating을 하는 neural net을 만들었다. 학습은 likelihood를 maximize하는 방향으로 학습하였다. 우리의 모델(NIC)는 양적평가(BLEU등), 질적평가에서 모두 뛰어났다. image description을 가진 size가 더 늘어나면 NIC의 성능도 증가할 것이다.&lt;/p&gt;

&lt;h3 id=&quot;1-introduction&quot;&gt;1. Introduction&lt;/h3&gt;

&lt;p&gt;이미지의 내용을 적절한 문장으로 설명해내는 것은 기존의 computer vision의 주된 목표였던 이미지 classification이나 object recognition문제보다 훨씬 어려운 문제이다. 단순히 이미지에 들어있는 object를 잡아내는 것이 아니라 그들의 특성, 하고 있는 활동, 다른 object와의 관계 까지 이해해야 하기 때문이다. 뿐만 아니라 이해한 바를 자연어로써 표현하려면 language model 역시 필요하게 된다.&lt;/p&gt;

&lt;p&gt;과거에는 machine translation은, 단어를 각각 해석하고, 이를 정렬하는 등의 여러개의 분리된 작업들이 따로 따로 연구되었지만 최근의 RNN은 이를 훨씬 쉬우면서도 뛰어난 성능으로써 해낼 수 있다는걸 보여주었다. “encoder” RNN이 source sentence를 읽고 이를 fixed-length vector representation으로 바꾸면, “decoder” RNN이 그에 기반하여 target sentence 를 만들어 낸다.&lt;/p&gt;

&lt;p&gt;여기에서는 해당 구조에서 encoder RNN을 CNN으로 대체한 방식을 선보인다. 알다시피, CNN은 input image를 fixed-length vector로써 임베딩함으로써 이미지에 대한 우수한 representation을 만들어 낼 수 있다. 따라서, 이미지 분류를 목적으로 &lt;strong&gt;pre-train된 CNN의 last hidden layer&lt;/strong&gt;를 &lt;strong&gt;decoder RNN의 input으로 넣어 sentence를 만들어내는 형식&lt;/strong&gt;의 구조이다. 즉 기존의 sentence를 받던 모델에서 input이 (convolution 연산을 거친) image로 바뀐 것이다. 이로써 이미지 input이 들어오면 바로 target sequence of words의 likelihood를 maximize할 수 있는 single joint model(&lt;strong&gt;end-to-end 시스템&lt;/strong&gt;)을 선보이고자 한다. 이를 Neural Image Caption(NIC)라 부를것이다.&lt;/p&gt;

&lt;p&gt;앞에서 언급했듯이 이는 end-to-end 시스템이다. (기존의 두가지 방법을 따로 합치던것과 다르다는 의미인듯). 전체 neural net이 &lt;strong&gt;SGD&lt;/strong&gt;를 이용하여 학습된다. 구체적으로는 machine translation에서 자주 사용되는(사실 다른 분야에도 많이쓰이는) target sentence의 likelihood를 최대화하는 방식으로 학습을 한다.&lt;/p&gt;

&lt;p&gt;(뒤에도 언급되지만, CNN은 pre-trained된 모델이고 RNN이 해당 방식으로 학습된다. 그리고 여기서 RNN은 전통적인 vanilla RNN을 의미하는게 아닌, 전반적인 recursive model을 지칭하는 단어로 쓰인다.)&lt;/p&gt;

&lt;p&gt;이렇게 함으로써 기존의 최상의 결과보다 훨씬 뛰어난 성능을 보였다. Pascal dataset에서 기존의 모델의 BLEU 점수(높을 수록 좋음)가 25 였던 반면 NIC는 59점을 기록하여, 사람의 점수 69와도 비교할만한 성능을 보였다. 또한 더큰 corpora에 pre-trained되어 더 좋은 성능을 기대할 수 있다.&lt;/p&gt;

&lt;h3 id=&quot;2-related-work&quot;&gt;2. Related Work&lt;/h3&gt;

&lt;p&gt;object recognition에서 attribute와 location도 인식할 수 있게 되면서, 이를 이용하여 description을 generate하려는 시도들이 있었으나 이는 수작업이 많이 들어가고 text generation의 표현력이 좋지 못하다.&lt;/p&gt;

&lt;p&gt;다른 시도는 &lt;strong&gt;이미지와 description을 같은 벡터공간에 co-embedding&lt;/strong&gt;해서 이미지와 비슷한 embedding공간에 있는 description을 반환하는 모델이 있었다. 그러나 이는 새로운 description은 만들어내지 못한다. 즉 training data에 있던 object라도 보지 못한 관계(unseen composition)를 맺고 있으면 이에 대한 description을 만들지 못한다. 또한 반환된 description의 평가 역시 할 수 없다.&lt;/p&gt;

&lt;p&gt;또한, 기존에도 해당 논문과 비슷한 모델이 나온바 있으나 여기서는 더욱 powerful하고 direct한 RNN model을 사용하여 RNN이 text로 설명되는 object를 더 잘 받아들일(keep track) 수 있도록 만들었고, 그에따라 성능이 눈에 띄게 증가하였다.&lt;/p&gt;

&lt;h3 id=&quot;3-model&quot;&gt;3. Model&lt;/h3&gt;

&lt;p&gt;최근의 연구에 따르면 올바른 sequence model하에서, correct translation의 확률을 maximizing하는 방향으로 train을 하는 것이 성능이 좋다고 알려져 있다. 이러한 방식으로 기존의 encoder decoder RNN은 input을 고정된 차원의 벡터로 encoding하고 이를 sentence로 decode하게 된다. 이와 같은 형식을 image translation에도 적용하였다.&lt;/p&gt;

&lt;p&gt;즉 주어진 이미지에 대해 correct description에 대한 확률을 maximize하도록 하는것 인데, 식으로 나타내면 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560187-8c80dcd2-05a4-11e8-8441-fd92bb1a4559.PNG&quot; alt=&quot;show1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;모든 경우에 대해 input image &lt;script type=&quot;math/tex&quot;&gt;I&lt;/script&gt;가 주어졌을때의 correct description &lt;script type=&quot;math/tex&quot;&gt;S&lt;/script&gt;의 확률을 최대화 할 수 있는 parameter &lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;를 구하는 것이다.&lt;/p&gt;

&lt;p&gt;이때 description S는 길이가 정해져있지 않다. 최적의 문장이 몇개의 단어로 이루어졌는지는 그때그때 다를테니까. 따라서 실제 답(description)의 길이가 N개의 단어라면 그 답에 대한 확률은 고정된 수식이 아니라 다음과 같이 &lt;script type=&quot;math/tex&quot;&gt;S_0,..,S_N&lt;/script&gt;까지의 확률을 결합확률로 나타내야 한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560186-8c3d87f2-05a4-11e8-946a-38d8f9b94b74.PNG&quot; alt=&quot;show2&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;수식 t=1이어야 될꺼같은데..
&lt;script type=&quot;math/tex&quot;&gt;p(S|I)=p(S_1|I,S_0)p(S_2|I,S_0,S_1)..p(S_N|I,S_0,..,S_t-1)&lt;/script&gt;&lt;/p&gt;

  &lt;p&gt;즉 (I가 주어졌을때의 0번째 단어가 &lt;script type=&quot;math/tex&quot;&gt;S_0&lt;/script&gt;일 확률) X (I, &lt;script type=&quot;math/tex&quot;&gt;S_0&lt;/script&gt;이 주어졌을때의 1번째 단어가 &lt;script type=&quot;math/tex&quot;&gt;S_1&lt;/script&gt;일 확률) X …의 형태인 것이다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;train 과정에서는 이미지와 실제 description이 &lt;script type=&quot;math/tex&quot;&gt;(S,I)&lt;/script&gt;의 pair로 주어지고, 위의 식에 따라 최적화를 한다. (SGD를 사용하였다.)&lt;/p&gt;

&lt;p&gt;식은 조금 복잡해보이지만 t-1번째까지의 단어가 주어졌을때 t번째 단어에 대한 확률 &lt;script type=&quot;math/tex&quot;&gt;p(S_t\lvert I,S_0,..,S_{t-1})&lt;/script&gt;은 RNN으로 간단하게 구현이 되는 데, t-1번까지의 ‘조건’들이 fixed length 인 hidden state &lt;script type=&quot;math/tex&quot;&gt;h_t&lt;/script&gt;로 표현이 되는 것이다. 알다시피 이 hidden state는 새로운 input &lt;script type=&quot;math/tex&quot;&gt;x_t&lt;/script&gt;가 들어오면 non-linear 함수를 거쳐 새로 업데이트 된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560183-8bca7bb8-05a4-11e8-8309-44bb539322dd.PNG&quot; alt=&quot;show4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이 때 RNN의 성능을 향상시키기 위해 다음 2가지가 고려되었다. &lt;strong&gt;1)&lt;/strong&gt; 어떤 non-linear function을 써야할까 &lt;strong&gt;2)&lt;/strong&gt; 어떤 방식으로 이미지와 단어가 &lt;script type=&quot;math/tex&quot;&gt;x_t&lt;/script&gt;로써 들어갈 수 있을까&lt;/p&gt;

&lt;p&gt;non-linear로는 성능이 뛰어나다 알려진 LSTM를 사용하였다. (non-linear라길래 Relu 그런걸 생각했는데 LSTM의 update방식을 통틀어서 non-linear라 부른듯하다.) 또한 image representation으로는 object recognition, detection에 뛰어난 성능을 보이는 CNN을 사용하였다. 이때, batch normalization을 사용하였다.&lt;/p&gt;

&lt;h3 id=&quot;31-lstm-based-sentence-generator&quot;&gt;3.1 LSTM-based Sentence Generator&lt;/h3&gt;

&lt;p&gt;LSTM을 택한 주된 이유는 vanishing gradient문제를 잘 해결해주기 때문이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560181-8b8e41c0-05a4-11e8-85f0-e8af14d52226.PNG&quot; alt=&quot;show5-LSTM&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이해를 돕기 위해 논문에서 제시된 그림보다 직관적인 그림은 다음과 같다.(&lt;a href=&quot;http://colah.github.io/posts/2015-08-Understanding-LSTMs/&quot;&gt;참고&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35672650-1cca790e-0737-11e8-8390-fe804a342a6a.PNG&quot; alt=&quot;LSTM&quot; /&gt;&lt;/p&gt;

&lt;p&gt;LSTM은 매 input마다 업데이트 되는 memory cell C가 핵심 요소이다. 이 cell C는 3개의 gate가 각각 곱해지며 통제를 받는데, gate가 0이면 값을 반영을 하지 않고, 1이면 반영을 하는 형태이다. 3개의 gate는 각각 현재의 cell 값을 ‘잊을지 말지’를 통제하는 &lt;strong&gt;forget gate(f)&lt;/strong&gt;, 어떤 input을 반영해줄지를 통제하는 &lt;strong&gt;input gate(i)&lt;/strong&gt;, 어떤 것을 output으로 내보낼지를 통제하는 &lt;strong&gt;output gate(o)&lt;/strong&gt;가 있다. 위의 그림에서 3개의 &lt;script type=&quot;math/tex&quot;&gt;\sigma&lt;/script&gt;가 각각 순서대로의 gate이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560179-8b4d5cbe-05a4-11e8-88a9-4f3f68f5380b.PNG&quot; alt=&quot;show5-LSTM2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;각각에 대한 수식은 위와 같다. (위의 수식에선 hidden state를 &lt;script type=&quot;math/tex&quot;&gt;m_t&lt;/script&gt;로 나타냈다.)&lt;/p&gt;

&lt;p&gt;최종적으로는 &lt;script type=&quot;math/tex&quot;&gt;m_t&lt;/script&gt;에 softmax를 씌워 모든 단어에 대한 확률 &lt;script type=&quot;math/tex&quot;&gt;p_t&lt;/script&gt;를 만들어 낸다.&lt;/p&gt;

&lt;h4 id=&quot;training&quot;&gt;Training&lt;/h4&gt;

&lt;p&gt;이러한 구조를 가진 LSTM은 이미지와 이전까지의 단어(&lt;script type=&quot;math/tex&quot;&gt;S_0&lt;/script&gt;부터 &lt;script type=&quot;math/tex&quot;&gt;S_{t-1}&lt;/script&gt;)를 토대로 다음단어(&lt;script type=&quot;math/tex&quot;&gt;S_t&lt;/script&gt;)를 예측해내도록 학습된다. 위의 LSTM을 recurrent한 그림이 아닌 unfold된 그림으로 그리면 다음과 같다. 물론 펼쳐놓았을뿐 각각의 LSTM은 parameter를 share한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560178-8b1998c0-05a4-11e8-985f-8c53dfa0c312.PNG&quot; alt=&quot;show5-LSTM3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이때 &lt;script type=&quot;math/tex&quot;&gt;S_t&lt;/script&gt;는 &lt;strong&gt;각각 dictionary size의 차원인 one-hot vector&lt;/strong&gt;이다. &lt;script type=&quot;math/tex&quot;&gt;S_0&lt;/script&gt;과 &lt;script type=&quot;math/tex&quot;&gt;S_N&lt;/script&gt;은 각각 시작과 끝을 나타내는 special stop word로 지정하였다. 또한 각각의 단어 S에 word embedding &lt;script type=&quot;math/tex&quot;&gt;W_e&lt;/script&gt;를 해줌으로써 CNN을 통한 image representation과 word가 같은 차원에 있도록 하였다. 즉 첫번째 input, &lt;script type=&quot;math/tex&quot;&gt;S_{-1}&lt;/script&gt;은 CNN(I)이고, 여기서 나온 hidden state이 두번째 input &lt;script type=&quot;math/tex&quot;&gt;S_0&lt;/script&gt;와 합쳐져 결과적으로 output &lt;script type=&quot;math/tex&quot;&gt;S_1&lt;/script&gt;과 새로운 hidden state를 만드는 것이다. 추가로 매 time step마다 image를 따로 넣어주는 방식을 시도해 보았으나, 이는 경험적으로 overfitting의 더 안좋은 결과를 낫는것으로 밝혀졌다.&lt;/p&gt;

&lt;p&gt;이때의 loss는 각 step에서의 negative log likelihood의 합이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560177-8adf4990-05a4-11e8-9c84-87cd987ca103.PNG&quot; alt=&quot;show6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이를 최소화 시키는 방향으로 LSTM의 parameter와 word embedding &lt;script type=&quot;math/tex&quot;&gt;W_e&lt;/script&gt;, CNN의 image embedding을 하는 top layer를 학습한다.&lt;/p&gt;

&lt;h4 id=&quot;inference&quot;&gt;inference&lt;/h4&gt;

&lt;p&gt;sentence를 만드는 방법은 여러가지가 있는데, 첫번째 방법은 &lt;script type=&quot;math/tex&quot;&gt;p_1&lt;/script&gt;에 따라 첫번째 단어를 만들고, 이를 다시 input으로 넣어줘 &lt;script type=&quot;math/tex&quot;&gt;p_2&lt;/script&gt;를 만들고, 이를 end-of-sentence 토큰이 나오거나 최대 길이가 될때까지 반복하는 Sampling기법이 있다. (각 단계에서 최고의 하나의 단어만을 뽑기에, 매우 greedy한 방법이다. 이는 하나의 단어가 잘못될 경우 그에 기반한 모든 결과가 망가지는 위험이 있다. )&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;사실 위에서 설명한 그림은 sampling 방식과 더 가까운데…아마 설명의 편의를 위해서 그런것 같다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;두번째로는 매 t번째까지의 input으로 만들어진 최적의 문장 k개를 후보로 저장하고 또 그 후보들로 만든 t+1번째까지의 문장 중 k개의 문장을 반환하는 것이다. 이를 &lt;strong&gt;BeamSearch&lt;/strong&gt;라고 한다.&lt;/p&gt;

&lt;p&gt;여기에선 BeamSearch 방식으로 실험을 진행하였고, k=20으로 하였다. k=1일 경우 결과의 BLEU수치는 평균적으로 2점정도 내려갔다.(그럼 5개의 description에 20개의 상당히 다른 문장들. 어떻게 Loss를 만드는걸까. 이는 좀더 찾아보자!)&lt;/p&gt;

&lt;h3 id=&quot;4-experiments&quot;&gt;4. Experiments&lt;/h3&gt;

&lt;h4 id=&quot;41-evaluation-metrics&quot;&gt;4.1 Evaluation Metrics&lt;/h4&gt;

&lt;p&gt;주어지지 않은 이미지에 대한 description에 대한 평가 척도는 선행연구들에서 많이 제안되었다. 물론 제일 좋은 것은 사람들에게 평가를 맡기는 것이지만, 선행연구에서 사람들의 평가와 평가척도가 어느정도 일치함을 밝혀냈다 한다.&lt;/p&gt;

&lt;p&gt;image description에 가장 많이 쓰이는 척도는 &lt;strong&gt;BLEU&lt;/strong&gt;이다. 이는 reference sentence(예를 들면 사람이 만들어낸 description)와 얼마나 비슷한지로써 답을 평가하는 척도로, 구체적으로는 몇개의 n-gram이 reference sentence와 겹치지를 통해 평가한다. &lt;a href=&quot;https://en.wikipedia.org/wiki/BLEU&quot;&gt;참고&lt;/a&gt; (대부분의 연구는 1-gram, 즉 unigram으로 진행되었다). 우리는 이 BLEU를 이용하였고 이때의 reference sentence와 우리의 generated output은 다음에서 확인할 수 있다. &lt;a href=&quot;http://nic.droppages.com/&quot;&gt;http://nic.droppages.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;BLEU 말고도 우리의 목표 description과 얼마나 가까운지를 평가하기 위해 perplexity를 지표로 사용할 수도 있다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;주어진 이미지에 대해 correct description에 대한 확률을 maximize하도록 했던 입장에서. perplexity는 추정된 단어들에 대한 probability의 역수의 기하평균이다.&lt;/p&gt;

  &lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560187-8c80dcd2-05a4-11e8-8441-fd92bb1a4559.PNG&quot; alt=&quot;show1&quot; /&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;perplexity는 추정된 단어들에 대한 probability의 역수의 기하평균이다. 이는 validation set(정답description이 있다)에 대한 hyper parameter tuning에서는 사용되었으나 논문에서 따로 제시하진 않았다. (연구자들의 추가적인 논의를 위해 다른 평가척도인 ME-TEOR, Cider라는 것도 제시하였다)&lt;/p&gt;

&lt;h3 id=&quot;42-datasets&quot;&gt;4.2 Datasets&lt;/h3&gt;

&lt;p&gt;사용한 데이터셋은 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35560176-8a7d3106-05a4-11e8-93be-881c79b55846.PNG&quot; alt=&quot;show7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;SBU를 제외하고는 모두 ‘5개의 문장’ 라벨이 있다. SBU는 Flikcr에서 유저들이 올린 description이므로 noise가 심한 dataset이라 할 수 있다. 또한 Pascal 데이터는 test를 위해서만 사용하였는데, 나머지 4개의 data set으로 학습을 하고 평가를 하는 식으로 사용되었다.&lt;/p&gt;

&lt;h3 id=&quot;43-results&quot;&gt;4.3 Results&lt;/h3&gt;

&lt;h4 id=&quot;43-1-training-details&quot;&gt;4.3-1 Training Details&lt;/h4&gt;

&lt;p&gt;supervised approach는 많은 데이터를 필요로하지만, 최상의 이미지는 10만개뿐이었다. 고로 데이터가 더 많아지면 더 좋은 결과를 낼것이라 기대한다&lt;/p&gt;

&lt;p&gt;overfitting을 방지하기 위해 &lt;strong&gt;ImageNet을 통해 pretrained된 CNN&lt;/strong&gt;으로  weight initialize를 하였다. word embedding &lt;script type=&quot;math/tex&quot;&gt;W_e&lt;/script&gt;도 pretrained된 것을 써보았으나 효과가 없었다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;CNN을 제외한 weight은 randomly initialized&lt;/li&gt;
  &lt;li&gt;모든 weight은 SGD로 학습, learning rate은 고정(decay 없음)&lt;/li&gt;
  &lt;li&gt;embedding size와 LSTM size는 512로 같다&lt;/li&gt;
  &lt;li&gt;ovrfitting을 방지하기 위해 dropout과 ensemble model&lt;/li&gt;
  &lt;li&gt;hidden unit과 depth를 다양하게&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Dropout과 ensemble은 BLEU의 큰 향상을 보이지 못했다.&lt;/p&gt;

&lt;h4 id=&quot;43-2-generation-results&quot;&gt;4.3-2 Generation Results&lt;/h4&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35732649-2cfc3e76-0812-11e8-9f38-80f0c4bb574e.PNG&quot; alt=&quot;show8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Table1은 여러 평가척도로 내본 성능 결과. 표를 보면 사람보다 좋은 결과가 있는데 실제 비교에선 이만큼 잘하진 못했으므로, 평가척도 역시 더많은 연구가 필요하다. (논문 전반에서 BLEU의 한계를 어필하고 있다.)&lt;/p&gt;

&lt;p&gt;Table2는 이전 연구들의 모델, 그리고 사람과의 성능 비교. 여기서 BLEU는 5명의 사람들이 만들어낸 description을 토대로 만든 BLEU를 평균낸것.&lt;/p&gt;

&lt;p&gt;평가지표는 선행 연구들에서 많이 사용되던 BLEU-4로 하였다. (제시된 Table2에는 BLEU-1을 제시했으면서..)&lt;/p&gt;

&lt;h4 id=&quot;43-3-transfer-learning-data-size-and-label-quality&quot;&gt;4.3-3 Transfer Learning, Data Size and Label Quality&lt;/h4&gt;

&lt;p&gt;한 data set에서 만들어진 모델을 다른 data set에서 평가해서(transfer) domain의 mismatch에도 불구하고 high quality data, more data로 극복가능한지 보았다.&lt;/p&gt;

&lt;p&gt;같은 유저그룹에 의해 만들어져 label이 비슷할 것인 Flickr 30과 Flickr 8로 transfer learning을 해보았다.  Flickr 30로 학습하였을 경우(데이터가 4배 정도 많다) Flickr 8에서 BLEU가 4점 올랐다. 이는 많은 데이터에 기반한 overfitting방지의 역할을 한듯하다.&lt;/p&gt;

&lt;p&gt;MSCOCO는 Flickr 30보다도 5배더 크지만, mismatch도 더 큰 데이터인데, 이 경우 BLEU가 10점 내려갔다. 그러나 여전히 준수한 description을 보였다. 마지막으로 SBU는 크기가 크지만 사람이 만든 description이 아닌 단순 캡션, 즉 좋지 못한 labeling이었는데 MSCOCO로 학습한 모델을 SBU에 돌려보았을때 28점에서 16점으로 떨어졌다.&lt;/p&gt;

&lt;p&gt;고로 크기도 질도 중요하다..domain이 비슷한 data set은 역시 중요하다..&lt;/p&gt;

&lt;h4 id=&quot;43-4-generation-diversity-discussion&quot;&gt;4.3-4 Generation Diversity Discussion&lt;/h4&gt;

&lt;p&gt;generating의 관점에서, 모델이 새로운 caption을 만들어냈는지, 다양하고 high quality인지 보고자 하였다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35672988-11b6ccf6-0738-11e8-9a78-d3a086f3d742.PNG&quot; alt=&quot;show9&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이는 Beam Search방법에서 N개의 best를 뽑은것. 다양한 단어, 다양한 관점에서 문장이 만들어졌다. 이 중 볼드체는 training set에 없었던 문장들이다. 가장 높은 점수의 best문장만으 보았을때는, 80%가 training set의 문장으로, training data가 적으므로(5개 라벨뿐이니) 예시문장을 만들어내게 되었다. 그러나 상위 15개의 generated 문장들을 보았을때는 58점 정도로, 사람과 견줄만한 수준이었음에도 절반정도가 새로운 description이었다. 따라서 다양하고 high quality의 문장을 만들어냈다고 볼 수 있다.&lt;/p&gt;

&lt;h4 id=&quot;43-5-ranking-results&quot;&gt;4.3-5 Ranking Results&lt;/h4&gt;

&lt;p&gt;우리는 좋지 않은 평가 방법이라 생각했지만 다른 연구들이 많이 썼던 ranking score도 써봤는데, 여기서도 좋은 점수가 나왔다.(생략)&lt;/p&gt;

&lt;h4 id=&quot;43-6-human-evaluation&quot;&gt;4.3-6 Human Evaluation&lt;/h4&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35672652-1d23c162-0737-11e8-8dc7-5c69c8b309d1.PNG&quot; alt=&quot;show10&quot; /&gt;&lt;/p&gt;

&lt;p&gt;몇개의 test set에 대해 사람이 바로 평가를 내려보게도 하였다. 그러나 이때 ground truth에 대해 reference sentence 점수차도 많이나 역시나 BLEU가 완벽한 평가지표가 아님을 보였다.&lt;/p&gt;

&lt;h4 id=&quot;43-7-analysis-of-embeddings&quot;&gt;4.3-7 Analysis of Embeddings&lt;/h4&gt;

&lt;p&gt;이전 단어 &lt;script type=&quot;math/tex&quot;&gt;S_{t-1}&lt;/script&gt;을 LSTM의 input으로 넣어주기 위해 사용한 word embedding은 one-hot-encoding과 다르게 dictionary size에 제한되지 않는다.(!) 따라서 다른 모델들과 함께 jointly trained될 수 있다. 다음은 학습된 embedding space에서 근접이웃들의 몇가지 예시이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35672651-1cf6b9ce-0737-11e8-98b9-6fe42710dc24.PNG&quot; alt=&quot;show11&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이렇게 model에서 학습된 관계는 vision component에도 도움을 줄 수 있는데, horse와 pony, donkey를 비슷한 위치에 있음으로 CNN이 horse-looking 동물의 feature를 extract하는 것이 더 수월해진다.(!) 아주 극단적인 케이스, 예를 들어 유니콘(unicorn)이 제시되어도 다른 word embedding과의 근접성으로 인해 추가적인 정보를 줄 것이다.(라고 가정을 했다.)&lt;/p&gt;

&lt;h4 id=&quot;5-추가-제언&quot;&gt;5. 추가 제언&lt;/h4&gt;

&lt;p&gt;추가로 이미지와 텍스트가 각각 있는 unsupervised data에서 image description의 성능을 향상시킬 수 있는 방법을 연구하는 것도 흥미로울 것이당.&lt;/p&gt;
</description>
        <pubDate>Thu, 01 Feb 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/02/01/Show-and-Tell_A-Neural-Image-Caption-Generator-%EB%85%BC%EB%AC%B8-%EB%A6%AC%EB%B7%B0.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/02/01/Show-and-Tell_A-Neural-Image-Caption-Generator-%EB%85%BC%EB%AC%B8-%EB%A6%AC%EB%B7%B0.html</guid>
        
        <category>Deep Learning</category>
        
        <category>NLP</category>
        
        
        <category>딥러닝</category>
        
      </item>
    
      <item>
        <title>발제용ch5 Resampling method</title>
        <description>
&lt;ul&gt;
  &lt;li&gt;이번주 진도가 4,5장입니다. 발제는 30분내로 두개를 다 할것이구, issue는 하나만 만들겟습니당&lt;/li&gt;
  &lt;li&gt;작성자 : 11기 고동영&lt;/li&gt;
  &lt;li&gt;발제용이 아닌 원본 : https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/26/ISL-Resampling-Methods_ch5.html&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;재표본(Resampling)은 통계학에서 빼놓을 수 없는 요소이다. 간단히 말하자면 이는 training set에서 반복해서 sample을 뽑고, 거기에 반복해서 model을 적합시켜보는 것이다. 이는 기존의 training set &lt;strong&gt;전체를 단지 한번만 쓰는것&lt;/strong&gt; 보다 더 &lt;strong&gt;추가적인 정보&lt;/strong&gt;(어떤것이든! 생각보다 많다)를 줄 수 있는데, 예를들면 다음과 같다.&lt;/p&gt;

&lt;p&gt;하나의 training set에 대해 수많은 sample들을 뽑아보고, 거기에 각각 선형회귀적합을 해본다. 이를 통해 기존에 한번만 적합시켰을때는 할 수 없었던, 우리의 model이 데이터가 달라짐에 따라 어느정도 &lt;strong&gt;범위&lt;/strong&gt;에 있을 것인지에 대한 평가를 해볼 수 있게 된다.&lt;/p&gt;

&lt;p&gt;여기에선 가장 많이 쓰이는 resampling method인 Cross-validation과 bootstrap을 다룰 것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;여기 안에 들어간것은 개인적인 참고를 위한 지엽적인 부분이니, 안읽으셔도 됩니다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;51-cross-validation&quot;&gt;5.1 Cross-Validation&lt;/h3&gt;

&lt;p&gt;앞절에서 다루었듯이, test error 와 training error는 다르다. 모델을 적합시키는데 쓰이지 않은, 즉 주어지지 않은 data(test set)에 대한 오류율이 test error인데, 이걸 낮추는게 모델의 최종목적이라 할 수 있다. 반면 training error는 주어진 데이터에 대한 오류율로, 특히나 overfitting의 경우 실제 error율을 과소평가할 수도 있다.&lt;/p&gt;

&lt;p&gt;평가를 하기 위한 test set이 따로 주어져 있다면 좋겠지만, 현실에선 그렇지 않은 경우가 훨씬 많다. (내일의 주가를 예측하는 문제를 생각해보자.) 이를 해결하기 위해 2가지 방법이 쓰이는데, &lt;strong&gt;1)&lt;/strong&gt; training error rate에 수학적인 보정을 가하여 test error를 간접적으로 추정하는것 (6장에서 다룸) &lt;strong&gt;2)&lt;/strong&gt; training set중 몇개를 따로 빼내서(&lt;strong&gt;hold out&lt;/strong&gt;) test error를 &lt;strong&gt;직접적으로 추정&lt;/strong&gt;하는 방법. 여기선 후자의 방법을 다룰 것이다.&lt;/p&gt;

&lt;h4 id=&quot;51-1-the-validation-set-approach&quot;&gt;5.1-1 The Validation set Approach&lt;/h4&gt;

&lt;p&gt;Validation set approach는 test error을 추정하는 가장 간단한 방법인데, 간단하게 우리의 training data를 &lt;strong&gt;random&lt;/strong&gt;하게 &lt;strong&gt;반&lt;/strong&gt; 잘라서, test error 추정을 위해 따로 빼놓는 것이다.(그냥 반이라고 생각하는 경우가 많은데, random하게 잘라야된다. 혹시나 순서에 따른 패턴이 있을수도 있으니!)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428687-55e00e3a-0268-11e8-9685-1b18ca42ce22.PNG&quot; alt=&quot;validation1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;training set에서 떨어져 나온 이 data set들을 &lt;strong&gt;validation set&lt;/strong&gt;이라고 부른다. (남은) training set에서 적합을 시키고 이를 validation set에 대해 error rate(회귀문제에선 대표적으로 MSE로 구한다)를 구하여  test error rate를 추정하는 것이다.&lt;/p&gt;

&lt;p&gt;예를 들어 3장의 회귀분석에서, 자료가 U자형의 띄어 선형적합이 잘 안되는것 같아 다항회귀를 고려하고자 한다. 이때, 어떤 모델(2차항 모델, 3차항모델 등등)이 실제 관계에 잘 적합하는지를 알고 싶다. 그 경우 주어져있던 자료가 392개 라면 이를 196개로 나누어, 하나는 training set으로 적합에 사용하고, 남은 196개의 validation set의 자료를 통해 error rate를 추정해보는 것이다. (선형회귀에서는 계수의 p-value로 이를 알 수 있지만, 복잡한 모델일 수록 이를 구하기 힘들다) 쉽게 말해, 모의고사용 문제를 따로 빼놓아, 평가를 해본다고 생각하면 된다.&lt;/p&gt;

&lt;p&gt;그러나 이 방법은 랜덤하게 &lt;strong&gt;‘반이나’&lt;/strong&gt; 자른다는 점에서, 그 단점이 있다. data set이 어떻게 잘리느냐에 따라서 model의 변동이 심하고, 그에 따라 test MSE의 추정치도 심하게 변화하기 때문이다. 여러 방법에 따른 test MSE를 추정하고자 하였던 원 목적을 생각해보았을때, 이는 좋은 결과가 아니다. (은근히 많이 헷갈려한다. 우리는 model 자체를 평가하려는게 아니다. &lt;a href=&quot;https://stats.stackexchange.com/questions/11602/training-with-the-full-dataset-after-cross-validation?noredirect=1&amp;amp;lq=1&quot;&gt;참고&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428686-559f8554-0268-11e8-9e8c-1cba68b4af35.PNG&quot; alt=&quot;validation2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위의 U자형 자료에 대한 회귀 예시로 돌아와, 왼쪽은 validation set approach를 한번만 해본것, 오른쪽은 10번 반으로 잘라서, 10번 해본것이다. 둘다 2차항 이상으로 적합하는 것에 큰 효과가 없음을 알려주긴 한다. 그러나, &lt;strong&gt;1)&lt;/strong&gt;  model에 따라 (어떻게 반으로 잘렸는지에 따라) &lt;strong&gt;추정된 test MSE의 변동이 천차만별&lt;/strong&gt;이고, 심지어 &lt;strong&gt;최적의 validation MSE를 위한 차수&lt;/strong&gt;도 천차만별이다. (고로 어떤 차수를 쓸것인지 불분명해진다) 또한, &lt;strong&gt;2)&lt;/strong&gt; 자료의 수를 반이나 줄였다는 점에서, &lt;strong&gt;추정의 성능역시 떨어지게&lt;/strong&gt; 된다. 반개의 자료만으로 적합한 모델은, 전체 자료로 적합하였을 경우 모델이 가졌을 test MSE보다 더 클 수 밖에 없다.(덜 정확할테니까) 즉, test error rate를 overestimate하게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;뒤에서 나오겠지만, 사실 validation을 하기 위해 전체 자료 n개 중 일부를 빼는 순간, 전체 데이터(n개)로 할 수 있는 적합의 test error rate에 대한 추정은 아주 약간이라도 overestimate될 수 밖에 없다. 1개라도 더 작은 데이터셋을 가지고 분석을 한것이니까.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;51-2-leave-one-out-cross-validation&quot;&gt;5.1-2 Leave-One-Out Cross-Validation&lt;/h4&gt;

&lt;p&gt;Leave-One-Out Cross-Validation, 줄여서 LOOCV는 이러한 validation set approach의 단점을 줄이고자 하는 방법이다. 이 방법은 validation set으로 반을 잘라내는 것이 아니라, &lt;strong&gt;한개&lt;/strong&gt;만 따로 빼낸다. 그리고 전체 자료n개중 나머지 n-1개의 training set으로 적합을 한뒤, &lt;strong&gt;하나의 자료에 대해서&lt;/strong&gt; error rate를 계산한다. (&lt;script type=&quot;math/tex&quot;&gt;MSE_1=\frac {y_1-\hat y_1}{1}&lt;/script&gt;) 그리고, 위의 방법을 &lt;strong&gt;모든 자료&lt;/strong&gt;에 &lt;strong&gt;반복&lt;/strong&gt;한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428685-55676214-0268-11e8-890b-4333bfc5bdf0.PNG&quot; alt=&quot;validation3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;즉, 모든 자료n을 각각 한번씩 빼고, 각각에 경우 남은 n-1개의 training set 에대해 전부 적합을 한다. 이 경우 각 &lt;strong&gt;추정된 n개의 test MSE&lt;/strong&gt;가 생길 것이고, 이를 최종적으로 &lt;strong&gt;평균&lt;/strong&gt; 내주어, test error를 추정한다. 식으로 나타내면 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428684-552f9af0-0268-11e8-9356-03da7a9c975f.PNG&quot; /&gt;&lt;/p&gt;

&lt;p&gt;사실, 이렇게 나온 LOOCV는 평균을 내기 전에도 모든 n번의 결과에 거의 차이가 없다. (이는 사실 뒤에도 나오지만, 우리의 data에 거의 최대로 맞추어 적합했기 때문. 즉 high variance를 의미한다. 이에 관해서는 뒤에서 더 설명한다)&lt;/p&gt;

&lt;p&gt;LOOCV는, 다음과 같은 장점이 있다. &lt;strong&gt;1)&lt;/strong&gt; 데이터의 반만을 가지고 적합을 하는 validation set approach와 달리, n-1개를 가지고 적합을 하기에 전체 training data의 test MSE에 대해 할 수 있는 거의 가장 정확한 추정을 할 수 있다. 즉, 거의 overestimate 하지 않는다. 바꿔말하면, &lt;strong&gt;bias가 매우 적다&lt;/strong&gt;. &lt;strong&gt;2)&lt;/strong&gt; 어떻게 training/validation을 나누느냐에 따라 결과가 달라졌던 validation set approach에 비해, LOOCV는 n번의 모든 경우를 자르고 평균을 내기에, &lt;strong&gt;결과가 달라지지 않는다.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;데이터를 하나씩 빼서 n번의 적합을 하고 error를 각각 구하는것은 매우 소모적인 일일 수 있다. 그러나 least square로 적합한 선형회귀, 혹은 다항회귀에선, 이전 장에서 정의되었던 leverage statistic을 이용하여 더 빠르게 구할 수도 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428682-54c9e94e-0268-11e8-9d95-2e3cdf811b80.PNG&quot; alt=&quot;validation6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;기존의 MSE를 구하는 식에서 분모에 leverage statistic &lt;script type=&quot;math/tex&quot;&gt;h_i&lt;/script&gt;를 포함한 항이 추가된 식이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;leverage statistic은 least square에서 회귀계수들을 구하기 위한 정규방정식을 푸는 과정에서 자연스레 나오게 된다. 즉 least square로 푼 회귀문제에선 LOOCV는 전혀 어려운 문제가 아니다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;51-3-k-fold-cross-validation&quot;&gt;5.1-3 k-Fold Cross-Validation&lt;/h4&gt;

&lt;p&gt;너무 단순한 validation set approach와 너무 손이 많이 가는 LOOCV. 그들의 중간점이 바로 이 k-fold CV(Cross-Validation)이다. 전체 데이터를 특정한 수 k개(분석자가 정한다.)의  그룹으로 &lt;strong&gt;random&lt;/strong&gt;하게 나눈다. 그리고 첫번째 그룹을 빼고, 남은 k-1개의 그룹으로 모델을 적합시키는 것이다. LOOCV에서 처럼, 이를 k번 반복한다. (첫번째 그룹을 빼서 &lt;script type=&quot;math/tex&quot;&gt;MSE_1&lt;/script&gt;구하고, …, k번째 그룹을 빼서 &lt;script type=&quot;math/tex&quot;&gt;MSE_k&lt;/script&gt; 구하고.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428680-545c1158-0268-11e8-9bcf-df4e25b78b0e.PNG&quot; alt=&quot;validation8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;최종적으로 나온 &lt;strong&gt;k개의 MSE를 평균&lt;/strong&gt;을 내어 test MSE를 추정한다. 식으로는 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428681-5494683c-0268-11e8-8990-de9b638d43d1.PNG&quot; alt=&quot;validation7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;식을 보면 알겠지만, k=n이 되면 LOOCV이다. 실제에서는 k는 주로, 5개, 혹은 10개로 쓰인다. k=10이더라도, 이는 전체 데이터갯수 n번만큼의 적합을 해야했던 LOOCV에 비해 훨씬 수월한 방법이다.(10만개의 데이터셋이 있다 생각해보자) 그럼에도, 아래의 그림에서 볼 수 있듯이, 어떻게 10개의 그룹으로 나누는지에 따라서도 &lt;strong&gt;추정이 크게 변동하지 않는다&lt;/strong&gt;. 왼쪽의 그림은 LOOCV, 오른쪽은 여러번 다르게 잘라본 10-fold CV이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428683-54faf674-0268-11e8-84d9-32fd191b24a3.PNG&quot; alt=&quot;validation5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이렇게 나온 k-fold CV는 LOOCV와 &lt;strong&gt;성능&lt;/strong&gt;에서도 큰 차이를 보이진 않는다.&lt;/p&gt;

&lt;p&gt;추가적으로 뒤에서 다루겠지만, computational 문제 외에도, &lt;strong&gt;bias-variance trade-off의 측면&lt;/strong&gt;에서 LOOCV보다 강점이 있다.&lt;/p&gt;

&lt;h4 id=&quot;51-4-bias-variance-trade-off-for-k-fold-cross-validation&quot;&gt;5.1-4 Bias-Variance Trade-Off for k-Fold Cross-Validation&lt;/h4&gt;

&lt;p&gt;LOOCV와 k-fold CV의 관계에서도, &lt;strong&gt;bias-variance trade-off&lt;/strong&gt;가 등장한다.&lt;/p&gt;

&lt;p&gt;데이터의 반(&lt;script type=&quot;math/tex&quot;&gt;\frac {n}{2}&lt;/script&gt;개)만을 적합에 사용하는 validation set approach에서는, 그 수가 절대적으로 줄어 test error rate를 제대로 추정하지 못할 것(overestimate)이라는 것을 언급했었다.  사실 추정의 bias는 전체 full data를 쓰지 않겠다는 것에서 부터, 이미 전체 자료로 적합한 모델에 대한 test MSE에는 bias가 생길 수 밖에 없다.(&lt;a href=&quot;https://stats.stackexchange.com/questions/154830/10-fold-cross-validation-vs-leave-one-out-cross-validation?noredirect=1&amp;amp;lq=1&quot;&gt;참고&lt;/a&gt;. 추천) 이러한 점에서, &lt;strong&gt;LOOCV는&lt;/strong&gt; 거의 전체 데이터은 n-1개의 데이터를 가지고 적합을 하기에 &lt;strong&gt;근사적으로&lt;/strong&gt; unbiased 한 추정을 할 수 있다. 즉, &lt;strong&gt;bias가 매우 낮다&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;그러나,&lt;/strong&gt; 2장에서 다루었듯이 모델의 test MSE는 bias만으로 결정되지 않는다. (&lt;script type=&quot;math/tex&quot;&gt;Avg({y}_{0}-\hat f({x}_{0}))^2=Var(\hat f({x}_{0}))+[Bias(\hat f({x}_{0}))]^2+Var(\epsilon)&lt;/script&gt; 상기.) 모델의 Variance가 얼마나 적은지도 역시 중요한데, &lt;strong&gt;Variance 의 관점&lt;/strong&gt;에서 LOOCV는 &lt;strong&gt;k-fold CV보다 못하다&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;LOOCV는 낮은 bias를 가지고 있는 반면 높은 variance를 가지고 있다. LOOCV에서 우리가 평균을 취해주는 n개의 적합된 모델들은, 1개의 데이터만을 빼고 적합을 했다는 점에서 거의 동일한 데이터(n-1개 중 n-2개가 동일)를 가지고 적합을 시킨, &lt;strong&gt;거의 동일한 모델&lt;/strong&gt;이다. 바꿔말하면, 그 n개의 적합된 모델들은, 서로간에 &lt;strong&gt;높은정도로 correlated 된&lt;/strong&gt; 모델들이다. 따라서 이 모델들을 합하고 나눈 LOOCV는 높은 Variance를 가지고 있는 것이다. (이는 기초 통계의 수식에서 알 수 있다. &lt;script type=&quot;math/tex&quot;&gt;Var(\sum^n_{i=1} X_i)=\sum_{i=1}^n\sum_{j=1}^n Cov(X_i,X_j)&lt;/script&gt; 고로 ‘highly correlated 된 것들의 평균’의 분산은 ‘correlated 되지 않은 것들의 평균’의 분산보다 더 크다.)&lt;/p&gt;

&lt;p&gt;더 쉽게 말해보자면, 만약 모집단에서 여러개의 training data를 뽑을 수 있다면 그때마다의 LOOCV의 test MSE 추정치는 변동할 것(high Variance)이라는 것이다. overfitting과 비슷하게 생각하면 이해하기 쉽다.&lt;/p&gt;

&lt;p&gt;사실 validation set approach를 제외하고는 모든 CV방법은 서로 어느정도 겹치는 데이터를 가지고 적합을 하게 되고, 그에 따라 추정량의 Variance가 크게 된다.  다만 k=n인 경우, 즉 LOOCV에서 이 correlated가 최대가 된다. 그러나 k-fold의 경우, 각 sample간에 correlated 된 정도가 상대적으로 덜하다. 고로, 조금 &lt;strong&gt;덜 겹치는&lt;/strong&gt;, k-fold CV가 Variance의 측면에서는 LOOCV보다 더 나은 방법이 된다. 쉽게말하자면, variance와 bias의 적당한 타협을 본 방안인 것이다. k가 몇인지에 따라 이 정도도 달라지지만, 주로 k=5, 혹은 10을 사용한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;그러나 전체 데이터 셋이 극단적을 으로 작을 경우 데이터 자체의 noise가 심할 수 있으므로, 이 경우는 LOOCV를 쓰기도 한다. 이 경우는 k-fold도 (높은 bias를 가지고 있으면서도)  높은 variance를 가질 수 있기 때문&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;51-5-cross-validation-on-classification-problems&quot;&gt;5.1-5 Cross-Validation on Classification Problems&lt;/h4&gt;

&lt;p&gt;이 전까지는 양적변수의 상황을 가정하고 MSE를 사용하는 경우에 대한 Cross-Validation을 논하였지만, 이는 질적변수에도 적용할 수 있다. 이 경우, 2장에서 논의 했던 대로 error rate를 측정하는 방식이 조금 달라질 뿐 모든 논의는 동일하다. 구체적으로 LOOCV의 경우 error rate는 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;CV_{(n)}=\frac{1}{n} \sum^n_{i=1}I(y_i\neq y_i)&lt;/script&gt;
예를 들어, 특정 데이터에 다중로지스틱회귀를 하는 것을 생각해보자. 몇차항 적합을 해야 가장 test MSE가 낮을 것인가에 대해 10-fold CV가 역시 좋은 추정을 해줄 수 있다.&lt;/p&gt;
&lt;h3 id=&quot;52-the-bootstrap&quot;&gt;5.2 The Bootstrap&lt;/h3&gt;

&lt;p&gt;Bootstrap은 실제로는 계산하기 어려운 추정량들의 불확실성(uncertainty. 그것이 어떤 통계량의 분산이던, 평균이던 뭐던)을 계산하는데 널리 쓰이는 강력한 통계기법이다. 선형회귀분석에서 계수의 분산같은 경우 수식적으로 표준편차를 구하는 것이 가능하지만, 많은 경우, 사실 정말 많은 경우에 수식적으로 통계량의 특성은 &lt;strong&gt;정확히 구하지 못한다&lt;/strong&gt;. 이 경우, 이 bootstrap이 매우 강력한 툴로써 활용된다.&lt;/p&gt;

&lt;p&gt;예를 들어 미지의 변수 X와 Y만큼의 투자이익을 주는 두 회사에 각각 &lt;script type=&quot;math/tex&quot;&gt;\alpha​&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;1-\alpha​&lt;/script&gt;만큼의 비율을 투자한다 할 때, 전체 risk가 적은, 즉 &lt;script type=&quot;math/tex&quot;&gt;Var(\alpha X+(1-\alpha)Y)​&lt;/script&gt;를 최소화할 수 있는 방향으로 두 회사에 투자하려한다. 이 경우, 간단한 정리를 통해 해당 Var를 최소화하는 비율&lt;script type=&quot;math/tex&quot;&gt;\alpha​&lt;/script&gt;는 다음과 같다는 것을 도출할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428783-ef301fb2-0268-11e8-817f-b98fa08e237a.PNG&quot; alt=&quot;bstrap1&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Var(\alpha X+(1-\alpha)Y)=\alpha^2Var(X)+(1-\alpha)^2Var(Y)+2\alpha(1-\alpha)Cov(X,Y)=f(\alpha)&lt;/script&gt;라 두고&lt;/p&gt;

  &lt;p&gt;위 식은 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;에 대해서 아래로 볼록한 convex 형태이므로, &lt;script type=&quot;math/tex&quot;&gt;\frac {d f(\alpha)}{d\alpha}=0&lt;/script&gt;인 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;를 구하면 된다. 나머지는 단순 전개에 정리하고 식 넘기는것.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;여기서 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2_X=Var(X)&lt;/script&gt;이고, &lt;script type=&quot;math/tex&quot;&gt;\sigma_{XY}=Cov(X,Y)&lt;/script&gt;를 의미한다. 그러나 실제에선, 이를 최소화하는 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;의 식을 구성하는 &lt;script type=&quot;math/tex&quot;&gt;Var(X),Var(Y),Cov(X,Y)&lt;/script&gt;를 알 수 없다. 따라서 이를 가지고 있는 자료를 통해 추정할 수 밖에 없다. 이 경우 식은 다음과 같이 된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428782-eef56cd2-0268-11e8-9bc3-9e81569d09e1.PNG&quot; alt=&quot;bstrap2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;simulated 된 자료, 즉 만든 자료이므로, 여러번 sample을 뽑아 여러번 추정을 해보았더니, 추정된 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;은 0.532~0.657에서 왓다갔다 했다. 그럼, 우리의 추정의 정확도, 즉 추정량 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;의 standard deviation(표준편차)에 대해 알고싶다. 즉, 데이터를 &lt;strong&gt;많이 뽑아 볼 수 있다면&lt;/strong&gt;, 그때마다 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;는 얼마나 변동하는지를 알아보고 싶은 것이다.&lt;/p&gt;

&lt;p&gt;회귀분석과 다르게 어떠한 분포 가정하에서 해당 값들을 구한것도 아니고 수많은 변수들이 복잡하게 얽혀있기에, 우리는 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;의 sd에 대해서 알길이 없다. (위의 식을 알고 있어도 분산은 구할 수 없다.)그러나 이것은 simulated 된 데이터이므로, 이를 단순하게  100개쌍의 데이터를 1000번뽑아서, 어느정도 값이 나오는지, 얼마나 변동했는지 가늠해볼수가 있다.(!) 참고로 이때, 데이터의 true 값들은 다음과 같았다. &lt;script type=&quot;math/tex&quot;&gt;\sigma_x^2=1, \sigma_Y^2=1.25, \sigma_{XY}=0.5&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;1000번의 반복을 통해 만들어진 값들은 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428781-eec31408-0268-11e8-8105-b0a488fc3f3c.PNG&quot; alt=&quot;bstrap3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428780-ee8983be-0268-11e8-990f-a305b4bad029.PNG&quot; alt=&quot;bstrap3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;참값을 알고 있는 시점에서, 추정값들의 평균 &lt;script type=&quot;math/tex&quot;&gt;\bar \alpha&lt;/script&gt;는 true값 0.6에 &lt;strong&gt;매우 근사하다&lt;/strong&gt;. sd의 경우는 참값을 알 수 없지만, 이러한 방식으로 대략 0.08정도라고, 말할 수 있게 되었다.&lt;/p&gt;

&lt;p&gt;이와 같이 수식으로는 계산하기 힘들더라도 실제로 &lt;strong&gt;수없이 많이 뽑아볼 수 있다면&lt;/strong&gt; 그 참값에 매우 근사한 수치를 얻을 수 있다. 그러나 현실에서는, 위와 같이 데이터를 수없이 많이 뽑아볼 수가 없다. 그러나, Bootstrap은 수많은 &lt;strong&gt;새로운 sample들&lt;/strong&gt;을 뽑아내어, 위와 같은 &lt;strong&gt;추론을 가능하게&lt;/strong&gt; 한다.&lt;/p&gt;

&lt;p&gt;어떤식으로 이게 가능할까? Bootstrap은, (위의 simulated data에서 했듯이) 모집단에서 샘플을 계속 새로 뽑는게 아니라, &lt;strong&gt;가지고 있는 원래의 data set&lt;/strong&gt;에서 &lt;strong&gt;복원추출로&lt;/strong&gt; 새로운 샘플을 계속 뽑는다. 그림으로 더욱 직관적인 이해가 가능하다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428779-ee4d669a-0268-11e8-948b-5d7d545763df.PNG&quot; alt=&quot;bstrap5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;원래의 data Z는 3개밖에 없지만, 이를 가지고 복원추출을 반복 한다(이 경우 3개의 데이터로 구한 추정량에 대한 특성을 알고싶은 거기에, 3개 복원추출을 한다!). 그에따라 3번째 자료가 2번뽑힌 sample, 2번째 자료가 2번뽑힌 sample, 등등 수많은 &lt;strong&gt;새로운 sample&lt;/strong&gt;이 생긴다. 이를 충분히 큰 수 B번을 반복하여 복원추출하면, 그에 따라 &lt;strong&gt;B개의 sample&lt;/strong&gt;이 생기고, 그에 따라 &lt;strong&gt;B개의 추정량 &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol {\hat \alpha}&lt;/script&gt;&lt;/strong&gt;가 생기게 된다. 이제 이 B개의  추정량 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;을 가지고, 다음과 같이 SE를 구할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428778-ee0fb106-0268-11e8-84ae-d230f5b84545.PNG&quot; alt=&quot;bstrap6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이에 대한 성능 확인을 위해 앞의 두 회사에 대한 투자의 예시에서, 100개의 data set 한개만을 가지고 bootstrap으로 1000개의 sample을 만들어 추정을 해보았다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428777-edd66b76-0268-11e8-8ea9-28c74725e24a.PNG&quot; alt=&quot;bstrap7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;황색이 앞서 해본 모집단을 반복추출해서 얻은 결과이고, 청색이 하나의 data set만을 가지고 bootstrap으로 반복추출해서 얻은 결과이다. 각 sample에 대해 추정량 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;를 구했을때, 이들의 분포가 매우 유사해보인다. 이는 오른쪽의 박스플롯을 통해서도 확인할 수 있다. 실제로 bootstrap을 통해 구해본 &lt;script type=&quot;math/tex&quot;&gt;SE(\hat\alpha)=0.087&lt;/script&gt;로, 모집단을 통해 구해본 0.083과 상당히 유사하다. 이러한 방식을 통해, 적은 수의 data set을 가지고 구하기 힘든 통계량의 특성까지도 구할 수 있게 되는 것이다.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;참고&lt;/p&gt;

&lt;p&gt;LOOCV의 variance가 크다 : https://stats.stackexchange.com/questions/178388/high-variance-of-leave-one-out-cross-validation&lt;/p&gt;

&lt;p&gt;모델의 하이퍼파라미터를 test하는게 아니다 : https://stats.stackexchange.com/questions/11602/training-with-the-full-dataset-after-cross-validation?noredirect=1&amp;amp;lq=1&lt;/p&gt;

&lt;p&gt;LOOCV와 k-fold의 bias variance(추천) : https://stats.stackexchange.com/questions/154830/10-fold-cross-validation-vs-leave-one-out-cross-validation?noredirect=1&amp;amp;lq=1&lt;/p&gt;
</description>
        <pubDate>Fri, 26 Jan 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/26/%EB%B0%9C%EC%A0%9C%EC%9A%A9ch5-Resampling-method.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/26/%EB%B0%9C%EC%A0%9C%EC%9A%A9ch5-Resampling-method.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[ISL] 5장 - Resampling Methods(CV, Bootstrap)이해하기</title>
        <description>
&lt;p&gt;재표본(Resampling)은 통계학에서 빼놓을 수 없는 요소이다. 간단히 말하자면 이는 training set에서 반복해서 sample을 뽑고, 거기에 반복해서 model을 적합시켜보는 것이다. 이는 기존의 training set &lt;strong&gt;전체를 단지 한번만 쓰는것&lt;/strong&gt; 보다 더 &lt;strong&gt;추가적인 정보&lt;/strong&gt;(어떤것이든! 생각보다 많다)를 줄 수 있는데, 예를들면 다음과 같다.&lt;/p&gt;

&lt;p&gt;하나의 training set에 대해 수많은 sample들을 뽑아보고, 거기에 각각 선형회귀적합을 해본다. 이를 통해 기존에 한번만 적합시켰을때는 할 수 없었던, 우리의 model이 데이터가 달라짐에 따라 어느정도 &lt;strong&gt;범위&lt;/strong&gt;에 있을 것인지에 대한 평가를 해볼 수 있게 된다.&lt;/p&gt;

&lt;p&gt;여기에선 가장 많이 쓰이는 resampling method인 Cross-validation과 bootstrap을 다룰 것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;여기 안에 들어간것은 개인적인 참고를 위한 지엽적인 부분이니, 안읽으셔도 됩니다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3 id=&quot;51-cross-validation&quot;&gt;5.1 Cross-Validation&lt;/h3&gt;

&lt;p&gt;앞절에서 다루었듯이, test error 와 training error는 다르다. 모델을 적합시키는데 쓰이지 않은, 즉 주어지지 않은 data(test set)에 대한 오류율이 test error인데, 이걸 낮추는게 모델의 최종목적이라 할 수 있다. 반면 training error는 주어진 데이터에 대한 오류율로, 특히나 overfitting의 경우 실제 error율을 과소평가할 수도 있다.&lt;/p&gt;

&lt;p&gt;평가를 하기 위한 test set이 따로 주어져 있다면 좋겠지만, 현실에선 그렇지 않은 경우가 훨씬 많다. (내일의 주가를 예측하는 문제를 생각해보자.) 이를 해결하기 위해 2가지 방법이 쓰이는데, &lt;strong&gt;1)&lt;/strong&gt; training error rate에 수학적인 보정을 가하여 test error를 간접적으로 추정하는것 (6장에서 다룸) &lt;strong&gt;2)&lt;/strong&gt; training set중 몇개를 따로 빼내서(&lt;strong&gt;hold out&lt;/strong&gt;) test error를 &lt;strong&gt;직접적으로 추정&lt;/strong&gt;하는 방법. 여기선 후자의 방법을 다룰 것이다.&lt;/p&gt;

&lt;h4 id=&quot;51-1-the-validation-set-approach&quot;&gt;5.1-1 The Validation set Approach&lt;/h4&gt;

&lt;p&gt;Validation set approach는 test error을 추정하는 가장 간단한 방법인데, 간단하게 우리의 training data를 &lt;strong&gt;random&lt;/strong&gt;하게 &lt;strong&gt;반&lt;/strong&gt; 잘라서, test error 추정을 위해 따로 빼놓는 것이다.(그냥 반이라고 생각하는 경우가 많은데, random하게 잘라야된다. 혹시나 순서에 따른 패턴이 있을수도 있으니!)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428687-55e00e3a-0268-11e8-9685-1b18ca42ce22.PNG&quot; alt=&quot;validation1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;training set에서 떨어져 나온 이 data set들을 &lt;strong&gt;validation set&lt;/strong&gt;이라고 부른다. (남은) training set에서 적합을 시키고 이를 validation set에 대해 error rate(회귀문제에선 대표적으로 MSE로 구한다)를 구하여  test error rate를 추정하는 것이다.&lt;/p&gt;

&lt;p&gt;예를 들어 3장의 회귀분석에서, 자료가 U자형의 띄어 선형적합이 잘 안되는것 같아 다항회귀를 고려하고자 한다. 이때, 어떤 모델(2차항 모델, 3차항모델 등등)이 실제 관계에 잘 적합하는지를 알고 싶다. 그 경우 주어져있던 자료가 392개 라면 이를 196개로 나누어, 하나는 training set으로 적합에 사용하고, 남은 196개의 validation set의 자료를 통해 error rate를 추정해보는 것이다. (선형회귀에서는 계수의 p-value로 이를 알 수 있지만, 복잡한 모델일 수록 이를 구하기 힘들다) 쉽게 말해, 모의고사용 문제를 따로 빼놓아, 평가를 해본다고 생각하면 된다.&lt;/p&gt;

&lt;p&gt;그러나 이 방법은 랜덤하게 &lt;strong&gt;‘반이나’&lt;/strong&gt; 자른다는 점에서, 그 단점이 있다. data set이 어떻게 잘리느냐에 따라서 model의 변동이 심하고, 그에 따라 test MSE의 추정치도 심하게 변화하기 때문이다. 여러 방법에 따른 test MSE를 추정하고자 하였던 원 목적을 생각해보았을때, 이는 좋은 결과가 아니다. (은근히 많이 헷갈려한다. 우리는 model 자체를 평가하려는게 아니다. &lt;a href=&quot;https://stats.stackexchange.com/questions/11602/training-with-the-full-dataset-after-cross-validation?noredirect=1&amp;amp;lq=1&quot;&gt;참고&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428686-559f8554-0268-11e8-9e8c-1cba68b4af35.PNG&quot; alt=&quot;validation2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위의 U자형 자료에 대한 회귀 예시로 돌아와, 왼쪽은 validation set approach를 한번만 해본것, 오른쪽은 10번 반으로 잘라서, 10번 해본것이다. 둘다 2차항 이상으로 적합하는 것에 큰 효과가 없음을 알려주긴 한다. 그러나, &lt;strong&gt;1)&lt;/strong&gt;  model에 따라 (어떻게 반으로 잘렸는지에 따라) &lt;strong&gt;추정된 test MSE의 변동이 천차만별&lt;/strong&gt;이고, 심지어 &lt;strong&gt;최적의 validation MSE를 위한 차수&lt;/strong&gt;도 천차만별이다. (고로 어떤 차수를 쓸것인지 불분명해진다) 또한, &lt;strong&gt;2)&lt;/strong&gt; 자료의 수를 반이나 줄였다는 점에서, &lt;strong&gt;추정의 성능역시 떨어지게&lt;/strong&gt; 된다. 반개의 자료만으로 적합한 모델은, 전체 자료로 적합하였을 경우 모델이 가졌을 test MSE보다 더 클 수 밖에 없다.(덜 정확할테니까) 즉, test error rate를 overestimate하게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;뒤에서 나오겠지만, 사실 validation을 하기 위해 전체 자료 n개 중 일부를 빼는 순간, 전체 데이터(n개)로 할 수 있는 적합의 test error rate에 대한 추정은 아주 약간이라도 overestimate될 수 밖에 없다. 1개라도 더 작은 데이터셋을 가지고 분석을 한것이니까.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;51-2-leave-one-out-cross-validation&quot;&gt;5.1-2 Leave-One-Out Cross-Validation&lt;/h4&gt;

&lt;p&gt;Leave-One-Out Cross-Validation, 줄여서 LOOCV는 이러한 validation set approach의 단점을 줄이고자 하는 방법이다. 이 방법은 validation set으로 반을 잘라내는 것이 아니라, &lt;strong&gt;한개&lt;/strong&gt;만 따로 빼낸다. 그리고 전체 자료n개중 나머지 n-1개의 training set으로 적합을 한뒤, &lt;strong&gt;하나의 자료에 대해서&lt;/strong&gt; error rate를 계산한다. (&lt;script type=&quot;math/tex&quot;&gt;MSE_1=\frac {y_1-\hat y_1}{1}&lt;/script&gt;) 그리고, 위의 방법을 &lt;strong&gt;모든 자료&lt;/strong&gt;에 &lt;strong&gt;반복&lt;/strong&gt;한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;MSE_1=\frac {y_1-\hat y_1}{1}&lt;/script&gt;는 사실 통계적으로는 test error에 대한 ‘거의’ unbiased한 estimator이다. (n-1개로 적합했으므로) 그러나 갯수가 1개 이므로, 매우 변동이 큰 estimator 일것이다. 사실 직관적으로 봐도 자료 1개로 추정하는건 부정확할 것 이라는건 이해할 수 있다.&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;p&gt;또하나의 헷갈리는점. n개의 데이터로 적합한 것의 (training) MSE는, test MSE에 대한 ‘unbiased’ estimator이다!(주의. 실제 함수에 대해 unbiased라는게 아님. test MSE에 unbiased) 근데 왜 training MSE로 안쓰냐, 혹은 근데 왜 training MSE는 이리 욕을 먹느냐? 그건 바로 unbiased이지만 Variance가 어마어마하기 때문. 수많은 random error를 가지고 발생한 데이터들을 가지고 적합한 모델의 training MSE의 ‘Expectation’은 test MSE이지만, 그 수많은 random error들로 인한 Variance가 있다. 그걸 보완해주고자 validation을 하는것. 이 경우 unbiased측면에선 약간의 손실이 생기지만(bias가 생기지만), 약간의 bias가 생긴 모델들을 ‘여러번’ 적합하여 평균낸다는 점에서 variance가 줄어든다.&lt;/p&gt;
  &lt;/blockquote&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428685-55676214-0268-11e8-890b-4333bfc5bdf0.PNG&quot; alt=&quot;validation3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;즉, 모든 자료n을 각각 한번씩 빼고, 각각에 경우 남은 n-1개의 training set 에대해 전부 적합을 한다. 이 경우 각 &lt;strong&gt;추정된 n개의 test MSE&lt;/strong&gt;가 생길 것이고, 이를 최종적으로 &lt;strong&gt;평균&lt;/strong&gt; 내주어, test error를 추정한다. 식으로 나타내면 다음과 같다.&lt;/p&gt;

&lt;div class=&quot;pull-right&quot;&gt;

&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428684-552f9af0-0268-11e8-9356-03da7a9c975f.PNG&quot; /&gt;

&lt;/div&gt;

&lt;p&gt;사실, 이렇게 나온 LOOCV는 평균을 내기 전에도 모든 n번의 결과에 거의 차이가 없다. (이는 사실 뒤에도 나오지만, 우리의 data에 거의 최대로 맞추어 적합했기 때문. 즉 high variance를 의미한다. 이에 관해서는 뒤에서 더 설명한다)&lt;/p&gt;

&lt;p&gt;LOOCV는, 다음과 같은 장점이 있다. &lt;strong&gt;1)&lt;/strong&gt; 데이터의 반만을 가지고 적합을 하는 validation set approach와 달리, n-1개를 가지고 적합을 하기에 전체 training data의 test MSE에 대해 할 수 있는 거의 가장 정확한 추정을 할 수 있다. 즉, 거의 overestimate 하지 않는다. 바꿔말하면, &lt;strong&gt;bias가 매우 적다&lt;/strong&gt;. &lt;strong&gt;2)&lt;/strong&gt; 어떻게 training/validation을 나누느냐에 따라 결과가 달라졌던 validation set approach에 비해, LOOCV는 n번의 모든 경우를 자르고 평균을 내기에, &lt;strong&gt;결과가 달라지지 않는다.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;데이터를 하나씩 빼서 n번의 적합을 하고 error를 각각 구하는것은 매우 소모적인 일일 수 있다. 그러나 least square로 적합한 선형회귀, 혹은 다항회귀에선, 이전 장에서 정의되었던 leverage statistic을 이용하여 더 빠르게 구할 수도 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428682-54c9e94e-0268-11e8-9d95-2e3cdf811b80.PNG&quot; alt=&quot;validation6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;기존의 MSE를 구하는 식에서 분모에 leverage statistic &lt;script type=&quot;math/tex&quot;&gt;h_i&lt;/script&gt;를 포함한 항이 추가된 식이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;leverage statistic은 least square에서 회귀계수들을 구하기 위한 정규방정식을 푸는 과정에서 자연스레 나오게 된다. 즉 least square로 푼 회귀문제에선 LOOCV는 전혀 어려운 문제가 아니다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;51-3-k-fold-cross-validation&quot;&gt;5.1-3 k-Fold Cross-Validation&lt;/h4&gt;

&lt;p&gt;너무 단순한 validation set approach와 너무 손이 많이 가는 LOOCV. 그들의 중간점이 바로 이 k-fold CV(Cross-Validation)이다. 전체 데이터를 특정한 수 k개(분석자가 정한다.)의  그룹으로 &lt;strong&gt;random&lt;/strong&gt;하게 나눈다. 그리고 첫번째 그룹을 빼고, 남은 k-1개의 그룹으로 모델을 적합시키는 것이다. LOOCV에서 처럼, 이를 k번 반복한다. (첫번째 그룹을 빼서 &lt;script type=&quot;math/tex&quot;&gt;MSE_1&lt;/script&gt;구하고, …, k번째 그룹을 빼서 &lt;script type=&quot;math/tex&quot;&gt;MSE_k&lt;/script&gt; 구하고.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428680-545c1158-0268-11e8-9bcf-df4e25b78b0e.PNG&quot; alt=&quot;validation8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;최종적으로 나온 &lt;strong&gt;k개의 MSE를 평균&lt;/strong&gt;을 내어 test MSE를 추정한다. 식으로는 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428681-5494683c-0268-11e8-8990-de9b638d43d1.PNG&quot; alt=&quot;validation7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;식을 보면 알겠지만, k=n이 되면 LOOCV이다. 실제에서는 k는 주로, 5개, 혹은 10개로 쓰인다. k=10이더라도, 이는 전체 데이터갯수 n번만큼의 적합을 해야했던 LOOCV에 비해 훨씬 수월한 방법이다.(10만개의 데이터셋이 있다 생각해보자) 그럼에도, 아래의 그림에서 볼 수 있듯이, 어떻게 10개의 그룹으로 나누는지에 따라서도 &lt;strong&gt;추정이 크게 변동하지 않는다&lt;/strong&gt;. 왼쪽의 그림은 LOOCV, 오른쪽은 여러번 다르게 잘라본 10-fold CV이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428683-54faf674-0268-11e8-84d9-32fd191b24a3.PNG&quot; alt=&quot;validation5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이렇게 나온 k-fold CV는 LOOCV와 &lt;strong&gt;성능&lt;/strong&gt;에서도 큰 차이를 보이진 않는다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428679-5421a43c-0268-11e8-9923-68ab23c72244.PNG&quot; alt=&quot;validation9&quot; /&gt;&lt;/p&gt;

&lt;p&gt;simulated 된 data이므로 실제 true test MSE와 비교를 하였는데, 실제 함수 관계가 다양한 flexible (순서대로 적당히 flexible, 안 flexible, 많이 flexible)인 경우에 대하여 test MSE와 CV test MSE의 선이다. 파랑이 true test MSE, 주황이 10-fold CV, 검은 점선이 LOOCV로 구한 test MSE의 추정선이다. LOOCV와 10-fold CV가 거의 비슷한 선을 그리고 있음을 볼 수 있다.&lt;/p&gt;

&lt;p&gt;추가적으로 뒤에서 다루겠지만, computational 문제 외에도, &lt;strong&gt;bias-variance trade-off의 측면&lt;/strong&gt;에서 LOOCV보다 강점이 있다.&lt;/p&gt;

&lt;h4 id=&quot;51-4-bias-variance-trade-off-for-k-fold-cross-validation&quot;&gt;5.1-4 Bias-Variance Trade-Off for k-Fold Cross-Validation&lt;/h4&gt;

&lt;p&gt;LOOCV와 k-fold CV의 관계에서도, &lt;strong&gt;bias-variance trade-off&lt;/strong&gt;가 등장한다.&lt;/p&gt;

&lt;p&gt;데이터의 반(&lt;script type=&quot;math/tex&quot;&gt;\frac {n}{2}&lt;/script&gt;개)만을 적합에 사용하는 validation set approach에서는, 그 수가 절대적으로 줄어 test error rate를 제대로 추정하지 못할 것(overestimate)이라는 것을 언급했었다.  사실 추정의 bias는 전체 full data를 쓰지 않겠다는 것에서 부터, 이미 전체 자료로 적합한 모델에 대한 test MSE에는 bias가 생길 수 밖에 없다.(&lt;a href=&quot;https://stats.stackexchange.com/questions/154830/10-fold-cross-validation-vs-leave-one-out-cross-validation?noredirect=1&amp;amp;lq=1&quot;&gt;참고&lt;/a&gt;. 추천) 이러한 점에서, &lt;strong&gt;LOOCV는&lt;/strong&gt; 거의 전체 데이터은 n-1개의 데이터를 가지고 적합을 하기에 &lt;strong&gt;근사적으로&lt;/strong&gt; unbiased 한 추정을 할 수 있다. 즉, &lt;strong&gt;bias가 매우 낮다&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;그러나,&lt;/strong&gt; 2장에서 다루었듯이 모델의 test MSE는 bias만으로 결정되지 않는다. (&lt;script type=&quot;math/tex&quot;&gt;Avg({y}_{0}-\hat f({x}_{0}))^2=Var(\hat f({x}_{0}))+[Bias(\hat f({x}_{0}))]^2+Var(\epsilon)&lt;/script&gt; 상기.) 모델의 Variance가 얼마나 적은지도 역시 중요한데, &lt;strong&gt;Variance 의 관점&lt;/strong&gt;에서 LOOCV는 &lt;strong&gt;k-fold CV보다 못하다&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;LOOCV는 낮은 bias를 가지고 있는 반면 높은 variance를 가지고 있다. LOOCV에서 우리가 평균을 취해주는 n개의 적합된 모델들은, 1개의 데이터만을 빼고 적합을 했다는 점에서 거의 동일한 데이터(n-1개 중 n-2개가 동일)를 가지고 적합을 시킨, &lt;strong&gt;거의 동일한 모델&lt;/strong&gt;이다. 바꿔말하면, 그 n개의 적합된 모델들은, 서로간에 &lt;strong&gt;높은정도로 correlated 된&lt;/strong&gt; 모델들이다. 따라서 이 모델들을 합하고 나눈 LOOCV는 높은 Variance를 가지고 있는 것이다. (이는 기초 통계의 수식에서 알 수 있다. &lt;script type=&quot;math/tex&quot;&gt;Var(\sum^n_{i=1} X_i)=\sum_{i=1}^n\sum_{j=1}^n Cov(X_i,X_j)&lt;/script&gt; 고로 ‘highly correlated 된 것들의 평균’의 분산은 ‘correlated 되지 않은 것들의 평균’의 분산보다 더 크다.)&lt;/p&gt;

&lt;p&gt;더 쉽게 말해보자면, 만약 모집단에서 여러개의 training data를 뽑을 수 있다면 그때마다의 LOOCV의 test MSE 추정치는 변동할 것(high Variance)이라는 것이다. overfitting과 비슷하게 생각하면 이해하기 쉽다.&lt;/p&gt;

&lt;p&gt;사실 validation set approach를 제외하고는 모든 CV방법은 서로 어느정도 겹치는 데이터를 가지고 적합을 하게 되고, 그에 따라 추정량의 Variance가 크게 된다.  다만 k=n인 경우, 즉 LOOCV에서 이 correlated가 최대가 된다. 그러나 k-fold의 경우, 각 sample간에 correlated 된 정도가 상대적으로 덜하다. 고로, 조금 &lt;strong&gt;덜 겹치는&lt;/strong&gt;, k-fold CV가 Variance의 측면에서는 LOOCV보다 더 나은 방법이 된다. 쉽게말하자면, variance와 bias의 적당한 타협을 본 방안인 것이다. k가 몇인지에 따라 이 정도도 달라지지만, 주로 k=5, 혹은 10을 사용한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;그러나 전체 데이터 셋이 극단적을 으로 작을 경우 데이터 자체의 noise가 심할 수 있으므로, 이 경우는 LOOCV를 쓰기도 한다. 이 경우는 k-fold도 (높은 bias를 가지고 있으면서도)  높은 variance를 가질 수 있기 때문&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;51-5-cross-validation-on-classification-problems&quot;&gt;5.1-5 Cross-Validation on Classification Problems&lt;/h4&gt;

&lt;p&gt;이 전까지는 양적변수의 상황을 가정하고 MSE를 사용하는 경우에 대한 Cross-Validation을 논하였지만, 이는 질적변수에도 적용할 수 있다. 이 경우, 2장에서 논의 했던 대로 error rate를 측정하는 방식이 조금 달라질 뿐 모든 논의는 동일하다. 구체적으로 LOOCV의 경우 error rate는 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;CV_{(n)}=\frac{1}{n} \sum^n_{i=1}I(y_i\neq y_i)&lt;/script&gt;
구체적인 예를 들어, 2장에서 나왔던 데이터에 다중로지스틱회귀를 하는 것을 생각해보자. 이 경우에도, simulated 된 데이터이므로 실제 bayes classifier와 test error를 측정할 수 있다. 가장 기본적인 로지스틱회귀 (&lt;script type=&quot;math/tex&quot;&gt;log(\frac{p}{1-p})=\beta_0+\beta_1X_1+\beta_2X_2&lt;/script&gt;)의 결과는 아래 그림의 왼쪽 위 그림이다. 딱 봐도, 기존의 선형적인 로지스틱 회귀로는 안될 것같다. 따라서 이를 다항회귀에서 했던 그대로, 수정을 가한다. 수정은 간단하게 이런 식으로 하면 된다.
&lt;script type=&quot;math/tex&quot;&gt;log(\frac{p}{1-p})=\beta_0+\beta_1X_1+\beta_2X_1^2+\beta_3X_2+\beta_4X_2^2&lt;/script&gt;
각각의 차수를 높인 경우에 대해 그림이 제시되어 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428678-53ef31aa-0268-11e8-9c78-e4d3bc7a94e9.PNG&quot; alt=&quot;validation10&quot; /&gt;&lt;/p&gt;

&lt;p&gt;4차항 까지 넣엇을때, test error가 조금 높아졌다. 따라서 다항로지스틱회귀로 할 수 있는 최적의 적합은 3차항까지를 추가하는 것이다. 그러나 실제에서는 이를 어떻게 알 수 있을까? 역시, Cross-Validation을 통해 가능하다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428677-53b1fa24-0268-11e8-8516-9c98c06228eb.PNG&quot; alt=&quot;validation11&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그림에서 갈색 선이 실제 Test error, 검은선이 10-fold CV, 파랑선이 training error 이다. 왼쪽은 로지스틱회귀에 대한 그림, 오른쪽은 KNN으로 적합한 것에 대한 그림이다. 파랑색 train error의 경우 flexible 해질수록 감소하지만, test error는 그렇지 않다. 그리고 10-fold CV가 이를 어느정도 잘 잡아내주고 있다.&lt;/p&gt;

&lt;h3 id=&quot;52-the-bootstrap&quot;&gt;5.2 The Bootstrap&lt;/h3&gt;

&lt;p&gt;Bootstrap은 실제로는 계산하기 어려운 추정량들의 불확실성(uncertainty. 그것이 어떤 통계량의 분산이던, 평균이던 뭐던)을 계산하는데 널리 쓰이는 강력한 통계기법이다. 선형회귀분석에서 계수의 분산같은 경우 수식적으로 표준편차를 구하는 것이 가능하지만, 많은 경우, 사실 정말 많은 경우에 수식적으로 통계량의 특성은 &lt;strong&gt;정확히 구하지 못한다&lt;/strong&gt;. 이 경우, 이 bootstrap이 매우 강력한 툴로써 활용된다.&lt;/p&gt;

&lt;p&gt;예를 들어 미지의 변수 X와 Y만큼의 투자이익을 주는 두 회사에 각각 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;1-\alpha&lt;/script&gt;만큼의 비율을 투자한다 할 때, 전체 risk가 적은, 즉 &lt;script type=&quot;math/tex&quot;&gt;Var(\alpha X+(1-\alpha)Y)&lt;/script&gt;를 최소화할 수 있는 방향으로 두 회사에 투자하려한다. 이 경우, 간단한 정리를 통해 해당 Var를 최소화하는 비율&lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;는 다음과 같다는 것을 도출할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428783-ef301fb2-0268-11e8-817f-b98fa08e237a.PNG&quot; alt=&quot;bstrap1&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Var(\alpha X+(1-\alpha)Y)=\alpha^2Var(X)+(1-\alpha)^2Var(Y)+\alpha(1-\alpha)Cov(X,Y)=f(\alpha)&lt;/script&gt;라 두고&lt;/p&gt;

  &lt;p&gt;위 식은 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;에 대해서 아래로 볼록한 convex 형태이므로, &lt;script type=&quot;math/tex&quot;&gt;\frac {d f(\alpha)}{d\alpha}=0&lt;/script&gt;인 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;를 구하면 된다. 나머지는 단순 전개에 정리하고 식 넘기는것.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;여기서 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2_X=Var(X)&lt;/script&gt;이고, &lt;script type=&quot;math/tex&quot;&gt;\sigma_{XY}=Cov(X,Y)&lt;/script&gt;를 의미한다. 그러나 실제에선, 이를 최소화하는 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;의 식을 구성하는 &lt;script type=&quot;math/tex&quot;&gt;Var(X),Var(Y),Cov(X,Y)&lt;/script&gt;를 알 수 없다. 따라서 이를 가지고 있는 자료를 통해 추정할 수 밖에 없다. 이 경우 식은 다음과 같이 된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428782-eef56cd2-0268-11e8-9bc3-9e81569d09e1.PNG&quot; alt=&quot;bstrap2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;simulated 된 자료, 즉 만든 자료이므로, 여러번 sample을 뽑아 여러번 추정을 해보았더니, 추정된 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;은 0.532~0.657에서 왓다갔다 했다. 그럼, 우리의 추정의 정확도, 즉 추정량 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;의 standard deviation(표준편차)에 대해 알고싶다. 즉, 데이터를 &lt;strong&gt;많이 뽑아 볼 수 있다면&lt;/strong&gt;, 그때마다 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;는 얼마나 변동하는지를 알아보고 싶은 것이다.&lt;/p&gt;

&lt;p&gt;회귀분석과 다르게 어떠한 분포 가정하에서 해당 값들을 구한것도 아니고 수많은 변수들이 복잡하게 얽혀있기에, 우리는 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;의 sd에 대해서 알길이 없다. (위의 식을 알고 있어도 분산은 구할 수 없다.)그러나 이것은 simulated 된 데이터이므로, 이를 단순하게  100개쌍의 데이터를 1000번뽑아서, 어느정도 값이 나오는지, 얼마나 변동했는지 가늠해볼수가 있다.(!) 참고로 이때, 데이터의 true 값들은 다음과 같았다. &lt;script type=&quot;math/tex&quot;&gt;\sigma_x^2=1, \sigma_Y^2=1.25, \sigma_{XY}=0.5&lt;/script&gt;&lt;/p&gt;

&lt;p&gt;1000번의 반복을 통해 만들어진 값들은 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428781-eec31408-0268-11e8-8105-b0a488fc3f3c.PNG&quot; alt=&quot;bstrap3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428780-ee8983be-0268-11e8-990f-a305b4bad029.PNG&quot; alt=&quot;bstrap3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;참값을 알고 있는 시점에서, 추정값들의 평균 &lt;script type=&quot;math/tex&quot;&gt;\bar \alpha&lt;/script&gt;는 true값 0.6에 &lt;strong&gt;매우 근사하다&lt;/strong&gt;. sd의 경우는 참값을 알 수 없지만, 이러한 방식으로 대략 0.08정도라고, 말할 수 있게 되었다.&lt;/p&gt;

&lt;p&gt;이와 같이 수식으로는 계산하기 힘들더라도 실제로 &lt;strong&gt;수없이 많이 뽑아볼 수 있다면&lt;/strong&gt; 그 참값에 매우 근사한 수치를 얻을 수 있다. 그러나 현실에서는, 위와 같이 데이터를 수없이 많이 뽑아볼 수가 없다. 그러나, Bootstrap은 수많은 &lt;strong&gt;새로운 sample들&lt;/strong&gt;을 뽑아내어, 위와 같은 &lt;strong&gt;추론을 가능하게&lt;/strong&gt; 한다.&lt;/p&gt;

&lt;p&gt;어떤식으로 이게 가능할까? Bootstrap은, (위의 simulated data에서 했듯이) 모집단에서 샘플을 계속 새로 뽑는게 아니라, &lt;strong&gt;가지고 있는 원래의 data set&lt;/strong&gt;에서 &lt;strong&gt;복원추출로&lt;/strong&gt; 새로운 샘플을 계속 뽑는다. 그림으로 더욱 직관적인 이해가 가능하다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428779-ee4d669a-0268-11e8-948b-5d7d545763df.PNG&quot; alt=&quot;bstrap5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;원래의 data Z는 3개밖에 없지만, 이를 가지고 복원추출을 반복 한다(이 경우 3개의 데이터로 구한 추정량에 대한 특성을 알고싶은 거기에, 3개 복원추출을 한다!). 그에따라 3번째 자료가 2번뽑힌 sample, 2번째 자료가 2번뽑힌 sample, 등등 수많은 &lt;strong&gt;새로운 sample&lt;/strong&gt;이 생긴다. 이를 충분히 큰 수 B번을 반복하여 복원추출하면, 그에 따라 &lt;strong&gt;B개의 sample&lt;/strong&gt;이 생기고, 그에 따라 &lt;strong&gt;B개의 추정량 &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol {\hat \alpha}&lt;/script&gt;&lt;/strong&gt;가 생기게 된다. 이제 이 B개의  추정량 &lt;script type=&quot;math/tex&quot;&gt;\hat \alpha&lt;/script&gt;을 가지고, 다음과 같이 SE를 구할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428778-ee0fb106-0268-11e8-84ae-d230f5b84545.PNG&quot; alt=&quot;bstrap6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이에 대한 성능 확인을 위해 앞의 두 회사에 대한 투자의 예시에서, 100개의 data set 한개만을 가지고 bootstrap으로 1000개의 sample을 만들어 추정을 해보았다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35428777-edd66b76-0268-11e8-8ea9-28c74725e24a.PNG&quot; alt=&quot;bstrap7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;황색이 앞서 해본 모집단을 반복추출해서 얻은 결과이고, 청색이 하나의 data set만을 가지고 bootstrap으로 반복추출해서 얻은 결과이다. 각 sample에 대해 추정량 &lt;script type=&quot;math/tex&quot;&gt;\alpha&lt;/script&gt;를 구했을때, 이들의 분포가 매우 유사해보인다. 이는 오른쪽의 박스플롯을 통해서도 확인할 수 있다. 실제로 bootstrap을 통해 구해본 &lt;script type=&quot;math/tex&quot;&gt;SE(\hat\alpha)=0.087&lt;/script&gt;로, 모집단을 통해 구해본 0.083과 상당히 유사하다. 이러한 방식을 통해, 적은 수의 data set을 가지고 구하기 힘든 통계량의 특성까지도 구할 수 있게 되는 것이다.&lt;/p&gt;

&lt;hr /&gt;

&lt;p&gt;참고&lt;/p&gt;

&lt;p&gt;LOOCV의 variance가 크다 : https://stats.stackexchange.com/questions/178388/high-variance-of-leave-one-out-cross-validation&lt;/p&gt;

&lt;p&gt;모델의 하이퍼파라미터를 test하는게 아니다 : https://stats.stackexchange.com/questions/11602/training-with-the-full-dataset-after-cross-validation?noredirect=1&amp;amp;lq=1&lt;/p&gt;

&lt;p&gt;LOOCV와 k-fold의 bias variance(추천) : https://stats.stackexchange.com/questions/154830/10-fold-cross-validation-vs-leave-one-out-cross-validation?noredirect=1&amp;amp;lq=1&lt;/p&gt;
</description>
        <pubDate>Fri, 26 Jan 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/26/ISL-Resampling-Methods_ch5.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/26/ISL-Resampling-Methods_ch5.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[NLP] Character-Word LSTM Language Models 논문 리뷰</title>
        <description>
&lt;p&gt;char-word LSTM 논문 리뷰&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;박스 안의 내용은 개인적인 이해를 위한 추가적인 부분&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;https://arxiv.org/abs/1704.02813&lt;/p&gt;

&lt;h4 id=&quot;abstract&quot;&gt;Abstract&lt;/h4&gt;

&lt;p&gt;Character-Word를 둘다 사용하는 LSTM으로써 word based의 문제를 해결하고, 파라미터 수를 줄였다. Character 단위의 정보는 단어의 비슷함을 알려주기도 하고 unknown word나 infrequent word 대해서도 적용할 수 있어 모델의 성능을 높여준다. 영어와 네덜란드어에 대하여 실험을 해보았을때, 이 모델이 파라미터가 더 많은 word-level모델에 비해서도 잘 작동하였다.&lt;/p&gt;

&lt;h4 id=&quot;1-introduction&quot;&gt;1. Introduction&lt;/h4&gt;

&lt;p&gt;Language model로 LSTM과 그것의 변형인 GRU(Gated Recurrent Unit)가 많이 사용되었다. LSTM이 더 성능이 좋다고 알려져 있기에, LSTM-based 모델에 집중하였다.&lt;/p&gt;

&lt;p&gt;기존의 neural net Language model은 다음과 같은 결점이 있다. 1). parameter를 최적화하는데 많은 training data를 필요로해서, 빈도수가 적은 단어에 대해서는 parameter 가 부정확하다. 2) 더욱 큰 한계는 one-hot 벡터로써 인코딩을 함으로써 단어 구조 내부의 정보를 사용할 수 없었다는 것.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;예를 들어 ‘felicity’는 ‘더할나위 없는 행복’ 이란 뜻으로, 대부분의 경우OOV(out-of-vocabulary)로 분류되지만, ‘-ity’라는 subword로 끝난다는 점에서 ‘ability’ , ‘complexity’등을 보고 명사라고 판단할 수 있을 것이다. 기존의 모델은 이를 반영할 수 없었다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;blockquote&gt;
  &lt;p&gt;우리는 character와 word embedding을 합침으로써 이런 단어구조의 정보를 활용할 수 있게되었다.  embedding을 합침으로서, 기존의 bag-of-characters 방식(input을 character들의 뭉치로 보는것)과 다르게 철자들의 order를 유지하면서도 각각의 철자 역시 보존할 수 있게 되었다. 또한, 훨씬 작은 차원의 character embedding matrix를 가진 character embedding과 부분적으로 바꾸었으므로, word embedding의 사이즈 역시 축소되게 된다. 이는 결국 파라미터의 감소로 이어진다. (vocabulary의 크기는 embedding size의 크기와 정비례는 아니더라도 비례인듯) 추가로, 비슷한 character sequence가 꼭 앞에만 등장하는것이 아니기에, (ex overfitting, underfitting) character를 forward로 넣어보는 것과 backward로 넣어보는 것을 둘다 해보았다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;논문의 결과를 &lt;strong&gt;먼저 요약&lt;/strong&gt;하자면 다음과 같다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;LSTM에서 word와 subword infomation을 합치는 방법, 즉 word와 character embedding을 합치는 방법을 을 제시하였다&lt;/li&gt;
  &lt;li&gt;word-level 임베딩 사이즈를 줄임으로써, 파라미터의 수를 효과적으로 감소시켰다&lt;/li&gt;
  &lt;li&gt;같은 hidden unit수(고로 더 많은 수의 파라미터)를 가진 word-level 모델과 비교해보고, 같은 파라미터 수를 가진 word-level 모델과도 비교해보았다. char-word model의 성능이 좋았다. 또한, backward order로 character를 넣는 것이 성능이 더 좋았다.&lt;/li&gt;
  &lt;li&gt;모델에 포함되지 않았던, OOV word에 대하여 성능이 좋았다.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;2-related-work&quot;&gt;2. Related Work&lt;/h3&gt;

&lt;p&gt;RNN에서 character-level을 사용하거나 둘의 정보를 합친 연구도 있었고, 형태소나 음절 같은 다른 subword information을 모델링한 연구도 있었다.(어잉?대단한데?) 그러나 여기에선 character 단위의 subword에만 집중한다. 역대 연구 설명들 주르륵…&lt;/p&gt;

&lt;p&gt;CNN에서도 character 단위가 가능했다. char CNN과 highway, LSTM layer를 합하여 좋은 성과를 냈다. 그러나 여기에서 주된 성과는 highway 덕분이었다. high way layer를 없애니 CNN과 LSTM을 가진 모델은 2개의 hidden layer를 가진 기존 word-level 모델보다 성능이 안좋았다 한다. 데이터 양이 많아질 경우는 좀 더 잘했다.&lt;/p&gt;

&lt;h3 id=&quot;3-character-word-lstm-language-models&quot;&gt;3. Character-Word LSTM Language Models&lt;/h3&gt;

&lt;p&gt;기존의 word-level LSTM의 작동은 다음과 같다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;t 번째 단어가 one-hot vector &lt;script type=&quot;math/tex&quot;&gt;w_t​&lt;/script&gt;로써 인코딩된다.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;이 one-hot vector &lt;script type=&quot;math/tex&quot;&gt;w_t&lt;/script&gt;는 embedding matrix &lt;script type=&quot;math/tex&quot;&gt;W_w&lt;/script&gt;가 곱해져, 최종적으로 word embedding &lt;script type=&quot;math/tex&quot;&gt;e_t&lt;/script&gt;를 만들어 낸다.&lt;/p&gt;

    &lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316684-e6853892-00ca-11e8-879e-22477bda6b6c.PNG&quot; alt=&quot;char-lstm-embed&quot; /&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;이 &lt;script type=&quot;math/tex&quot;&gt;e_t&lt;/script&gt;는 non-linear operation인 LSTM layer에 들어가고 최종적으로 output layer에서 softmax로 다음에 올 단어에 대한 확률을 반환한다.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;기존의 모델에서 달라지는 점은 word embedding 부분이 character embedding과 합쳐지는 것인데, 구체적으론 다음의 수식과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316796-6be6e4d6-00cb-11e8-99b1-38acdb92666b.PNG&quot; alt=&quot;char-lstm-embed2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;저기서 &lt;script type=&quot;math/tex&quot;&gt;c_t^1&lt;/script&gt;은 첫번째 character의 one-hot encoding이고 &lt;script type=&quot;math/tex&quot;&gt;W_c^1&lt;/script&gt;은 그것의 embedding matrix이다. 전체  단어인 &lt;script type=&quot;math/tex&quot;&gt;w_t&lt;/script&gt;와 그 안의 각각의 character &lt;script type=&quot;math/tex&quot;&gt;c_t^1,..c_t^n&lt;/script&gt;이 각각 embedding되어 합쳐진것이, LSTM의 input이 되는것이다. 이때, 전체 embedding size는 일정하게 유지한다. 따라서 word embedding의 size가 줄어든다. (keep the total embedding size constant, the ‘word’ embedding size shrinks in size)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316798-6c509598-00cb-11e8-8fda-5b26101780cd.PNG&quot; alt=&quot;char-lstm-embed3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이때, 합쳐지는 character의 갯수는 일정한 상수 &lt;script type=&quot;math/tex&quot;&gt;n&lt;/script&gt;으로 고정되었고, 이를 넘는 경우 순서대로 n번째까지만 넣었다. 반대로 character 갯수가 짧을 때에는, special symbol을 padding으로 넣어주었다. 또, 넣을때에는 character의 순서를 유지하였다. (순서를 무시하였을 경우 성능 향상이 없었다.)&lt;/p&gt;

&lt;h4 id=&quot;31-order-of-characters&quot;&gt;3.1 Order of characters&lt;/h4&gt;

&lt;p&gt;character가 추가되는 순서를 forward로도 backward로도 해보았다. 영어와 네덜란드어 에는 접미사가 중요한 경우가 많기에, 단어의 끝에 더 강조를 두기 위해 backward로 해보았다.  또한 양쪽 방향(both)도 해보았다.&lt;/p&gt;

&lt;h4 id=&quot;32-weight-sharing&quot;&gt;3.2 Weight sharing&lt;/h4&gt;

&lt;p&gt;character embedding 에서, 첫번째 character든 두번째 character든 같은 vocabulary(a~z, 1~10 등등)을 것이라는 점에서 같은 Weight를 사용하는 것도 의미가 있다. 이 경우 수식은 다음과 같다&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316693-e85accfe-00ca-11e8-88d4-d3f01bb70072.PNG&quot; alt=&quot;char-lstm-embed4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그러나 영어에서 맨 마지막에 오는 ‘s’가 특별하게 복수의 의미를 갖듯이, 각 위치마다 다른 의미를 가지고 있다고 볼 수도 있다.&lt;/p&gt;

&lt;p&gt;따라서 weight 를 공유하는 모델과 공유하지 않는 모델을 모두 실험하였다.&lt;/p&gt;

&lt;h4 id=&quot;33-number-of-parameters&quot;&gt;3.3 Number of parameters&lt;/h4&gt;

&lt;p&gt;total 임베딩 중 일부가 character를 modeling하는 데에 사용되었다는 점에서, 실제 word embedding은 훨씬 작아졌다 기존의 word-level LSTM에서 embedding matrix의 파라미터는 vocabulary size &lt;strong&gt;V&lt;/strong&gt;와 total embedding size &lt;strong&gt;E&lt;/strong&gt;의 곱인 &lt;script type=&quot;math/tex&quot;&gt;V \times E&lt;/script&gt;였다. 여기서 total embedding size &lt;script type=&quot;math/tex&quot;&gt;E&lt;/script&gt;는 word embedding size &lt;script type=&quot;math/tex&quot;&gt;E_w&lt;/script&gt;와 같다. (&lt;script type=&quot;math/tex&quot;&gt;E=E_w&lt;/script&gt;)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316692-e81207f8-00ca-11e8-834e-89e411d3301f.PNG&quot; alt=&quot;lstm1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그러나 char-word level 모델의 파라미터 갯수는 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316691-e7e08f0c-00ca-11e8-8ada-1f73bc96f6ef.PNG&quot; alt=&quot;lstm2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;여기서 &lt;strong&gt;n은 들어가는 character 갯수이고,C는 character size, &lt;script type=&quot;math/tex&quot;&gt;E_c&lt;/script&gt;는 character embedding size&lt;/strong&gt;이다. V가 C보다 훨씬 크므로, 파라미터 갯수를 엄청나게 줄였다고 할 수 있다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;E-n\times E_c=E_w&lt;/script&gt;아닌가? 라고 생각해서&lt;/p&gt;

  &lt;p&gt;그럼 &lt;script type=&quot;math/tex&quot;&gt;V\times (E_w)+n\times(C\times E_c)&gt;V \times E_w&lt;/script&gt;인데..?? 라고 생각할 수 있지만 total size가 fix면 &lt;script type=&quot;math/tex&quot;&gt;E_{w2}&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;E_{W1}&lt;/script&gt;보다 더 작아진 애이다. 그냥 word embedding size를 줄여줬다 이해하면 된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;character에서 weight sharing을 해준다면, n개의 각각의 파라미터가 필요 없으므로 다음과 같이 더 줄어든다&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316690-e7aadc68-00ca-11e8-8d9a-33ca0bd176a3.PNG&quot; alt=&quot;lstm3&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;4-experiments&quot;&gt;4. Experiments&lt;/h3&gt;

&lt;h4 id=&quot;41-setup&quot;&gt;4.1 Setup&lt;/h4&gt;

&lt;p&gt;test와 train은 TensorFlow로 하였다. 200개의 hidden unit이 들어있는 2개의 layer로 된 small LSTM과 650개의 hidden unit이 들어있는 2개의 layer로 된 large LSTM으로 실험하였다. **embedding layer의 크기는 항상 hidden layer의 크기와 같게하였다. **&lt;/p&gt;

&lt;p&gt;small model : 13에폭, 첫 4에폭 후에 0.5로 learning rate decay, 25% dropout&lt;/p&gt;

&lt;p&gt;large model : 39에폭, 6에폭 후에 0.8로 decay, 50% dropout&lt;/p&gt;

&lt;p&gt;영어 data set으로는 Penn Treebank(PTB)를 사용. 900k training word token, 70k validation set, 80k test set. 많지 않은 수이지만 여러 연구에서 쓰인 데이터다.  비교를 위해 이전 연구들과 같이 소문자로 통일하였고, unknown word는 &lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
&lt;unk&gt; %]]&gt;&lt;/script&gt;라고 썻다.  character vocabulary size는 &lt;strong&gt;48&lt;/strong&gt;이다. (이전 논문은 70개였는데…이미 다르지 않나….)&lt;/p&gt;

&lt;p&gt;네덜란드어 data set으로는 Corpus of Spken Dutch(CGN)가 쓰였다. 회의나 토론, 강연 등의 내용이 담긴 데이터셋이고 1.4M train token, 180 validation set,190k test token이 있었다. 성능 비교를 위해, 저 중 PTB와 같은 data set size 만이용하였고 같은 &lt;strong&gt;voabulary size(10k)&lt;/strong&gt;로 제한했다.&lt;/p&gt;

&lt;h4 id=&quot;42-baseline-models&quot;&gt;4.2 Baseline models&lt;/h4&gt;

&lt;p&gt;비교를 위해 만든 baseline model. &lt;strong&gt;1)&lt;/strong&gt; 하나는 같은 hidden unit이 있는(따라서 더 많은 파라미터를 가지고 있는) LSTM, &lt;strong&gt;2)&lt;/strong&gt;하나는 비슷한 수의 파라미터를 가진 LSTM이다. 즉, small model에서는 unit 을 200 -&amp;gt; 175, large에서는 650 -&amp;gt; 475로 줄였다.&lt;/p&gt;

&lt;p&gt;(비슷한 수의 parameter를 갖도록 한 버젼에 대하여) embedding layer size도 475이니까, large word-level model의 embedding matrix크기는 10000 X 475 =475,000개이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;(475X10000)&lt;/strong&gt; (10000X1)= (475X1), 10000개는 vocabulary의 크기. voca는 10k로 고정해놧었음.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;한편 10개의 character를 넣고 거기에 각각 25 embedding size의 character를 사용한 경우 총 (10000 X (650 -10 X 25)) + 10 X (48 X 25) = 412,000개이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(&lt;strong&gt;(650-10X25)&lt;/strong&gt; X 10000)(10000X1)=(400X1)&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;10개 X (25X48)&lt;/strong&gt;(48X1) = 10개 X (25X1), 합치면 (650X1)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;43-english&quot;&gt;4.3 English&lt;/h4&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316689-e77710e0-00ca-11e8-8a11-ce9b571862ec.PNG&quot; alt=&quot;lstm4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;영어 dataset PTB에 대해서 보았을때, small model의 경우 전체 임베딩에서 단어 임베딩이 과반을 차지하는 경우(embedding size가 15이고 단어갯수가 7개 이상)를 제외하고는 같은 파라미터갯수의 base model보다 뛰어났다. 같은 hidden unit(200)을 가진 base model보다는, 약간 좋아졌다. character embedding 의 size가 커지면 반대로 word embedding size가 줄어들어 충분한 정보를 주지 못하였다. 즉, 큰 character embedding size의 경우 좋은 성능을 보이지 못했다.&lt;/p&gt;

&lt;p&gt;제일 좋은 성능을 보인것은 character embedding size 5로 3~7개의 character만을 추가한 경우였다. (!! 앞에서 부터 넣는것과 뒤에서 부터 넣는 것의 차이점인듯. n개 이외에는 아예 잘라서 안쓰는거니까.)&lt;/p&gt;

&lt;p&gt;large model의 경우에도 character embedding size가 지나치게 커지면 좋은 결과를 보이지 못했다. 제일 좋은 성능을 보인 것은 &lt;strong&gt;character embedding size가 25이고 8개의 character만을 넣는 모델&lt;/strong&gt;이었다.&lt;/p&gt;

&lt;p&gt;단어를 넣는 순서에 대해서도 달리 해보았다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316688-e7482186-00ca-11e8-909b-2bba3796efee.PNG&quot; alt=&quot;lstm5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;가장 좋은 성능을 보인 것은 both로, 앞에서 3개, 뒤에서 3개 넣은 것이다. 그러나 넣는 character 수를 늘리면 오히려 성능이 저하되었다. forward, back ward중에서는 backward가 전반적으로 좀더 잘했다.&lt;/p&gt;

&lt;p&gt;결론 : 추가되는 character embedding이 전체 embedding size에 비례하여야 한다. word embedding이 더 많이 들어가야 한다. Large model에서 제일 좋은 성능 향상을 보였다.&lt;/p&gt;

&lt;h4 id=&quot;다른-연구의-모델들과-비교&quot;&gt;다른 연구의 모델들과 비교&lt;/h4&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316687-e718297c-00ca-11e8-85ee-61702480efd3.PNG&quot; alt=&quot;lstm6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;또, 기존의 char-level로 해본 Kim et al보다(highway를 제거한모델에서) 성능이 좋았고, bidirectional로 char-word embedding을 하고 dropout을 쓰지 않은 Cho과는 비슷한 성능이었지만(비교를 위해 우리모델도 dropout안함) 우리모델이 덜 complex하다.&lt;/p&gt;

&lt;h4 id=&quot;44-dutch&quot;&gt;4.4 Dutch&lt;/h4&gt;

&lt;p&gt;richer morphology. 형태학적으로 더 뛰어나다…예상한대로 English에서보다 성능향상이 더 뛰어났다. 최적의 결과를 낸 모델설정은 English와 같았다.&lt;/p&gt;

&lt;h4 id=&quot;45-random-cw-models&quot;&gt;4.5 Random CW models&lt;/h4&gt;

&lt;p&gt;character를 넣는 것이 input에 noise를 넣는 역할로써 성능향상이 이뤄진것 아니냐를 탐구하기 위해, (noise가 성능향상시키나???) 진짜 noise, 즉 무작위 character를 넣은 모델을 만들어 보았다. 다른 설정은 모두 동일.&lt;/p&gt;

&lt;p&gt;그에 따른 결과는 다음과 같다. 무작위 noise모델을 base-model과 우리모델과 비교했을때 차이를 나타낸 표.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316686-e6eb13f6-00ca-11e8-976f-c116e66782d0.PNG&quot; alt=&quot;lstm7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Random noise모델은 English에서는 baseline보다도 못했고, Dutch에서는 baseline모델보다는 잘햇으나 우리모델보다는 훨씬 못했다. 고로, character를 넣는게 유의미하다.&lt;/p&gt;

&lt;h4 id=&quot;46-sharing-weights&quot;&gt;4.6 Sharing weights&lt;/h4&gt;

&lt;p&gt;위에서 설명한대로 각 위치의 character 임베딩을 모두 통일해보았다. 그러나 이 경우에도 첫번째 character는 첫번째 자리에 들어갈것이므로, 위치 정보가 사라진것은 아니다. (다만 ‘s’의 예시처럼 위치에 따른 특별한 의미가 있을 것이라는걸 반영못해준듯). 이렇게 하면 모든 character가 같은 embedding으로 매핑되면서, 파라미터수가 많이 줄어든다. 이를 baseline과 sharing안한 char-word와 비교한 결과.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35316685-e6bde836-00ca-11e8-8ffa-0bf33d8dbdfb.PNG&quot; alt=&quot;lstm8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;English의 경우 small model을 제외하고 baseline보다 더 나은 결과를 보였으나, weight sharing안한 모델이 ‘약간’ 더 좋았다. 그로 positon마다 특별한 의미가 있는것 같다.&lt;/p&gt;

&lt;h4 id=&quot;47-dealing-with-out-of-vocabulary-words&quot;&gt;4.7 Dealing with out-of-vocabulary words&lt;/h4&gt;

&lt;p&gt;언급하였듯이 Out of Vocabulary의 단어들에 대해 character 정보를 알 수 있으니 error가 줄지 않을까 기대했다. 이에 대해 다음과 같이 실험했다.&lt;/p&gt;

&lt;p&gt;OOV word가 들어왔을때 나오는 다음 단어에 대한 probability들을 check해보았다. 기존이 word-level model과 가장 좋았던 char-word model (25 char embed size, 6 char, backward)로 해보았다. 그 결과 Char-word model이 실제 단어에 높은 확률을 부여한게 17483번, word model이 더 높은 확률 부여한게 10724번으로, OOV word에 실제 도움이 된다할 수 있다. (한 3문장으로 스르륵 넘어갓다..)&lt;/p&gt;

&lt;h3 id=&quot;5-conclusion-and-future-work&quot;&gt;5. Conclusion and future work&lt;/h3&gt;

&lt;p&gt;char-word LSTM은 기존의 word LSTM에 비해 다음과 같은 장점이 있다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;LSTM의 size를 줄여준다(parameter가 줄었다고 표현하는게 더 맞는거같은데, 논문에선 이렇게 표현하였다.)&lt;/li&gt;
  &lt;li&gt;성능은 더 좋아진다. (improves the perplexity)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;또한, 여러 char embedding size, 여러 추가되는 char 갯수, 여러 order로 해보았는데, char embedding이 차지하는 비중이 지나치게 커지면 안되고, backward order가 조금더 잘했고, 양방향으로 조금씩 넣는것도 잘했다.&lt;/p&gt;

&lt;p&gt;random noise를 넣어본 모델보다 잘했기에, char를 넣는게 noise를 만들어서 잘한 것은 아니라 할 수 있다.&lt;/p&gt;

&lt;p&gt;weight sharing은, share 안한 모델보다 약간 못했다. 마지막으로 char-word model은 OOV에 대해 더 잘 작동했다.&lt;/p&gt;

&lt;h4 id=&quot;future-work&quot;&gt;future work&lt;/h4&gt;

&lt;p&gt;char-LSTM과 word-LSTM을 합치는것도 시도해볼만하다. 그리고 char를 one-hot vector가 아닌 co-occurrence vector로 넣는것도 유의미할듯하다. 사람의 언어구조를 모방해서 frequent에는 word-LSTM, infrequent에는 subword-LSTM을 해보는 것을 어떨까.&lt;/p&gt;
</description>
        <pubDate>Wed, 24 Jan 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/01/24/Character-Word-LSTM-Language-Models-%EB%85%BC%EB%AC%B8-%EB%A6%AC%EB%B7%B0.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/01/24/Character-Word-LSTM-Language-Models-%EB%85%BC%EB%AC%B8-%EB%A6%AC%EB%B7%B0.html</guid>
        
        <category>Deep Learning</category>
        
        <category>NLP</category>
        
        
        <category>딥러닝</category>
        
      </item>
    
      <item>
        <title>[ISL] 4장 - 분류(로지스틱, LDA, QDA) 이해하기</title>
        <description>
&lt;p&gt;이 장에서는 가장 많이 쓰이는 분류모델 3가지, &lt;strong&gt;로지스틱 회귀, 선형 판별 분석, KNN&lt;/strong&gt;을공부한다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;여기 안에 들어간것은 개인적인 참고를 위한 지엽적인 부분입니다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;숫자형 변수를 예측했던 3장의 회귀문제와는 다르게, 질적 변수를 예측해야 하는 경우도 있다. 질적 변수(혹은 범주형 변수)를 예측하는 문제를 classification이라 부른다. classification 방법들은 보통 &lt;strong&gt;각 범주에 속할 ‘확률’을 예측하는 형태로 분류&lt;/strong&gt;를 한다. (사실 이미 여기서 부터 선형회귀와 다르다)&lt;/p&gt;

&lt;p&gt;이 전과 똑같이, &lt;script type=&quot;math/tex&quot;&gt;(x_{1},y_{1}),...,(x_{n},y_{n})&lt;/script&gt;의 주어진 데이터를 가지고 (여기서 y는 어느클래스에 속하는지, 즉 답.) 학습을 한 후 새로운 데이터 input &lt;script type=&quot;math/tex&quot;&gt;x_{0}&lt;/script&gt;이 주어졌을때 그 데이터가 어디에 속하는지를 분류하는 것이다. 예를 들면 환자의 현재 상태를 체크한 데이터들을 보고 이 환자의 증상이 무었인지를 분류하는 문제를 들 수 있다.&lt;/p&gt;

&lt;p&gt;이 경우 왜 회귀분석으로 접근할 수 는 없을까? 범주형 변수를 임의로(강제로) 숫자형 변수로 만들어주면 회귀분석을 ‘할 수는’ 있다. 예를 들어 감기라면 &lt;script type=&quot;math/tex&quot;&gt;Y=1&lt;/script&gt;, 폐렴이라면 &lt;script type=&quot;math/tex&quot;&gt;Y=2&lt;/script&gt;, 독감이라면 &lt;script type=&quot;math/tex&quot;&gt;Y=3&lt;/script&gt; 과같은 식으로. 이런 식으로 회귀분석을 하면 값은 나온다. 그러나 이는 잘못된 접근이다. 앞장에서도 다루었지만 임의로 숫자를 부여하게 되면, 감기와 폐렴의 차이(위의 encoding에선 1)이 폐렴과 독감의 차이(1)와 같다는 의미가 되버린다.&lt;/p&gt;

&lt;p&gt;또 변수가 2개일때는 encoding, 즉 0과 1등의 숫자를 부여해서 마치 ‘1이 나올 확률’처럼 해석하는 시도가 어느정도 가능하지만(이때는 True, False의 역할을 하기 때문) 이 역시 아래 그림과 같이 회귀분석으로는 한계가 있다. 즉, [0,1]사이에만 존재하는 것이 아니라, 음수값이나 1.12등도 나올 수 있기에, 확률값으로 볼 수가 없다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482733-48cf66e4-0431-11e8-9550-d9d310ef8782.PNG&quot; alt=&quot;class-linear&quot; /&gt;&lt;/p&gt;

&lt;p&gt;따라서 범주형 자료를 예측하기 위해선, &lt;strong&gt;분류의 목적에 맞게 고안된&lt;/strong&gt; 다른 방법을 써야 한다.&lt;/p&gt;

&lt;h2 id=&quot;41-로지스틱-회귀-logistic-regression&quot;&gt;4.1 로지스틱 회귀 (Logistic Regression)&lt;/h2&gt;

&lt;p&gt;로지스틱 회귀는 반응변수 Y가 ‘미납자가 될것인가 or 아닌가’와 같은 두개의 범주를 나눌때 주로 쓰인다. 그러나 로지스틱회귀는 Y를 (앞의 잘못된 회귀분석 예시에서 그랫듯이) 바로 계산의 대상으로 두지 않는다. 앞에서도 언급하였듯이, 분류문제에서는 &lt;strong&gt;Y가 특정 카테고리에 속할 확률&lt;/strong&gt;을 목표로 두고 모델링을 한다.(bayes classifier를 상기하자) 위의 예시에서 독립변수(X)로 카드 부채(balance)가 주어졌을때 확률은 이렇다.
&lt;script type=&quot;math/tex&quot;&gt;Pr(미납자=yes|balance)&lt;/script&gt;
줄여서 &lt;script type=&quot;math/tex&quot;&gt;p(balance)&lt;/script&gt;로 표현하기도 한다(즉, &lt;script type=&quot;math/tex&quot;&gt;p(X)&lt;/script&gt;). 특정 input에 대해 이 확률을 구한다면, 0.5이상일 경우 미납자로 치부해버리거나, 좀더 위험을 피하고자 하는 회사라면  이 확률이 0.1 이상일 경우 미납자로 판단하는 등의 결정을 내릴 수 있을 것이다.&lt;/p&gt;

&lt;h4 id=&quot;어떻게-이런-모델링을-할까&quot;&gt;어떻게 이런 모델링을 할까&lt;/h4&gt;

&lt;p&gt;그럼 어떻게 ‘Y가 특정 카테고리에 속할 확률’을 목표로 두고 모델링을 할 수 있을까? 첫부분의 그림에서 보았듯이 &lt;script type=&quot;math/tex&quot;&gt;p(X)=\beta_{0}+\beta_{1}X&lt;/script&gt;식의 단순한 선형 적합으로는 ‘확률’의 의미를 띌 수 없다. 그럼 낮은 balance의 input에 대해선 음수를, 반대의 경우 1을 넘는 확률을 반환해 버리기 때문이다. 넘는 확률들을 0과 1로 치부해버려도, 특정 input에 대해 확률이 1, 즉 100%라는 현실적이지 않은 결과가 나오게 된다. 직관적으로 이해 할 수 있지만 &lt;strong&gt;binary classification(범주2개를 분류하는 문제)에서 선형적합은 한계가 있을 수 밖에&lt;/strong&gt; 없다.&lt;/p&gt;

&lt;p&gt;이 문제를 boundary problem이라 하는데(&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
-\infty&lt;x&lt;\infty %]]&gt;&lt;/script&gt; 일때도 특정 boundary를 넘어가지 않는 함수를 만드는 것), 이를 해결하기 위한 많은 함수형태가 있지만, 로지스틱회귀에선 &lt;strong&gt;로지스틱 함수&lt;/strong&gt;라 불리는 다음 식을 쓴다.
&lt;script type=&quot;math/tex&quot;&gt;p(X)=\frac {e^{\beta_{0}+\beta_{1}X}}{1+e^{\beta_{0}+\beta_{1}X}}&lt;/script&gt;
(혹은 간략화하여 &lt;script type=&quot;math/tex&quot;&gt;\frac {1}{1+e^{-f(x)}}&lt;/script&gt;라고 쓰기도 한다. 머신러닝에서는 이 식을 더 많이 보았을 것이다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482732-489fd2ee-0431-11e8-83ca-e14500caa76c.PNG&quot; alt=&quot;class-linear-log&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위 식을 이용하면 다음과 같이, 0과 1에 가까워지지만 절대 넘지는 않는 ‘확률’의 특성에 딱 맞아 떨어지는 함수형태가 만들어 진다. 책의 예시에서 미납자의 비율은 3%였는데, 로지스틱 적합의 미납자 비율은 0.033으로 엄청 잘 맞았다.(물론 이는 과장된 가짜 데이터지만..) 위의 식의 계수들은 &lt;strong&gt;maximum likelihood로&lt;/strong&gt; 구한다. (뒤에 설명)&lt;/p&gt;

&lt;h4 id=&quot;오즈의-등장&quot;&gt;오즈의 등장&lt;/h4&gt;

&lt;p&gt;위의 식을 정리하면, 다음과 같은 식을 얻을 수 있다.
&lt;script type=&quot;math/tex&quot;&gt;\frac{p(X)}{1-p(X)}=e^{\beta_{0}+\beta_{1}X}&lt;/script&gt;
여기서 &lt;script type=&quot;math/tex&quot;&gt;\frac{p(X)}{1-p(X)}&lt;/script&gt;에 주목하자. 이는 ‘(해당클래스에 속할 확률)/(속하지 않을 확률)’을 의미한다(!) 이를&lt;em&gt;odds&lt;/em&gt;라고 부르는데, &lt;script type=&quot;math/tex&quot;&gt;0\sim\infty&lt;/script&gt;값을 가질 수 있고 각각 &lt;strong&gt;0일 수록&lt;/strong&gt; (&lt;script type=&quot;math/tex&quot;&gt;p(X)&lt;/script&gt;가) 매우 낮은 확률, &lt;strong&gt;&lt;script type=&quot;math/tex&quot;&gt;\infty&lt;/script&gt;일수록&lt;/strong&gt; 매우 큰 확률을 의미한다.(&lt;script type=&quot;math/tex&quot;&gt;p(X)&lt;/script&gt;에 값을 몇개 넣어보면 바로 느낌온다.)&lt;/p&gt;
&lt;h4 id=&quot;로짓의-등장&quot;&gt;로짓의 등장&lt;/h4&gt;

&lt;p&gt;이제 거의 다왔다. 최종적으로 우리에게 익숙한 선형회귀(느낌의) 식을 만들기 위해 양쪽에 log를 취해주자
&lt;script type=&quot;math/tex&quot;&gt;log(\frac{p(X)}{1-p(X)})=\beta_{0}+\beta_{1}X&lt;/script&gt;
좌변을 ‘오즈’에 ‘로그’를 씌워줬다 하여 ‘&lt;em&gt;log-odds&lt;/em&gt;’ 혹은 ‘&lt;em&gt;logit&lt;/em&gt;‘이라고 부른다. 로지스틱 회귀 모델은, 바로 이 &lt;strong&gt;‘로짓’과 &lt;script type=&quot;math/tex&quot;&gt;X&lt;/script&gt;가 선형관계에 있는 모델&lt;/strong&gt;이다(!).&lt;/p&gt;

&lt;p&gt;이때, 해석에 주의해야 한다. 앞장의 선형 회귀모델에서 &lt;script type=&quot;math/tex&quot;&gt;\beta_{1}&lt;/script&gt;은 X가 한 단위 증가할때 Y의 변화량이었지만, 여기에선 &lt;strong&gt;‘로짓’의 변화량&lt;/strong&gt;이다. 바꿔 말하면, &lt;strong&gt;‘오즈’, 즉 &lt;script type=&quot;math/tex&quot;&gt;\frac{p(X)}{1-p(X)}&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;e^{\beta_{1}}&lt;/script&gt;배 만큼 증가하는 것&lt;/strong&gt;이다 (!!) 이때 &lt;script type=&quot;math/tex&quot;&gt;\beta_{1}&lt;/script&gt;이 양수면 X와 Y의 변동도 양의 관계, 음수면 변동도 음의 관계이다. (&lt;script type=&quot;math/tex&quot;&gt;\beta_{1}&lt;/script&gt;의 부호에 따라 함수 개형이 위아래로 뒤집힌다.)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;‘증가(혹은 변동)’에 대한 개념이 선형회귀의 &lt;script type=&quot;math/tex&quot;&gt;Y_{i}+\beta_{1}=Y_{i+1}&lt;/script&gt;만큼 직관적이지 않다.&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac{p(X_{i})}{1-p(X_{i})}*e^{\beta_{1}}=\frac{p(X_{i+1})}{1-p(X_{i+1})}&lt;/script&gt;을 풀면 &lt;script type=&quot;math/tex&quot;&gt;p(X)&lt;/script&gt;가 얼마나 변동했는지를 구할 수는 잇으나.. 식이 굉장히 지저분해져서, 그냥 딱 ‘‘오즈가 &lt;script type=&quot;math/tex&quot;&gt;e^\beta_{1}&lt;/script&gt;만큼 증가했다’‘로 받아들이는게 좋다. 즉 &lt;script type=&quot;math/tex&quot;&gt;Y_i&lt;/script&gt;, 그러니까 &lt;script type=&quot;math/tex&quot;&gt;p(X)&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;X&lt;/script&gt;의 한 단위 증가에 변화하는 구체적인 량은 현재 &lt;script type=&quot;math/tex&quot;&gt;X&lt;/script&gt;의 수준에 따라 다르다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;maximum-likelihood를-이용한-계수-추정&quot;&gt;Maximum likelihood를 이용한 계수 추정&lt;/h4&gt;

&lt;p&gt;앞에서 살짝 얘기하였으나, 로지스틱회귀의 경우 mle로 추정을 한다.(least square로도 추정’할 수’는 있으나 mle의 성질이 여기서는 더 좋기에 mle로 추정한다.) Maximum likelihood는 많은 non-linear model을 적합하는데에 사용된다.&lt;/p&gt;

&lt;p&gt;maximum likelihood란 간단하게 관측값들을 토대로 결정을 내리는 방법이라 보면 된다. 실제 함수의 parameter &lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;를 추정할때, 해당 관측값들을 토대로 &lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;가 취할 수 있는 여러 값 중 &lt;strong&gt;‘그 관측값을 만들어 냈을 가능성이 가장 큰 값’&lt;/strong&gt;을  &lt;script type=&quot;math/tex&quot;&gt;\theta&lt;/script&gt;로 추정하는 방법이다.&lt;/p&gt;

&lt;p&gt;더욱 일차원 적으로 표현하자면, 미납자class의 데이터는 1을 많이, 미납자가 아닌 class는 0을 많이 반환하는 모델을 만드는것이다. binary classification의 경우 이 식은 다음과 같이 표현된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482731-48311638-0431-11e8-8d74-657a69d5876b.PNG&quot; alt=&quot;logi-mle&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이를 &lt;em&gt;likelihood function&lt;/em&gt;이라 하는데, 이를 최대화 해주는 parameter &lt;script type=&quot;math/tex&quot;&gt;\beta_{0},\beta_{1}&lt;/script&gt;을 찾는 것이다.(여기서
&lt;script type=&quot;math/tex&quot;&gt;p(x_i)=Pr(Y_i=y_i|x_i)&lt;/script&gt;
)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;maximum likelihood는 주로 log를 씌워 log-likelihood로 계산을 한다. 그렇게 함으로써 곱이 합의 형태로 바뀌며 계산이 쉬워진다.(미분을 할 경우 이게 훨씬 더 쉽다) 위의 식에 log를 씌우고 ‘-‘를 붙이면 그 유명한 NLL(Negative log likelihood)이 된다. 즉, 둘은 사실 같은 것이다. (&lt;a href=&quot;https://ko.wikipedia.org/wiki/%EB%A1%9C%EC%A7%80%EC%8A%A4%ED%8B%B1_%ED%9A%8C%EA%B7%80&quot;&gt;참고&lt;/a&gt;)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;다음은 R을 통해 예시문제, 카드 부채(balance)와 미납자인지 아닌지에서 로지스틱을 적합한 결과이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482730-47f97ab6-0431-11e8-99da-28dddb6d97f7.PNG&quot; alt=&quot;logi-table&quot; /&gt;&lt;/p&gt;

&lt;p&gt;카드 부채의 계수가 0.0055이므로 balance가 1증가할때 미납자에 대한 ‘오즈’가 &lt;script type=&quot;math/tex&quot;&gt;e^{0.0055}&lt;/script&gt;배 증가한다고 해석 할 수 있다. 또한 이때의 p-value는 선형회귀에서 t분포를 사용한것과 다르게 &lt;strong&gt;z-분포&lt;/strong&gt;를 사용하였고, 마찬가지로 standard error를 통해 추정의 정확도 역시 구할 수 있다.&lt;/p&gt;

&lt;p&gt;좀더 상세히 말하자면 &lt;script type=&quot;math/tex&quot;&gt;\frac{b_{1}-0}{SE[b_{1}]}\sim Z&lt;/script&gt;이고 p-value는 전과 같게 &lt;script type=&quot;math/tex&quot;&gt;H_{0}:\beta_{1}=0&lt;/script&gt;에 대한 검정에 사용된다.&lt;/p&gt;

&lt;p&gt;실제 확률은 구해진 계수를 &lt;script type=&quot;math/tex&quot;&gt;p(X)=\frac {e^{\beta_{0}+\beta_{1}X}}{1+e^{\beta_{0}+\beta_{1}X}}&lt;/script&gt;에 대입하고 X값을 넣으면 된다. 또 선형회귀에서 처럼, 질적변수는 더미변수(0,1)를 만들어서 같은 방식으로 적합하면 된다.&lt;/p&gt;

&lt;h4 id=&quot;다중-로지스틱-회귀와-confounding&quot;&gt;다중 로지스틱 회귀와 confounding&lt;/h4&gt;

&lt;p&gt;이름이 더 어렵게 생겼지만, 선형회귀에서와 같이 변수가 한개가 아니라 여러개가 된것이다. 역시나, 식을 다음과 같이 확장만 하면 된다
&lt;script type=&quot;math/tex&quot;&gt;p(X)=\frac {e^{\beta_{0}+\beta_{1}X+...\beta_{p}X_{p}}}{1+e^{\beta_{0}+\beta_{1}X+...\beta_{p}X_{p}}}&lt;/script&gt;
혹은 
&lt;script type=&quot;math/tex&quot;&gt;log(\frac{p(X)}{1-p(X)})=\beta_{0}+\beta_{1}X+...\beta_{p}X_{p}&lt;/script&gt;
같은 방식으로 &lt;script type=&quot;math/tex&quot;&gt;\beta_{0},\beta_{1},...,\beta_{p}&lt;/script&gt;를 추정하기 위해 maximum likelihood를 사용한다.&lt;/p&gt;

&lt;p&gt;그러나 신기한 사실! 책의 예제에서 단순히 미납자~학생(인지 아닌지)으로 적합하였을때는 계수가 양수, 즉 ‘학생이면 미납자일 확률이 더 크다’로 나왔었는데, 학생(&lt;script type=&quot;math/tex&quot;&gt;X_{1}&lt;/script&gt;)과 부채(&lt;script type=&quot;math/tex&quot;&gt;X_{2}&lt;/script&gt;)로 적합하였더니 학생에 대한 계수가 음수, 즉 ‘학생이면 미납자일 확률이 더 작다’를 의미하는 결과가 나왔다. 심지어 p-value가 둘다 유의하게 나왔는데도!&lt;/p&gt;

&lt;p&gt;이는, 다중회귀에서의 계수가 다른 변수들이 ‘고정’된 상태에서의 의미, 즉 동일한 부채(balance)에서 학생들이 미납자일 확률이 작다를 의미하기 때문이다. 이는 그림을 통해 알 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482729-47bfd608-0431-11e8-860b-9a13222d29a1.PNG&quot; alt=&quot;stud-logi&quot; /&gt;&lt;/p&gt;

&lt;p&gt;왼쪽 그림에서 빨간 곡선은 부채에 따른 학생의 미납자 비율, 파란색은 비학생이다. 그리고 그림 아래부분의 빨간직선, 파란직선은 전체의 미납자 비율이다. &lt;strong&gt;같은 balance 수준(X) 내에서는&lt;/strong&gt; 학생의 미납자 비율이 더 낮지만, &lt;strong&gt;전체적으로 보았을때&lt;/strong&gt;는 학생의 미납자 비율이 더 높다. 왜 그럴까? 같은 부채의 정도에서는 학생이 미납자가 아닐 확률이 더 높지만, ‘부채가 높은 사람은 미납자일 확률이 크다-&amp;gt;그런데 학생들은 부채가 높은 사람이 non-student에 비해 더 많다!(이는 오른쪽 그림을 통해서 알 수 있다)’. 이에 따라 balance 정보가 없으면 전체로 보아 학생이 더 미납자가 될 확률이 크다고 판단할 수 있지만 balance 정보가 있을 경우 학생이 미납자가 될 확률이 더 작다라고 판단할 수 있게 되는것이다. 이렇게, 변수 자체에 correlated된 관계가 있을 경우 하나의 변수만을 이용하는 것은 다른 결과를 가져 올 수 있다. 이를 &lt;em&gt;confounding&lt;/em&gt;문제 라고 부른다.&lt;/p&gt;

&lt;p&gt;추가로, 2개 이상의 범주에서의 로지스틱 회귀을 하는 것이 ‘가능’은 하다. 그러나 이 경우 성능이 다른 모델(바로 뒤에 나옴!)에 비해 안좋기에 실제에서 그렇게 자주 쓰이진 않는다.&lt;/p&gt;

&lt;h2 id=&quot;41-linear-discriminant-analysis&quot;&gt;4.1 Linear Discriminant Analysis&lt;/h2&gt;

&lt;p&gt;직접적으로 
&lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)&lt;/script&gt;
를 구했던 로지스틱 회귀와는 조금 다르게, LDA에서는 조금 덜 직접적인 방법을 쓴다. 각각의 Y가 주어졌을때의 X의 분포, &lt;strong&gt;즉 
&lt;script type=&quot;math/tex&quot;&gt;P(X|Y)&lt;/script&gt;
를  통하여  &lt;em&gt;‘Bayes’ theorem’&lt;/em&gt;으로 
&lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)&lt;/script&gt;
를 추정하고자&lt;/strong&gt; 한다. 이 때 X의 분포,&lt;br /&gt;
&lt;script type=&quot;math/tex&quot;&gt;P(X|Y)&lt;/script&gt;
에 정규가정이 생긴다면, 로지스틱 회귀와 매우 유사한 형태가 된다.&lt;/p&gt;

&lt;p&gt;매우 유사한 형태가 된다면, 왜 굳이 로지스틱 회귀가 아닌 LDA를 사용할까? 다음의 이유가 있다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;2개 이상의 범주가 있을 시 성능이 더 뛰어나다&lt;/li&gt;
  &lt;li&gt;범주가 명확하게 구분되 있을 경우, 로지스틱 회귀는 굉장히 불안정한 결과를 낸다(계수가 쉽게 변동한다). LDA는 그렇지 않다(범주가 명확하게 구분되어 있다는 것은, 0,1의 분류에서 보통은 한 x 수준에서도 0인 data도 1인 data도 어느정도 겹쳐있기 마련인데 0인 x의 수준과 1인x의 수준이 극단적으로 나뉘어져 있는 경우를 말한다. &lt;a href=&quot;https://stats.stackexchange.com/questions/254124/why-does-logistic-regression-become-unstable-when-classes-are-well-separated&quot;&gt;참고&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;자료의 개수 n이 적을때에도 각 클래스에 대한 X의 분포가 정규분포와 유사하다면, 역시나 로지스틱 회귀보다 안정적인 성능을 보인다.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;고로, 예상 가능했겟지만 상당한 경우에 LDA가 장점이 있기에 쓰인다.&lt;/p&gt;

&lt;h3 id=&quot;using-bayes-theorem-for-classification&quot;&gt;Using Bayes’ Theorem for Classification&lt;/h3&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\pi_k&lt;/script&gt;를 임의의 관측치가 k번째 클래스에서 왔을 확률이라고 하자. 쉽게 말해 주어진 자료 중 몇개의 라벨이 k클래스인 자료인지를 보면 된다. (즉, &lt;script type=&quot;math/tex&quot;&gt;P(Y_k)&lt;/script&gt;를 의미한다. 이를 &lt;strong&gt;사전확률&lt;/strong&gt;이라고도 한다.) 그리고 &lt;script type=&quot;math/tex&quot;&gt;f_k(x)&lt;/script&gt;를 Y=k클래스 일때 특정 &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;가 나타나는 확률 이라고 하자. 즉, &lt;script type=&quot;math/tex&quot;&gt;f_k(x)=P(X=x|Y=k)&lt;/script&gt;이다. 베이즈의 정리는 다음과 같은 형식으로 &lt;strong&gt;사후 확률&lt;/strong&gt;을 구하는 방법이다.
&lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)=\frac{\pi_kf_k(x)}{\sum^{K}_{l=1}\pi_lf_l(x)}&lt;/script&gt;
사실 이 책의 notation이 좀 독특한것이지 (notation 정리 : &lt;script type=&quot;math/tex&quot;&gt;f_k(x)=P(X=x|Y=k)​&lt;/script&gt;이고 &lt;script type=&quot;math/tex&quot;&gt;\pi_k=P(Y_k)​&lt;/script&gt;이다.)&lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)=\frac{P(Y_k)P(X| Y_k)}{P(Y_1)P(X| Y_1)+P(Y_2)P(X| Y_2)+..+P(Y_K)P(X| Y_K)}=\frac{P(X\cap Y_k)}{P(X\cap Y_1)+P(X\cap Y_2)+..+P(X\cap Y_K)}​&lt;/script&gt;와 같은 말이다. 따라서 &lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)​&lt;/script&gt;를 바로 예측하는 것이 아닌 &lt;script type=&quot;math/tex&quot;&gt;P(Y_k)​&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;P(X=x|Y=k)​&lt;/script&gt;를 추정하여 이로써 계산하는 것이다. 이 때 &lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)​&lt;/script&gt;, 즉 우리의 목표는 &lt;strong&gt;사후확률&lt;/strong&gt;이라 부른다. 사실 &lt;script type=&quot;math/tex&quot;&gt;P(Y_k)​&lt;/script&gt;는 &lt;strong&gt;전체 데이터에서 몇개가 k클래스 라벨을 가지고 있는지&lt;/strong&gt; 보면 추정완료이지만, &lt;script type=&quot;math/tex&quot;&gt;f_k(x) =P(X=x|Y=k)​&lt;/script&gt;는 추정하기가 좀 까다로워 &lt;strong&gt;특정 분포를 가정을 하고&lt;/strong&gt; 분석을 진행한다. 2장의 Bayes Classifier에서 배웠듯이, &lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)​&lt;/script&gt;를 올바르게 추정할 수 있다면 오류율이 최소인 이상적인 분류를 할 수 있을 것이다. 따라서 이제, &lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)​&lt;/script&gt;를 추정하기 위해 필요한 &lt;script type=&quot;math/tex&quot;&gt;f_k(x)​&lt;/script&gt;를 	잘 추정할 수 있는 방법에 대해 다룰 것이다.&lt;/p&gt;

&lt;h3 id=&quot;linear-discriminant-analysis-for-p--1&quot;&gt;Linear Discriminant Analysis for p = 1&lt;/h3&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;P(X=x|Y=k)=f_k(x)&lt;/script&gt;
를 	추정하기 위해, 위에서도 언급하였듯이 &lt;strong&gt;분포를 가정&lt;/strong&gt;한다. 가장 대표적으론 &lt;strong&gt;정규가정&lt;/strong&gt;을 하는데, 수식으로 표현하자면 이렇다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482726-47330d54-0431-11e8-88d5-c1abe5b737a0.PNG&quot; alt=&quot;LDA1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;즉, 각각의 평균과 분산 &lt;script type=&quot;math/tex&quot;&gt;k=1,..,K&lt;/script&gt;인 K개의 각기 다른 정규분포가 있는 것이다. 추가로 모든 k에 대해 분산이 &lt;script type=&quot;math/tex&quot;&gt;\sigma&lt;/script&gt;로 동일하다는 가정, 즉 등분산 가정을 한다. (선형회귀에서 이미 한번 접했다.) 이 경우 우리의 최종 목표는 다음과 같은 수식으로 변화할 수 있다. (어려워 보이지만 단순히 대입한 것이다)
&lt;script type=&quot;math/tex&quot;&gt;p_k(x)=P(Y=k|X=x)=\frac{\pi_kf_k(x)}{\sum^{K}_{l=1}\pi_lf_l(x)}&lt;/script&gt;
&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482725-470538f2-0431-11e8-931b-bc42e685a2a9.PNG&quot; alt=&quot;LDA2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그 후 저 확률이 가장 큰 &lt;script type=&quot;math/tex&quot;&gt;k&lt;/script&gt;클래스에게로 분류를 해주는 것이다(Bayes classifier 처럼). 또, 위의 확률 &lt;script type=&quot;math/tex&quot;&gt;p_k(x)&lt;/script&gt;에 log를 씌우고, 어떤 k에 대해서든 변하지 않는 중복된 term을 없애면 결국 다음 수식이 가장 큰 클래스&lt;script type=&quot;math/tex&quot;&gt;k&lt;/script&gt;를 고르는 문제로 귀결된다. (log는 1:1함수이므로 정보의 손실이 없다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482724-46d8c10a-0431-11e8-91ae-e85653bf41b8.PNG&quot; alt=&quot;LDA3&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;$p_k(x)=\frac{\pi_k\frac{1}{\sqrt{2\pi}\sigma}exp(-\frac{1}{2\sigma^2}(x-\mu_k)^2)}{same_1}$&lt;/p&gt;

  &lt;p&gt;$log(p_k(x))=log(\pi_k)-\frac{1}{2\sigma^2}x^2+\frac{1}{\sigma^2}x\mu_k-\frac{1}{2\sigma^2}\mu_k^2-same_1$ 이 중 &lt;script type=&quot;math/tex&quot;&gt;-\frac{1}{2\sigma^2}x^2&lt;/script&gt;도 모든 &lt;script type=&quot;math/tex&quot;&gt;k&lt;/script&gt;에 대해 동일하니까,&lt;/p&gt;

  &lt;p&gt;$=\frac{x\mu_k}{\sigma^2}-\frac{1}{2\sigma^2}\mu_k^2+log(\pi_k)+same_2$&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이 경우(정규가정과 등분산 가정) 공통분산&lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;와 각 클래스에 대한 parameter &lt;script type=&quot;math/tex&quot;&gt;\mu_k&lt;/script&gt;를 알고 있다면, (정규 가정과 등분산 가정 하에서) 정확한 Bayes classifier를 계산으로 도출할 수 있다. LDA는, 바로 이 공통분산&lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;와 각 클래스에 대한 parameter &lt;script type=&quot;math/tex&quot;&gt;\mu_k&lt;/script&gt;를 추정하여 Bayes classifier에 근사하고자 하는 것이다.&lt;/p&gt;

&lt;p&gt;parameter는 다음과 같이 추정한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482723-46aa18c8-0431-11e8-8149-69ddb0380717.PNG&quot; alt=&quot;LDA4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;간단하다. &lt;script type=&quot;math/tex&quot;&gt;\hat \mu_k&lt;/script&gt;는 단순히 sample mean을 구한것이고, 공통 분산 &lt;script type=&quot;math/tex&quot;&gt;\hat \sigma^2&lt;/script&gt;는 각 편차제곱에 자유도(K개의 &lt;script type=&quot;math/tex&quot;&gt;\hat \mu&lt;/script&gt;를 사용하였으니 &lt;script type=&quot;math/tex&quot;&gt;df=n-K&lt;/script&gt;)로 나누어 분산을 추정한 것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;이렇게 분산을 추정하는 것을 pooled variance라고 한다. k개의 &lt;script type=&quot;math/tex&quot;&gt;\hat \mu&lt;/script&gt;를 사용하여 자유도를 K만큼 잃었으나 각 클래스의 평균이 모두 동일하다는 가정이 없으므로 overall variance를 구하지 못하고 해당 식을 쓰게 된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이제 &lt;script type=&quot;math/tex&quot;&gt;f_k(x)&lt;/script&gt;는 추정이 끝났고(parameter를 다 구했으니), 이제 &lt;script type=&quot;math/tex&quot;&gt;\pi_k&lt;/script&gt;를 추정해야한다. (notation 정리 : 
&lt;script type=&quot;math/tex&quot;&gt;f_k(x)=P(X=x|Y=k)&lt;/script&gt;
이고 &lt;script type=&quot;math/tex&quot;&gt;\pi_k=P(Y_k)&lt;/script&gt;이다.)&lt;/p&gt;

&lt;p&gt;앞에서도 언급하였지만 &lt;script type=&quot;math/tex&quot;&gt;\pi_k&lt;/script&gt;는 다음과 같이 간단하게 추정될 수 있다.
&lt;script type=&quot;math/tex&quot;&gt;\hat \pi_k=\frac{n_k}{n}&lt;/script&gt;
즉 (k클래스 데이터의 수/전체 데이터의 수)이다. 앞서 구한 여러 추정량들을 토대로, 우리의 최종 목적은 다음의 &lt;script type=&quot;math/tex&quot;&gt;\hat \delta_k(x)&lt;/script&gt;가 최대가 되는 클래스k를 찾는것으로 귀결된다는. (단순히 추정한 값들로 바꿔 넣어 준 것이다.)
&lt;script type=&quot;math/tex&quot;&gt;\hat\delta_k(x)=x\frac{\hat \mu_k}{\hat \sigma^2}-\frac{\hat \mu_k^2}{2\hat \sigma^2}+log(\hat \pi_k)&lt;/script&gt;
Linear Discriminant라는 명칭은 최종 function인 &lt;script type=&quot;math/tex&quot;&gt;\hat \delta_k(x)&lt;/script&gt;가, 즉 최종 결정을 내리는 &lt;strong&gt;decision boundary가 &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;에 대한 선형식&lt;/strong&gt;으로 나오기 때문이다. (훨씬 복잡한 식으로 나오는 다른 모델들이 많다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482722-467e93e2-0431-11e8-93c3-24d6c4d16d9a.PNG&quot; alt=&quot;LDA5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위와 같이 초록과 빨강 각각 20개의 simulated 된 데이터가 있다면, 각 클래스(초록, 빨강)에 대해 &lt;script type=&quot;math/tex&quot;&gt;\hat \pi_k,\mu_k,\sigma&lt;/script&gt;를 추정하고 이를 통해 &lt;script type=&quot;math/tex&quot;&gt;\hat \delta_k(x)&lt;/script&gt;가 큰 클래스로 분류를 하는 것이다. (
&lt;script type=&quot;math/tex&quot;&gt;p_k(x)=P(Y=k|X=x)&lt;/script&gt;
의 추정확률이 제일 큰 클래스로 분류하는거랑 같은 말이다.)&lt;/p&gt;

&lt;p&gt;해당 그림에서 실선은 decision boundary, 즉 &lt;script type=&quot;math/tex&quot;&gt;\hat p_{초록}(x)=\hat p_{빨강}(x)&lt;/script&gt;인 경우의 경계선이다. simulated 데이터인 만큼 엄청난 데이터를 만들어 내어 구한 실제 boundary(Bayes classifier)가 점선으로 나와 있는데, simulated test data에 대하여 Bayes는 error rate가 10.6%, LDA는 11.1%로 상당한 성능을 보였음을 알 수 있다.&lt;/p&gt;

&lt;p&gt;최종 정리하자면, LDA는 ‘
&lt;script type=&quot;math/tex&quot;&gt;f_k(x)=P(X=x|Y=k)&lt;/script&gt;
에 대한 정규 가정과 각 클래스마다 다른 평균, 동일한 분산’을 가정하여 Bayes classifier의 확률을 추정하는 방법이다. 뒷장에서 ‘등분산’에 대한 가정을 떼어내는(즉 클래스마다 &lt;script type=&quot;math/tex&quot;&gt;\sigma_k^2&lt;/script&gt;를 가질 수 있게 하는) 방법을 배울 것이다.&lt;/p&gt;

&lt;h3 id=&quot;linear-discriminant-analysis-for-p-1&quot;&gt;Linear Discriminant Analysis for p &amp;gt;1&lt;/h3&gt;

&lt;p&gt;이제 한걸음 더 나아가, 변수가 여러개인 경우의 LDA에 대해 생각해보자. 기존에 
&lt;script type=&quot;math/tex&quot;&gt;P(X=x|Y=k)=f_k(x)&lt;/script&gt;
엔 정규분포를 가정하였지만, 이젠 &lt;script type=&quot;math/tex&quot;&gt;X=(X_1,..,X_p)&lt;/script&gt;가 다변량 정규분포(&lt;em&gt;multivariate Gaussian&lt;/em&gt;)를 따른다고 가정한다. 이번에도, 각 class마다의 평균은 다르고, 분산은 공통의 분산을 가정한다.&lt;/p&gt;

&lt;h4 id=&quot;다변량-정규분포란&quot;&gt;다변량 정규분포란?&lt;/h4&gt;

&lt;p&gt;이름에서부터 부담스런 포스를 팍팍 풍기는데, 그 의미는 간단하다. 다변량 정규분포는 각각의 변수들이 1차원의(기존의 알고 있는) 정규분포 하나를 따르고 각각의 변수 pair가 어떠한 correlation를 가지고 관계를 갖는 분포이다. 쉽게말해 다차원 정규분포라고 받아들이면 편하다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482721-464849f4-0431-11e8-9f9d-db0ad21c5c1e.PNG&quot; alt=&quot;LDA-multi&quot; /&gt;&lt;/p&gt;

&lt;p&gt;가장 간단하게 X가 2개인 경우부터 접근해보면, 위의 그림과 같은 그래프가 다변량 정규분포이다.(한 축에서만 바라볼 경우 우리가 아는 1차원의 정규분포가 나타남에 주목하라) 왼쪽그림은 가장 기본적인 그림으로, &lt;script type=&quot;math/tex&quot;&gt;Var(X_1)=Var(X_2)&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;Cor(X_1,X_2)=0&lt;/script&gt;인 경우의 그림이다. 그러나 많은 경우 각 &lt;strong&gt;변수들의 pair가 correlated되어 있는 경우&lt;/strong&gt;나 &lt;strong&gt;분산이 같지 않은 경우&lt;/strong&gt;가 있는데, 그 경우 오른쪽 그림처럼 약간 길게 늘어진 형태의 그래프가 그려진다.&lt;/p&gt;

&lt;p&gt;다변량 정규분포는 수식으로 나타낼 경우, p개의 정규분포를 일일이 쓰는 것이 아니라, 또 그들간의 correlation관계도 동시에 포함해주고자 다음과 같이 matrix로써 나타낸다.
&lt;script type=&quot;math/tex&quot;&gt;X\sim N(\boldsymbol \mu,\boldsymbol \sum)&lt;/script&gt;
식에서 &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol \mu&lt;/script&gt;는 p개 변수의 분포의 평균을 나타낸 p차원 &lt;strong&gt;vector&lt;/strong&gt;, &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol \sum&lt;/script&gt;는 p개 변수의 covariance를 나타낸 p*p크기의 &lt;strong&gt;covariance matrix&lt;/strong&gt;이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;2변량 정규분포일때 풀어써보면 다음과 같다.
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
X\sim N({\begin{pmatrix}\ \mu_1\\ \mu_2 \end{pmatrix},\begin{pmatrix}\ \sigma_1^2&amp;\rho\sigma_1\sigma_2 \\\rho\sigma_1\sigma_2&amp; \sigma_2^2 \end{pmatrix}}), \rho\sigma_1\sigma_2=Cov(X_1,X_2) %]]&gt;&lt;/script&gt;&lt;/p&gt;

&lt;/blockquote&gt;

&lt;p&gt;이를 수식으로 나타내면 다음과 같다. 엄청 부담스러 보이지만, &lt;script type=&quot;math/tex&quot;&gt;\boldsymbol \sum&lt;/script&gt;을 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;라고 생각한다면 기존에 알던 정규분포식의 생김새랑 크게 다르진 않다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482720-461cfc04-0431-11e8-9953-c84e85aa60a7.PNG&quot; alt=&quot;LDA-multi2&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;저기서 
&lt;script type=&quot;math/tex&quot;&gt;||&lt;/script&gt;
는 Determinant. 행렬을 root씌울 수 없으니 행렬은 이렇게 표현한다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;다시-lda&quot;&gt;다시 LDA&lt;/h4&gt;

&lt;p&gt;다시 돌아와서, 여러개의 변수를 포함한 LDA는 k클래스에 속한 관측치들의 분포 
&lt;script type=&quot;math/tex&quot;&gt;P(X=(x_1,..,x_p)|Y=k)=f_k(x)&lt;/script&gt;
가 다변량 정규분포, 즉 &lt;script type=&quot;math/tex&quot;&gt;N(\boldsymbol {\mu_k},\boldsymbol \sum)&lt;/script&gt;를 따른다고 가정한다. 이를 이용하여 다시 bayes 정리, 즉 &lt;script type=&quot;math/tex&quot;&gt;P(Y=k|X=x)=\frac{\pi_kf_k(x)}{\sum^{K}_{l=1}\pi_lf_l(x)}&lt;/script&gt;
를 통해 Bayes classifier의 확률을 구하면 결국 다음의 식을 최대화하는 k클래스를 고르는 문제로 귀결된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482719-45f15b08-0431-11e8-9229-cb4941825931.PNG&quot; alt=&quot;LDA-multi3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;역시 단순LDA 경우의 matrix버전이라고 보면 된다. 이 경우 역시 결정에 관여하는 함수식 &lt;script type=&quot;math/tex&quot;&gt;\delta_k(x)&lt;/script&gt;가 &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;의 선형함수이기에, LDA(Linear Discriminant Analysis)라고 부른다. 구체적인 예시로, 변수가 2개이고 클래스K가 총 3개일때 다음과 같이 결과가 나온다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482718-45c2a42a-0431-11e8-9db3-7c29f6a7705d.PNG&quot; alt=&quot;LDA-multi4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;바로 전 그림의 3차원 확률그림을 위에서 바라본것이라 이해하면 된다. 왼쪽그림은 클래스k가 &lt;script type=&quot;math/tex&quot;&gt;k=1,2,3&lt;/script&gt;인 각 경우에
&lt;script type=&quot;math/tex&quot;&gt;P(X=(x_1,x_2)|Y=k)=f_k(x)&lt;/script&gt;
를 추정하여 boundary를 그은 것이다. 저기서 각 원들은 각 분포의 95%신뢰 구간이다. 오른쪽 그림은 실제분포에서 20개씩 관측치를 뽑아 만든 LDA와 Bayes classifier를 비교해본 그림이다.(다시한번, simulated data이기에 Bayes classifier를 구할 수 있다.) error rate가 각각 0.0746, 0.0770으로 비슷한 수준의 성능을 보였다.&lt;/p&gt;

&lt;h4 id=&quot;null-classifier의-함정&quot;&gt;null classifier의 함정(!)&lt;/h4&gt;

&lt;p&gt;그러나, 실제문제 예를 들면 책의 예시에서 default(미납자)를 예측하는 모델을 만들고자 할때 좀 더 흥미로운 문제가 발생한다. 10000개의 training data에 대해 적합한 LDA는 2.75%의 낮은 오류율을 보였다. 그러나, 모델을 적합시킬때, 다음과 같은 점을 고려해야 한다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;training data에만 지나치게 잘 적합되어 있는게 아닐까? 즉, overfitting된게 아닐까?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;보통, data의 갯수n에 비해 parameter의 갯수 p가 많아지면 overfitting의 우려가 생긴다. 그러나 지금은 10000개의 data에 대해 2개의 parameter를 추정하고자 하였기에, 여기에선 overfitting에 대한 걱정은 주 관심사가 아니다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;전체 training data 중 default의 비율이 몇인가? 즉, 아무것도 하지 않은 null classifier에 비해 성능이 어느정도 좋은가?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;여기선 이게, 진짜 문제다. 실제로 training data 중 default(미납자)의 비율은 3.33% 밖에 되지 않았다. (현실적으로 납득이 갈만한 분포) 즉, LDA의 train error 2.75%는 그 자체로 평가되어야 하는게 아니라, 위의 3.33%를 고려하여 평가해야 하는것이다. 아무것도 하지 않고 모두 non-default로 평가하는 null classifier라도 error rate 는 3.33%밖에 되지 않으니 말이다. 이를 더욱 상세하게 볼 수 있게 한 표가 다음에 나와 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482717-458cfece-0431-11e8-8eb2-ff6cc075e7a1.PNG&quot; alt=&quot;LDA-table&quot; /&gt;&lt;/p&gt;

&lt;p&gt;LDA가 default라고 평가한 104명중 81명이 실제 default라서 &lt;strong&gt;default라 평가한 사람들에 한해서는&lt;/strong&gt; 잘한것 같다. 그러나, 전체 10000개의 data 중 non-default 9,667명 중에서는 9,664명을 non-default라고 옳게 평가하였지만, 실제 미납자 333명이 있는데, 그중 81명만을 default라고 제대로 평가하였다! 이는 무려 &lt;strong&gt;default인 사람 중 252/333=75.7%를 놓친 것&lt;/strong&gt;이다. non-default를 잘못 잡아내는 것보다 default를 잘못 잡아내는 것이 주된 관심사일 credit-card 회사에게 이는 결코 좋은 결과가 아니다. 의학분야에서는 이를 sensitivity와 specificity로 명명하는데, &lt;strong&gt;sensitivity&lt;/strong&gt;는 ‘목표 class를 제대로 잡아내었는지’, (여기선 81/333=24.3%) &lt;strong&gt;specificity&lt;/strong&gt;는 ‘반대 class는 제대로 잡아내었는지’, (여기선 9,644/9,667=99.8%)이다.&lt;/p&gt;

&lt;p&gt;그렇다면, 왜 이런 low sensitivity가 발생하게 되었을까? 그 답은, 우리가 따라하려 목표로한 Bayes Classifier가 &lt;strong&gt;‘어떤 class를 틀리던간에 상관 없이’&lt;/strong&gt;, 전체 &lt;strong&gt;&lt;em&gt;‘total&lt;/em&gt; error rate를 줄이고자’&lt;/strong&gt; 목표하였기 때문이다. 쉽게 말해 non-default라고 평가하면 ‘주로’ 맞으니까(train error가 적으니까), default라고 평가하는 것에 대해 매우 신중해진 것이다.&lt;/p&gt;

&lt;p&gt;이러한 문제를 해결하기 위해, Bayes classifier는 약간의 수정을 한다. 구체적으로는 ‘역치’를 수정을 한다. 기존의 Bayes classifier는 해당 class에 속할 확률이 가장 크면 배정을 하는, 즉 default/ non-default의 경우 50%가 넘으면 배정을 하였다. (식으로는
&lt;script type=&quot;math/tex&quot;&gt;P(default=yes|X=x)&gt;0.5&lt;/script&gt;
)그러나 위의 표에서 보았듯이, default는 실제 발생이 매우 드물다. 즉, 50%의 역치로는 이를 제대로 잡아주지 못하는 것이다. (실제로 default를 104명밖에 판결내리지 않았다.) 따라서, 이 역치를 줄여주는 것이다. 예를 들면 특정 input이 default일 확률이 0.2정도만 되어도 default로 평가하는 것이다.(식으로는 
&lt;script type=&quot;math/tex&quot;&gt;P(default=yes|X=x)&gt;0.2&lt;/script&gt;
) 역치 0.2의 LDA에 대한 결과는 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482716-455c1a16-0431-11e8-9747-9feaa80b3239.PNG&quot; alt=&quot;LDA-table2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이제 sensitivity의 관점에서, 전체 333명 중 138명, 즉 41.4%를 놓치게 되어 75.7%였던 지난 모델보다 훨씬 나은 결과를 보여주었다. 물론 non-default를 그만큼 더 못 판별하여 전체 total error-rate는 3.73%으로 늘어나게 되었다. 그러나 default를 잘 잡아내고자 하는 credit-card회사의 관점에서는 sensitivity가 낮은 이 모델이 더욱 좋은 모델인 것이다.&lt;/p&gt;

&lt;h5 id=&quot;여기서-잠깐-용어-정리-false-positive-true-positive-recall-precision&quot;&gt;여기서 잠깐, 용어 정리. (False positive, True positive, Recall, Precision)&lt;/h5&gt;

&lt;p&gt;지금은 sensitivity라는 용어를 사용하였지만, 사실 머신러닝에서는 다음의 단어가 많이 사용된다. False positive, True positive, Recall, Precision. 이들은 앞에서 다루었던 개념들에 명칭만 다른것인데, 우선 false positive, true positive부터 각각 무슨의미인지 살펴보자.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36676263-1a6776dc-1b03-11e8-801b-80d1e3f5fb22.PNG&quot; alt=&quot;LDA99&quot; /&gt;&lt;/p&gt;

&lt;p&gt;앞의 예시와 연결짓자면, ‘+’, 즉 positive는 ‘default’이고 ‘-‘,즉 negative는 ‘non-default’를 의미한다. 좀더 일반화해서 말하자면, &lt;strong&gt;’-‘는 귀무가설, ‘+’는 대립가설&lt;/strong&gt;을 의미한다. 예를들어 False Positive는 실제로는 ‘-‘인데 잘못해서 positive(‘+’)로 판단해버린, 즉 &lt;strong&gt;1종오류를 의미&lt;/strong&gt;한다. 전체 ‘-‘중에서 잘못해서 1종오류의 판단을 낸경우는 위의 표의 notation으로는 FP/N라고 표현할 수 있다. 이것이 &lt;strong&gt;False positive rate&lt;/strong&gt;이다.&lt;/p&gt;

&lt;p&gt;이제, recall과 precision에 대해 알아보자. recall은 말그대로 ‘재현율’이다. 즉, 전체 ‘+’(우리의 관심사건, 혹은 다른말로는 대립가설) 중 &lt;strong&gt;얼마나 True Positive로 잡아내었는지&lt;/strong&gt;를 의미한다. 표의 notation으로는 TP/P로 쓸 수 있다. 한편 precision은 ‘정확률’이다. ‘+’라고 &lt;strong&gt;잡아낸 애들중 얼마나 실제로 ‘+’였는지&lt;/strong&gt; 이다. 즉 TP/P*이다.&lt;/p&gt;

&lt;p&gt;비슷한말이 너무 많다. 이를 알기 쉽게 표로 정리하면, 다음과 같다. 사실 recall이 ‘재현율’, precision이 ‘정확률’, False positive가 ‘잘못 positive로 판단한 애들’이란 의미를 이해하면 많이 헷갈리진 않는다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/36676264-1a9f25dc-1b03-11e8-81ee-c9be6490c31c.PNG&quot; alt=&quot;LDA999&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;다시-돌아와서&quot;&gt;다시 돌아와서,&lt;/h5&gt;

&lt;p&gt;default의 역치(threshold)와 non-default의 오류율이 반비례관계에 있다는 것을 눈치 챘을 것이다. 이는 그래프로 나타내면, 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482713-44c7e6c0-0431-11e8-81e5-8f0028fd4ed0.PNG&quot; alt=&quot;LDA6&quot; /&gt;&lt;/p&gt;

&lt;p&gt;파란선이 default에 대한 오류율, 노란점선이 non-default에 대한 오류율, 검은선이 전체 오류율이다.&lt;/p&gt;

&lt;p&gt;역치가 1/K(여기서는 1/2이므로 0.5)에서 0까지 변동할 동안, default에 대한 오류율은 계속 감소하지만 non-default에 대한 오류율은 계속 증가한다. 그럼, 어느정도 역치가 좋을까? 역시나 이것도 &lt;strong&gt;그때그때 다르다&lt;/strong&gt;. 이 경우 default를 잘못 분류하는 것에 대한 위험비용을 계산을 고려하는 등의 도메인 지식이 요구될 것이다.&lt;/p&gt;

&lt;h4 id=&quot;비교를-위한-roc-curve&quot;&gt;비교를 위한 ROC curve&lt;/h4&gt;

&lt;p&gt;여러 threshold의 오류율을 비교하고자 할때, AUC(area under ROC curve)가 주로 이용된다. &lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482712-4495a6a6-0431-11e8-8533-5ac7dc6217e5.PNG&quot; alt=&quot;LDA7&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위의 선은 각 threshold에 따른 sensitivity와 1-specificity이다. y축은 default를 제대로 판별한 경우, x축은 non-default를 default로 잘못 판별한 경우이므로 왼쪽위 모서리에 가까운 점이 좋은 threshold이고, 저 점에 가까운 ROC를 보이는 모델이 더 좋은 모델이라 할 수 있다. (이는 단순히 비교할때 이렇게 비교하는게  좋다는 것이다. 왜 여기서 나왔는지..)&lt;/p&gt;

&lt;h3 id=&quot;quadratic-discriminant-analysis&quot;&gt;Quadratic Discriminant Analysis&lt;/h3&gt;

&lt;p&gt;Quadratic Discriminant Analysis , 즉 QDA는 이름에서 느껴지다시피 LDA와 약간 다르다. 
&lt;script type=&quot;math/tex&quot;&gt;P(X=(x_1,..,x_p)|Y=k)=f_k(x)&lt;/script&gt;
에 대하여 multivariate normal 분포를 가정하여 Bayes’ theorem을 이용한 분류를 한다는 점에서는 똑같지만, 모든 클래스k에 대하여 &lt;strong&gt;동일한 covariance matrix를 가정했던 LDA&lt;/strong&gt;와 달리 QDA는 k클래스 마다 &lt;strong&gt;각각의 covariance matrix를&lt;/strong&gt; 가지게 한다.&lt;/p&gt;

&lt;p&gt;즉, &lt;script type=&quot;math/tex&quot;&gt;X\sim N(\boldsymbol {\mu_k},\boldsymbol {\sum_k})&lt;/script&gt;를 갖게 하는 것이다. 훨씬 어려워 보이지만, 최종 결정 함수에서는 기존에는 모두 동일하여 제외되었던  &lt;script type=&quot;math/tex&quot;&gt;-\frac{1}{2}x_k^T\sum^{-1}x_k&lt;/script&gt;가 추가되기만 하면 된다. 식으로 나타내면 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482711-4464ee12-0431-11e8-9362-7fdbcb7a9126.PNG&quot; alt=&quot;LDA8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위의 식이 가장 크게 나오는 클래스k로 input을 분류해주는 것이다.  이 결정함수가 x에 대한 선형식이 아니기 때문에 QDA(quadratic)로 부른다.  자연스럽게 decision boundary도 LDA와는 다르게 비선형의 형태를 띄게 된다.&lt;/p&gt;

&lt;p&gt;왜 굳이, 분산이 동일하다 가정하는 LDA와 다르다 가정하는 QDA로 두개의 방법이 있을까? 답은 간단하게 bias-variance trade-off에 있다. p개의 예측변수가 있다면 그들의 covariance matrix를 추정하기 위해선 p(p+1)/2개의 parameter가 필요하다. (p개의 분산과 그들간의 covariance &lt;script type=&quot;math/tex&quot;&gt;_pC_2&lt;/script&gt;개) 이를 k개의 클래스에 대해 다른 분산으로 추정하려면 K*p(p+1)/2개의 parameter를 추정해야 하는 것이다. 작은 수의 parameter를 추정하는 LDA의 경우는 훨씬 덜 flexible하고 variance가 적은 모델이 된다. 그러나, 기본 가정인 공통분산이 아닐 경우, (많은 경우 아닐 것이다. 마치 선형 가정처럼) 높은 bias를 갖게 될 것이다.&lt;/p&gt;

&lt;p&gt;따라서, &lt;strong&gt;training data 수가 적어&lt;/strong&gt;서 variance를 줄이는 것이 중요할 경우 &lt;strong&gt;LDA를&lt;/strong&gt;, &lt;strong&gt;데이터 수가 많아&lt;/strong&gt;서 variance(데이터 셋이 달라지는 것에 따라 모델이 변동하는것)에 대한 우려가 적을때, 혹은 공분산에 대한 가정이 비현실적으로 판단될 때에는 &lt;strong&gt;QDA를&lt;/strong&gt; 사용한다.&lt;/p&gt;

&lt;h3 id=&quot;a-comparison-of-classification-methods&quot;&gt;A Comparison of Classification Methods&lt;/h3&gt;

&lt;p&gt;지금까지 논의한 classification방법들, KNN, 로지스틱 회귀, LDA, QDA에 대해 비교해보자(!).&lt;/p&gt;

&lt;h4 id=&quot;lda와-로지스틱&quot;&gt;LDA와 로지스틱&lt;/h4&gt;

&lt;p&gt;LDA와 로지스틱 회귀는, 접근 방식은 달랐지만 굉장히 유사한 밀접한 관계를 갖는다. 1개의 예측변수에 대해 2-클래스로 분류하는 문제를 보았을때, LDA로 로짓(log odds)를 계산해 보면 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482710-44395982-0431-11e8-9dab-44d8cea280bf.PNG&quot; alt=&quot;LDA9&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;엄밀히 말하자면 해당 식에서 &lt;script type=&quot;math/tex&quot;&gt;c_0,c_1&lt;/script&gt;은 &lt;script type=&quot;math/tex&quot;&gt;\mu_1,\mu_2,\sigma^2&lt;/script&gt;의 함수일 것이다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;로지스틱에서 로짓이 &lt;script type=&quot;math/tex&quot;&gt;log(\frac{p_1}{1-p_1(x)})=\beta_0+\beta_1X&lt;/script&gt;로 X에 대한 1차식으로 나타내어 지는것과 같다. 물론 로지스틱은 계수를 maximum likelihood로, LDA는 정규가정하에서 mean 과 variance의 추정으로 계수를 구하였기에, 이 둘의 계수 자체가 일치하지는 않지만, 선형 decision boundary를 만들어 낸다는 점에서 둘은 유사한 관계를 갖는다. 이러한 관계는 변수가 여러개일 때에도 마찬가지로 유지된다. 결국 적합방법이 다른 같은 계열의 방법이라고 이해하는 것이 좋다. 성능은 물론 LDA의 가정(정규가정)이 어느정도 맞을 경우 LDA가 좋고, 틀릴 경우 로지스틱회귀가 좋게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;binary classification에서 LDA의 로짓을 구하면 다음과 같다.&lt;/p&gt;

  &lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35482709-43f15330-0431-11e8-8c21-2d71cfc8997c.PNG&quot; alt=&quot;LDA10&quot; /&gt;&lt;/p&gt;

  &lt;p&gt;$\therefore \frac {p_1(x)}{p_2(x)}=\frac{\pi_1exp(-\frac{1}{2\sigma^2}(x-\mu_1)^2)}{\pi_2exp(-\frac{1}{2\sigma^2}(x-\mu_2)^2)}$&lt;/p&gt;

  &lt;p&gt;$log( \frac {p_1(x)}{p_2(x)})=log(\frac{\pi_1}{\pi_2})+(x-\mu_1)^2-(x-\mu_2)^2=c_1x+log(c)+c$&lt;/p&gt;

  &lt;p&gt;$=c_1x+c_0$&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;knn&quot;&gt;KNN&lt;/h4&gt;

&lt;p&gt;KNN은 가장 가까운 k개의 관측치를 보고 그들의 특성에 따라 분류를 하는 것으로, &lt;strong&gt;비모수적 방법&lt;/strong&gt;이라고 볼 수 있다. 따라서 실제 decision boundary가 non-linear일 때 좋은 성능을 보일 수 있다. 그러나 어떤 변수가 중요했는지 등에 대한 해석력은 잃게 된다. 애초에 데이터의 현황을 파악하여 반영하는 것이기에.&lt;/p&gt;

&lt;h4 id=&quot;qda&quot;&gt;QDA&lt;/h4&gt;

&lt;p&gt;QDA는 KNN과 LDA, 로지스틱회귀를 합친 특성을 가지고 있다. 이는 KNN보다는 flexible하지 않지만 decision boundary에 non-linear가정을 하였기에 LDA보다 flexible하고, 분포를 가정하였기에 KNN과 다르게 비교적 적은 데이터에서도 잘 적합할 수 있다. (LDA에 비해선 많이 필요하다. parameter수가 더 많으니.)&lt;/p&gt;

&lt;h4 id=&quot;실험을-통한-성능비교&quot;&gt;실험을 통한 성능비교&lt;/h4&gt;

&lt;p&gt;6개의 유형에 대한 시나리오 데이터를 가지고 비교해보았다. 3개는 Bayes decision boundary가 linear, 나머지는 non-linear이다. 각 시나리오 마다 100개의 random noise가 포함된 data를 만들고, 이에 대해 충분히 큰 test-set에 대해 각 모델의 test error를 비교해보았다. 이때, 예측변수(X)는 2개이다.  이를 모두 설명하는 것은 낭비이고, 각각의 시나리오에 대한 결과를 요약하면 다음과 같다.&lt;/p&gt;

&lt;p&gt;시나리오 1: 평균이 다른 서로 uncorrelated된 normal분포. 이때는 LDA가 제일 잘했다. LDA의 가정사항이 normal이니까. KNN이나 QDA는 이 경우 지나친 flexible을 가졌기에 bias측면에서의 강점은 별로 부각되지 않으며(정규가정이 딱 부합한 경우니까) Variance가 커졌기에, 잘 못했다. 로지스틱도 boundary가 선형이라는 점에서 LDA보다 약간 못했다.&lt;/p&gt;

&lt;p&gt;시나리오 2 : 평균이 다르고 correlation이 -0.5인 normal분포.(찌그러진 multivariate normal dist) 시나리오 1과 결과가 다르지 않았다&lt;/p&gt;

&lt;p&gt;시나리오 3: 이번엔 normal이 아닌 t-분포에서 뽑은거. LDA의 가정이 무너졌기에 로지스틱보다 조금 못했다. 그러나 다른애들보단 잘했다.(정규분포와비슷하니까)&lt;/p&gt;

&lt;p&gt;시나리오 4: 첫번째 클래스에 속하는 자료는 0.5 correlation의 normal dist, 두번째 클래스의 자료는 -0.5 correlation. 이 경우는 QDA의 가정을 만족하는 경우니, QDA가 다른 방법보다 잘했다.&lt;/p&gt;

&lt;p&gt;시나리오 5: 이차 decision boundary.(&lt;script type=&quot;math/tex&quot;&gt;X-1^2,X_2^2,X_1X_2&lt;/script&gt;가 들어간 로지스틱함수에서 반응변수를 뽑음) 이땐 예상대로 QDA가 제일 잘했고 그다음이 KNN-CV였다.&lt;/p&gt;

&lt;p&gt;시나리오 6: 이차보다도 더욱 non-linear한 function에서 뽑음. 이땐 KNN-CV, QDA, linear method순. KNN-1은 더욱 못했다. (1은 너무나도 flexible, 즉 너무나도 쉽게 variable) 고로 KNN에서 k를 잘 뽑아야한다는걸 시사한다.&lt;/p&gt;

&lt;p&gt;따라서, 어느상황에나 잘 적합되는 모델은 없다. 실제 decision boundary가 linear이면 LDA, 적당히 non-linear이면 QDA, 훨씬 non-linear(꼬불꾸불)하면 KNN. 이때 KNN의 경우 k를 몇으로 설정하느냐에 따라 결과는 천지차이인데, 다음 장(Cross-validation)에서 이를 다룰 것이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;또한, 3장에서 다루었던것 처럼 linear-method인 LDA나 로지스틱에도 다항식, 즉 &lt;script type=&quot;math/tex&quot;&gt;X^2,X^3&lt;/script&gt;등을 추가하여 non-linear한 결과를 낼 수 있다. 물론 이때는 bias는 줄것이나 Variance는 늘어날 것. 그리고 LDA에서 가능한 모든 2차항과 상호작용항을 추가 할 경우 이는 추정된 계수는 다르겠지만 식은 QDA와 같아진다.&lt;/p&gt;
&lt;/blockquote&gt;
</description>
        <pubDate>Tue, 23 Jan 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/23/ISL-Classification_ch4.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/23/ISL-Classification_ch4.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[ISL] 3장 - 선형회귀 이해하기</title>
        <description>
&lt;h2 id=&quot;3-선형-회귀linear-regression&quot;&gt;3. 선형 회귀(Linear Regression)&lt;/h2&gt;

&lt;p&gt;supervised learning의 아주 간단한 방법인 선형회귀. 다른 통계방법에 비해 간단하나 해석력이 뛰어나 여전히 널리쓰이고 있고 다른 방법들의 기초가 되는 지식이다. 고로 많이 알아두면 알아둘 수록 좋다. 참고한 자료는 ‘Applied Linear Regression Models 4th edition’.&lt;/p&gt;

&lt;p&gt;개인적으로 몰랏던 부분은 (!)로 표시.&lt;/p&gt;

&lt;p&gt;개인적인 참고를 위한 좀더 세부적인 설명은 다음의 형식을 맞춰 적었다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;세부적인 설명을 적는 부분&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;p&gt;독립변수와 종속변수의 관계, 예를 들어 TV,라디오, 뉴스 광고 지출과 총 판매량간의 관계를 밝히고자 할때 다음의 질문이 중요하다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;실제로 광고 지출과 총 판매량간에 관계가 있는가?&lt;/li&gt;
  &lt;li&gt;그 관계가 얼마나 뚜렷한가?&lt;/li&gt;
  &lt;li&gt;TV, 라디어, 뉴스 모두 관계가 있는가, 아니라면 그 중 누가 관계가 있는가?&lt;/li&gt;
  &lt;li&gt;이를 통한 예측은 어느정도 정확하다 할수 있는가?&lt;/li&gt;
  &lt;li&gt;실제 관계가 선형관계인가?&lt;/li&gt;
  &lt;li&gt;각 매체간에 상호작용 효과는 없는가?(TV에 지출한것이 신문에 지출한 것에도 영향을 미치는경우)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;이와 같은 질문에 대하여 선형회귀가 어떠한 답을 내줄 수 있는지를 알아볼 것이다.&lt;/p&gt;

&lt;h3 id=&quot;31-단순-선형회귀-simple-linear-regression&quot;&gt;3.1 단순 선형회귀 (simple linear regression)&lt;/h3&gt;

&lt;p&gt;독립변수와 종속변수의 관계를 설명할때 가장 많이 쓰이는 가장 단순한 그 모델. (모두의 머릿속에 떠오르는 그게 단순 선형회귀 맞다.) 식으로 써보자면&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;Y=\beta_{0}+\beta_{1}X+\epsilon&lt;/script&gt;

&lt;p&gt;이를 영어로는 &lt;strong&gt;‘regressing Y on(to) X’&lt;/strong&gt; 라고 표현한다.&lt;/p&gt;

&lt;p&gt;이때 $\beta_{0}$과 $\beta_{1}$이 우리가 추정하고자 하는 모델의 계수, 바꿔말하면 &lt;strong&gt;parameter&lt;/strong&gt;고, 우리가 추정한 계수는 역시나  $\hat \beta_{0}$과 $\hat \beta_{1}$으로 쓴다. (추정한 값을 간단하게 $b_{0}$의 형태로 쓰기도 한다)&lt;/p&gt;

&lt;h4 id=&quot;그럼-어떻게-계수들을-구하나&quot;&gt;그럼 어떻게 계수들을 구하나?&lt;/h4&gt;

&lt;p&gt;간단하게 우리가 가진 데이터에 우리의 선형 식이 최대한 잘 맞도록 계수를 구한다. ‘잘 맞도록’하는 방법으로는 가장 대표적으로 &lt;strong&gt;least squares&lt;/strong&gt;방법으 쓰인다.(다른 방법은 6장에서 다룬다!) 이는 결국 앞장에서 나왔던 MSE를 최소화하는 계수를 구하는 것과 같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181510-dc9c2998-fdba-11e7-9a2a-edf38c40b3f3.PNG&quot; alt=&quot;linear-regression&quot; /&gt;&lt;/p&gt;

&lt;p&gt;앞장에도 나왔던 그림. 저기서 빨간색이 우리가 가진 데이터, 파란색이 우리가 추정한 함수. 추정된 함수와 가지고 있는 데이터의 차를 잔차라고 하는데, $i$번째 데이터에 대한 잔차를 $e_{i}$라고 표현한다. 데이터와 추정된 함수가 얼마나 잘 맞는지는 잔차들을 제곱(square)해서 구한다. 이를 $RSS$(sum of squares residual) 혹은 $SSE$(sum of square error)이라고 한다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;RSS=e_{1}^2+...+e_{n}^2&lt;/script&gt;

&lt;p&gt;그럼 이걸 최소화하는 계수를 어떻게 구하냐? 간단! 해당 식이 제곱형태이니 미분해서 0이 되는 지점을 찾으면 된다.&lt;/p&gt;

&lt;p&gt;각 parameter에 대해 미분하고 간단하게 정리하여 나온 least square를 통해 추정된 계수는 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;b_{0}=\bar y -b_{1}\bar x&lt;/script&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;b_{1}=\frac{\sum x_{i}(y_{i}-\bar y)}{\sum x_{i}(x_{i}-\bar x)}&lt;/script&gt;

&lt;blockquote&gt;
  &lt;p&gt;$b_{0}$의 경우&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac {\partial RSS} {\partial b_0}=\frac {\partial \sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})^2} {\partial b_0}=0&lt;/script&gt;이 되는 값을 찾으면 된다.&lt;/p&gt;

  &lt;p&gt;${- 2\sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum(y_{i})-nb_{0}-\sum b_{1}x_{i}}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum(y_{i})-\sum b_{1}x_{i}}=nb_{0} $&lt;/p&gt;

  &lt;p&gt;$b_{0}=\frac{\sum(y_{i})}{n} -\frac{\sum b_{1}x_{i}}{n}$&lt;/p&gt;

  &lt;p&gt;$\therefore b_{0}=\bar y -b_{1}\bar x$&lt;/p&gt;

  &lt;p&gt;$b_{1}$의 경우&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\frac {\partial RSS} {\partial b_1}=\frac {\partial \sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})^2} {\partial b_1}=0&lt;/script&gt;이 되는 값을 찾으면 된다.&lt;/p&gt;

  &lt;p&gt;${- 2\sum_{i=1}^{n}x_{i}(y_{i}-b_{0}-b_{1}x_{i})}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum_{i=1}^{n}x_{i}(y_{i}-b_{0}-b_{1}x_{i})}=0 $&lt;/p&gt;

  &lt;p&gt;${\sum(x_{i}y_{i})-b_{0}\sum x_{i}-\sum b_{1}x_{i}^2}=0 $&lt;/p&gt;

  &lt;p&gt;$\sum x_{i}(y_{i}-\bar y)-b_{1}\sum x_{i}(x_{i}-\bar x)=0, \because b_{0}=\bar y -b1\bar x$&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\therefore b_{1}=\frac{\sum x_{i}(y_{i}-\bar y)}{\sum x_{i}(x_{i}-\bar x)}&lt;/script&gt;, 이는 &lt;script type=&quot;math/tex&quot;&gt;\frac{\sum (x_{i}-\bar x)(y_{i}-\bar y)}{\sum (x_{i}-\bar x)(x_{i}-\bar x)}&lt;/script&gt;로도 나타낼 수 있어(전개하면 똑같다) &lt;script type=&quot;math/tex&quot;&gt;b_{1}=\frac{Sxy}{Sxx}&lt;/script&gt;라고 쓰기도 한다 (sum of x&amp;amp;y, sum of x&amp;amp;x)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이 중 기울기, 즉 &lt;script type=&quot;math/tex&quot;&gt;b_{1}&lt;/script&gt;은 독립변수 &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;가 한단위 증가 했을때 종속변수 &lt;script type=&quot;math/tex&quot;&gt;\hat y&lt;/script&gt;(&lt;script type=&quot;math/tex&quot;&gt;=\hat f(x)&lt;/script&gt;)가 얼마나 변하는지를 의미한다. TV와 매출의 예시에서 &lt;script type=&quot;math/tex&quot;&gt;b_{1}=0.475&lt;/script&gt;라면 TV광고에 1달라 더 쓸때마다 평균 매출은 0.475개 늘어난다는 것을 의미한다. (추정된 선형 모델이 이렇게 예측한다는 것이지 실제 세상에선 당근 오차가 있다. )&lt;/p&gt;

&lt;p&gt;그러나 우리가 가진 데이터는 세상 모든 데이터가 아니라 한계가 있기 때문에, 이를 토대로 추정한 ‘추정된 회귀선’도 실재의 데이터를 기준으로 그은 선형 ‘모회귀선’과는 어느정도 차이가 있을 수 밖에 없다. 그러나 어쩔 수 없다. 우리의 주어진 데이터로는 이것이 최선이기에.&lt;/p&gt;

&lt;p&gt;다만, Least Square의 아주 중요한 성질중 하나가 least square 방법을 통해 추정된 회귀선은 &lt;script type=&quot;math/tex&quot;&gt;unbiased&lt;/script&gt;하다는 것이다. 즉 만약 수많은 데이터 셋들에 대하여 수많은 least square적합을 하면, 이 선들의 &lt;strong&gt;평균선&lt;/strong&gt;은 알지 못하는 &lt;strong&gt;진짜 관계&lt;/strong&gt;와 같아질 것이라는 것이다.&lt;/p&gt;

&lt;p&gt;예를 들어 $X$와 $Y$간의 실제 관계가 다음과 같다고 하자&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Y=2+3X+\epsilon&lt;/script&gt; 여기서 $\epsilon$은 평균이 0이고 많은 경우에 분산이 같은(등분산인) 정규분포를 가정한다. (앞에서도 말했듯이 이게 parametric방법. 이 가정이 물론 현실에서 틀릴 수도 있다.분석 후 이에 대한 검토가 이뤄져야한다.)&lt;/p&gt;

&lt;p&gt;위의 식에서 무작위로 100개의 data를 10번 뽑으면, random noise $\epsilon$으로 인해 아주 조금씩 다른 10개의 dataset(크기는 100)이 뽑힐것.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181416-0fab4cda-fdb9-11e7-8743-2efd0010bd19.PNG&quot; alt=&quot;unbiased-linear&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위 그림의 왼쪽에서 빨간선은 진짜 관계선, 즉 true &lt;script type=&quot;math/tex&quot;&gt;f&lt;/script&gt;이다. (&lt;script type=&quot;math/tex&quot;&gt;Y=2+3X+\epsilon&lt;/script&gt;) 이를 토대로 10번 랜덤하게 뽑은 데이터에 적합한 10개의 ‘추정선’들이 오른쪽 그림에 있다. 선들 하나 하나는 빨간선과 조금씩 오차가 있지만, 이들을 모아 &lt;strong&gt;평균&lt;/strong&gt;을 낸다면 진짜 빨간선과 점점 더 가까워 지는 것을 볼 수 있다. 즉 우리의 추정선의 &lt;strong&gt;기대값&lt;/strong&gt;은 진짜 선형 모회귀선의 값이다.&lt;/p&gt;

&lt;p&gt;이는 &lt;script type=&quot;math/tex&quot;&gt;\beta_{0},\beta_{1}&lt;/script&gt;에 대해서도 적용된다. 추정된 회귀계수의 기대값 true 값과 일치한다.&lt;/p&gt;

&lt;p&gt;그럼 기대되는 값이 참값과 같다면 다음 질문은 ‘얼마나 그 기대값이 믿을만한가?’이다. 이는 추정된 값(&lt;script type=&quot;math/tex&quot;&gt;\hat y_{0},\hat \beta_{0},\hat \beta_{1}&lt;/script&gt;)의 &lt;strong&gt;분산&lt;/strong&gt;을 구하는 문제가 된다. (기대값이 같아도 분산은 당근 천차만별일 수 있다.) 이 ‘분산’역시, 진짜값은 알 수 없고 우리가 가진 표본의 ‘표본분산’을 사용 해야한다. least square를 통해 구한 계수의 표본분산(standard error)은 다음과 같다&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181415-0f655a22-fdb9-11e7-8f84-0d85dcf34f3f.PNG&quot; alt=&quot;se_of_coeff&quot; /&gt;&lt;/p&gt;

&lt;p&gt;(이는 사실 앞에서 말했던 &lt;strong&gt;‘오차의 분산이 같다’&lt;/strong&gt;라는 가정이 있어야만 성립한다.)&lt;/p&gt;

&lt;p&gt;식을 보면 알겠지만, &lt;script type=&quot;math/tex&quot;&gt;\sum (x_{i}-\bar x)^2&lt;/script&gt;이 클수록 즉 &lt;script type=&quot;math/tex&quot;&gt;x&lt;/script&gt;의 변동이 클수록, 즉 x들이 멀리 퍼져있을 수록  &lt;script type=&quot;math/tex&quot;&gt;\hat \beta_{1}&lt;/script&gt;의 SE도 확실하게 낮아지는데, 직관적으로 데이터가 &lt;script type=&quot;math/tex&quot;&gt;\bar x&lt;/script&gt;에서 멀리 퍼져 있으면 기울기를 예측하는데 더 도움이 될것이라고 이해가 가능하다.(b0 역시 도움이 되지만, 회귀분석에서 주된 관심은 b1에 있다.)&lt;/p&gt;

&lt;p&gt;여기서 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2=Var(\epsilon)&lt;/script&gt;이다. 그러나 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;는 안 알려진 값이기에 SSE로 이를 추정을 하는데, 이 때 2개의 회귀계수를 추정하고자 하였기에 자유도를 2 잃어 자유도&lt;script type=&quot;math/tex&quot;&gt;df=n-2&lt;/script&gt;이다. (그리고 이렇게 바꿔서 추정을 해서 분포는 Normal에서 t분포로 바뀌게 된다.)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(글고  &lt;script type=&quot;math/tex&quot;&gt;E[MSE]=\sigma&lt;/script&gt;는 분포가정이 없이 가능하지만, t분포를 통한 추정은 &lt;script type=&quot;math/tex&quot;&gt;\epsilon \sim N&lt;/script&gt;이라는 가정이 있기에 가능하다. 책 48참고)&lt;/p&gt;

  &lt;p&gt;$\frac {(y_{i}-\beta_0-\beta_{1}x_{i})}{\sigma} \sim N(0,1)$&lt;/p&gt;

  &lt;p&gt;$\frac {\sum (y_{i}-\hat \beta_0-\hat \beta_{1}x_{i})^2}{\sigma^2} \sim \chi^2[n-2]$, (두개가 hat(&lt;script type=&quot;math/tex&quot;&gt;\hat{\beta}&lt;/script&gt;)으로 바뀐것 유의)&lt;/p&gt;

  &lt;p&gt;$\therefore \frac {SSE}{\sigma^2} \sim \chi^2[n-2]$&lt;/p&gt;

  &lt;p&gt;$\therefore E[\frac {SSE}{\sigma^2}]=n-2$&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;고로 앞장에서 언급하였던 MSE가 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt; 추정에 사용되는 신비한 결과. (&lt;script type=&quot;math/tex&quot;&gt;MSE= \frac{SSE}{(n-2)}=\hat \sigma^2&lt;/script&gt;) 그러나 직관적으로 생각해보면 분산을 ‘추정’한다는 개념에서는 우리의 추정 선에서의 변동을 보는 MSE를 쓰는것이 이해될 수 있다.&lt;/p&gt;

&lt;p&gt;또한 추정된 &lt;script type=&quot;math/tex&quot;&gt;\sigma&lt;/script&gt;는 거기에 제곱근을 씌워, RSE, 혹은 RMSE(root MSE)라고 쓴다. &lt;script type=&quot;math/tex&quot;&gt;RMSE=\sqrt \frac{SSE}{(n-2)}=\hat \sigma&lt;/script&gt;, 책에선 RSE. 헷갈리면 MSE만 기억해도 된다.&lt;/p&gt;

&lt;p&gt;이 추정된 분산을 토대로 회귀 계수에 대한 신뢰구간이나 가설검정을 할 수 있는데, 95% 신뢰구간은 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;[\hat \beta_{1}-t_{0.25, n-2}*SE(\hat \beta_{1}),\hat \beta_{1}+t_{0.25, n-2}*SE(\hat \beta_{1})]&lt;/script&gt;

&lt;p&gt;이는 b0의 경우에도 마찬가지 이다. 위의 예에서 b1의 95%신뢰구간이 [0.042,0.053]이 나왔을때 이는 &lt;strong&gt;95%의 신뢰수준으로 TV광고의 1달러 증가가 [0.042,0.053]개의 평균 판매액의 증가를 낸다&lt;/strong&gt;라고 말할 수 있다.&lt;/p&gt;

&lt;p&gt;가설검정은 대표적으로 X와 Y간에 관계가 있는지를 보는데 이는 결국&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;H_{0}: \beta_{1}=0&lt;/script&gt;을 검정하는것으로 귀결된다.&lt;/p&gt;

&lt;p&gt;위에서 언급했듯이 &lt;script type=&quot;math/tex&quot;&gt;\frac {\hat \beta_1-\beta_{1}}{SE(\hat \beta_{1})}&lt;/script&gt;이 &lt;script type=&quot;math/tex&quot;&gt;t(n-2)&lt;/script&gt;분포를 따르므로,&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;t= \frac {\hat \beta_1-0}{SE(\hat \beta_{1})}&lt;/script&gt;을 구하여 t분포상의 p-value(귀무가설 하에서 이런 사건이 일어날 확률이 얼마나 되는지를 의미하는 확률)를 구하면 된다. b0에 대한 검정도 위의 식에서 1을 0으로 바꿔서 똑같이 진행하면 된다. 지나치게 작은(유의수준보다 작은) p-value는 귀무가설을 기각할 만한 근거를 의미한다. 위의 가설에서는 ‘X와 Y가 관계 없다’(우리가 세운 X와 Y의 모델은 쓸모없다)가 귀무가설이었으니 p-value가 작을수록 좋다.&lt;/p&gt;

&lt;h4 id=&quot;모델의-평가&quot;&gt;모델의 평가&lt;/h4&gt;

&lt;p&gt;우리가 세운 모델이 쓸모가 있다고 결론이 나면, 두번째로는 얼마나 잘 적합을 하는지를 봐야한다. 이는 앞에서 언급되었던 MSE를 통해 이루어 진다&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;MSE= \frac{SSE}{(n-2)}=\hat \sigma^2&lt;/script&gt;, (책에선 RMSE(root MSE)를 썻다. RMSE를 사용하는 이유는 아래에서 나오지만, 바로 Y의 단위에 맞추어 생각할 수 있는 scaling의 의미가 있기 때문이다. )(???F통계량이 모델의 정확도 평가로 쓰일 수 있는가)&lt;/p&gt;

&lt;p&gt;RSE는 우리의 데이터를 우리 모델이 얼마나 잘 설명할 수 있는가를 의미하는데, 예시에서 RSE가 3.26이라면 실제 판매량 데이터가 우리 모델에서 3.26개 정도 차이날 것이라는 의미이다. 이 차이가 얼마나 큰것인지는 역시 문제에 따라 다르다.( 예측변수가 1,2,3..이라면 3.26은 큰것이지만 예측변수가 10000,2000등이라면 3.26은 굉장히 작은것. 단위에 따라 다르다, 즉 scaling을 포함하지 않았다) MSE가 추정된 ‘변동’이라는 의미에서, RSE는 true regression line에서 벗어난 정도의 ‘추정’이 라고 말할 수 있다.&lt;/p&gt;

&lt;p&gt;이를 비율로써 계산한 지표가 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;인데, &lt;strong&gt;‘전체 변동중 설명된 변동의 비율’&lt;/strong&gt;을 의미한다. 비율이므로 당연히 0~1사이 값이다. 이를 좀더 설명하자면&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;SST=\sum(y_{i}-\bar y)^2​&lt;/script&gt;,  즉 regression을 하기도 전에 있던, 전체의 평균에서 각 값들이 얼마나 왓다갔다 하는가를 의미하는 지표이다. (왜 전체 변동을 &lt;script type=&quot;math/tex&quot;&gt;\bar y​&lt;/script&gt;에서의 거리로 구하나? - 표본분산을 구할때 sample mean을 빼주는걸 생각하면 됨. 전체 분산 중 우리가 설명한 분산) 이 중 우리가 예측한 ‘왓다갓다 하는 정도’, 즉 데이터의 변동은 우리의 추정된 함수선일 것이고(SSR로 자주 표현), 추정된 함수선이 예측하지 못한 변동은 앞에서 다룬 SSE(&lt;script type=&quot;math/tex&quot;&gt;SSE=\sum_{i=1}^{n}(y_{i}-b_{0}-b_{1}x_{i})^2​&lt;/script&gt;)이다. 고로 &lt;script type=&quot;math/tex&quot;&gt;SST=SSR+SSE​&lt;/script&gt; 이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;notation에 대해 정리하자면&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;RSS=SSE&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;RSE=\sqrt{MSE}&lt;/script&gt;, &lt;script type=&quot;math/tex&quot;&gt;TSS=SST&lt;/script&gt;이다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;‘전체 변동중 설명된 변동의 비율’&lt;/strong&gt;인 &lt;script type=&quot;math/tex&quot;&gt;R^2=\frac{SSR}{SST}=1-\frac{SSE}{SST}&lt;/script&gt;이다. &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;가 높을 수록, &lt;script type=&quot;math/tex&quot;&gt;SSE&lt;/script&gt;가 낮을 수록 데이터의 변동을 잘 설명하고 있다고 보면 된다. 그러나 안타깝게도 &lt;strong&gt;얼마나 높은 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;가 만족스러운 적합이냐에는 답이 없다&lt;/strong&gt;. 그도 그럴것이, 물리학 등 분야에서는 높은 수치가 기준이 될것이나, 마케팅, 사회학 등 분야에서는 비교작 낮은 수치의 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;만으로도 의미가 있다고 판단 될 것이다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;또한 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;는 단순회귀 문제에서는 ‘얼마나 선형관계가 있느냐’를 보는 문제와 같아지기에, 우리의 데이터의 X와 Y의 &lt;script type=&quot;math/tex&quot;&gt;corelation&lt;/script&gt;을 보는것과 같아진다! 즉, 단순선형회귀에 국한해서, &lt;script type=&quot;math/tex&quot;&gt;R^2=r^2&lt;/script&gt;이다.&lt;/strong&gt; 추가로 단순선형회귀에선 cor(X,Y)나 cor(&lt;script type=&quot;math/tex&quot;&gt;\hat Y,Y&lt;/script&gt;)를 구하는거나 같아진다. Y.hat이 어차피 X의 선형결합이기 때문.&lt;/p&gt;

&lt;h3 id=&quot;32-다중-선형-회귀&quot;&gt;3.2 다중 선형 회귀&lt;/h3&gt;

&lt;p&gt;독립변수가 많을때는 어쩔까? 단순히 각각의 단순선형회귀를 여러개 하면? 안된다. 왜 안될까?(문제)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;우선 애초에, 3개의 독립변수가 다 주어졌을때, 3개의 모델로는 최종 어떤 Y를 결정해야 할지 정할 수가 없다.&lt;/li&gt;
  &lt;li&gt;각각에 대한 적합은 &lt;strong&gt;독립변수 끼리의 상호작용&lt;/strong&gt;을 배제해 버린다. 즉, 서로 correlated된 경우 문제가 심각해진다. (correlated란 서로 관계가 높아서, 한쪽을 알면 다른 한쪽도 어느정도 설명할 수 있다는것. ex-TV광고에 많이 투자한 회사는 대체적으로 신문광고에도 많이 투자했을것)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;고로, 여러 독립변수를 한번에 고려할 수 있는 다중 선형회귀를 사용한다. 식은 아주 간단하다&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;Y=\beta_{0}+\beta_{1}X_{1}+...+\beta_{p}X_{p}+\epsilon&lt;/script&gt;

&lt;p&gt;여기서 &lt;script type=&quot;math/tex&quot;&gt;\beta_{i}&lt;/script&gt;는 &lt;strong&gt;다른 독립변수들이 고정되어 있을때(!)&lt;/strong&gt; &lt;script type=&quot;math/tex&quot;&gt;X_{i}&lt;/script&gt;의 한단위 증가가 Y의 ‘평균’에 미치는 영향이다. (문제 : 실제 상황에서는 키가 크면 몸무게가 늘어난다. 이렇게 실제에선 다른변수가 고정되어 있을 수가 없는데 그럼 &lt;script type=&quot;math/tex&quot;&gt;\beta_{i}&lt;/script&gt;는 무슨 의미가 있을까?- 답: 회귀계수에 대한 해석을 단순회귀와 완벽하게 같은 이유로 이해하려면 변수들이 완전한 선형독립, 혹은 eigen vector여야만 가능하다. 그러나 현실에서는 변수간에 완전한 독립인 경우가 거의 없기에, 기본적으로 어쩔수 없다고 판단하고 분석을 진행한다. 이 정도가 크다 판단되면 상호작용항을 넣어주는데 이 경우 &lt;script type=&quot;math/tex&quot;&gt;(\beta_{i}+\beta_{ij}X_{j})X_{i}&lt;/script&gt;와 같이 다른 변수가 증가함을 반영한다)&lt;/p&gt;

&lt;h4 id=&quot;모델의-평가-1&quot;&gt;모델의 평가&lt;/h4&gt;

&lt;p&gt;모델의 평가는 역시 똑같은 방식으로 한다. 예측한 값&lt;script type=&quot;math/tex&quot;&gt;y_{i}&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;\hat y_{i}&lt;/script&gt;이 얼마나 차이가 날지. 식으로 쓰면 다음과 같다.&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181414-0f1badbe-fdb9-11e7-95d9-bedbdbd2d925.PNG&quot; alt=&quot;RSS-multi&quot; /&gt;&lt;/p&gt;

&lt;p&gt;변수가 2개인 경우 그림으로 나타낼 경우 좀더 직관적으로 와닿을 수 있다. 이제 2차원 평면에서의 1차원 선이 아니라 3차원 공간에서의 2차원 평면과 데이터의 차이를 의미하게 되었다. (사람의 인식의 한계가 3차원이기에, X1, X2 두개의 독립변수에 대한 multi linear regression을 본다.)&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181413-0ee0c08c-fdb9-11e7-9ef1-50d888cba8e1.PNG&quot; alt=&quot;graph-multi&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;모델의-계수&quot;&gt;모델의 계수&lt;/h4&gt;

&lt;p&gt;이 경우 해당 RSS를 최소화하는 &lt;script type=&quot;math/tex&quot;&gt;\hat \beta_{0},...,\hat \beta_{p}&lt;/script&gt;은 역시나 least square로 구하는데, 이 경우 matrix 연산이 들어간다. (matrix 연산은 별게 아니라 계산을 한꺼번에 하기 편한것. 사실 b0,b1에 대해 미분했듯이 전부 다 미분하고 풀면 답은 같게 나온다)&lt;/p&gt;

&lt;p&gt;참고로 matrix에서의 least square는 다음과 같다(일일이 해보면 여러개의 편미분분을 연립방적식 하는거랑 같다)&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;X'Xb=X'Y&lt;/script&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Y=Xb&lt;/script&gt;에서&lt;/p&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;\begin{pmatrix} y_{1}\\ y_{2}\\..\\y_{n}\end{pmatrix}=\begin{pmatrix}\begin{matrix} 1\\ 1\\..\\1\end{matrix}\begin{matrix} x_{11}\\ x_{12}\\..\\x_{1n}\end{matrix}\begin{matrix} x_{21}\\ x_{22}\\..\\x_{2n}\end{matrix}\end{pmatrix}\begin{pmatrix}b_{0}\\ b_{1}\\b_{2}\end{pmatrix}&lt;/script&gt;

  &lt;p&gt;(n * 1) = (n * 3) (3* 1)이다.&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;X'Xb=X'Y&lt;/script&gt; 이 식은 이렇게 풀린다. 일일이 해봄&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
X'X=(3 *n)(n*3)=\begin{pmatrix}\ n&amp; \sum x_{1}&amp;\sum x_{2}\\ \sum x_{1}&amp; \sum x_{1}^2&amp;\sum x_{1}\sum x_{2}\\ \sum x_{2}&amp; \sum x_{1}\sum x_{2}&amp;\sum x_{2}^2\end{pmatrix} %]]&gt;&lt;/script&gt;
&lt;script type=&quot;math/tex&quot;&gt;X'Y=(3*n)(n*1)=\begin{pmatrix}\sum y\\\sum x_{1}y\\\sum x_{2}y\end{pmatrix}&lt;/script&gt;
&lt;script type=&quot;math/tex&quot;&gt;\therefore X'Xb=X'Y&lt;/script&gt;
&lt;script type=&quot;math/tex&quot;&gt;% &lt;![CDATA[
=\begin{pmatrix}\ n&amp; \sum x_{1}&amp;\sum x_{2}\\ \sum x_{1}&amp; \sum x_{1}^2&amp;\sum x_{1}\sum x_{2}\\ \sum x_{2}&amp; \sum x_{1}\sum x_{2}&amp;\sum x_{2}^2\end{pmatrix}\begin{pmatrix}b_{0}\\ b_{1}\\b_{2}\end{pmatrix}=\begin{pmatrix}\sum y\\\sum x_{1}y\\\sum x_{2}y\end{pmatrix} %]]&gt;&lt;/script&gt;&lt;/p&gt;

  &lt;p&gt;이를 전개해보면&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;nb_{0}+b_{1}\sum x_{1}+b_{2}\sum x_{2}=\sum y&lt;/script&gt;등의 식이 나오는데, 이는 결국 단순선형에서 최소제곱의 정규방정식을 푸는것과 같게 나온다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;실제로 다중회귀를 해보면, 각각 하나씩 넣었을때는 유의하다(p-value가 작게)나온 변수일지라도 함께 들어가면 별로 안 중요한 경우가 생긴다. 아래 예시.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181413-0ee0c08c-fdb9-11e7-9ef1-50d888cba8e1.PNG&quot; alt=&quot;multi-table&quot; /&gt;&lt;/p&gt;

&lt;p&gt;단순회귀에서는 newspaper역시 p-value가 유의하게 나왔다.&lt;/p&gt;

&lt;p&gt;그러나 correlation matrix에서 보았을때 news는 radio랑 correlation계수가 높았고, 다중 회귀에서의 p-value가 엄청나게 높다.(즉 newspaper의 회귀계수가 0이라할 충분한 근거가 있다.) 다른 중요한 변수들(TV, 라디오 광고비용)이 이미 안중요한 변수(신문 광고비용)이 할 수 있던 설명을 다 해버렸기에, 그 변수는 더 이상 정보를 주는 변수가 아닌 것이다. 이는 신문 광고는 sale과 indirect한 영향을 주는 변수였다고 설명을 할 수도 있는데, indirect하지만 관계가 있는 대표적인 예로 아이스크림 판매량과 물놀이 사고가 있다. (더위라는 잠복변수)&lt;/p&gt;

&lt;hr /&gt;

&lt;h4 id=&quot;다중회귀에서의-질문들&quot;&gt;다중회귀에서의 질문들&lt;/h4&gt;

&lt;p&gt;다중회귀에서는 다음과 같은 질문들이 주로 던져지는데,&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;p개의 독립변수 중 하나라도 유의한가? (==모든 회귀계수가 전부0은 아닌가?)&lt;/li&gt;
  &lt;li&gt;그럼 모든p가 유의한가, 그중 몇개만 유의한가?&lt;/li&gt;
  &lt;li&gt;우리 데이터에 얼마나 잘 적합됬는가&lt;/li&gt;
  &lt;li&gt;우리의 예측은 얼마나 정확할 것인가?&lt;/li&gt;
&lt;/ol&gt;

&lt;h5 id=&quot;1-p개의-독립변수-중-하나라도-유의한가-모든-회귀계수가-전부0은-아닌가&quot;&gt;1. p개의 독립변수 중 하나라도 유의한가? (==모든 회귀계수가 전부0은 아닌가?)&lt;/h5&gt;

&lt;p&gt;이는 다음을 검정하는 문제로 귀결되고,&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;H_{0} : \beta_{1}=\beta_{2}=...=\beta_{p}=0&lt;/script&gt;

&lt;p&gt;이는 다음의 통계량을 통해 결정된다.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;F=\frac{(SST-SSE)/p}{SSE/(n-(p+1))}=\frac{MSR}{MSE}&lt;/script&gt; (MSR은 SSR을 df로 나눈것. 여기서 df는 독립변수의 갯수)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;그러나 뒤에 나올 q개의 계수만을 검정하는 데에도 일반화되서 쓰기에는 다음 식이 짱이다.&lt;/p&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;F=\frac {SSE(R)-SSE(F)}{df_{R}-df_{F}} \div \frac{SSE(F)}{df_{F}} \sim F(df_{R}-df_{F},df_{F})&lt;/script&gt;

  &lt;p&gt;저기서 R과 F는 각각 Reduced model, Full model이고, 쉽게 말해 R은 귀무가설 하의 모델, F는 모든 변수가 들어간 모델이라 보면 된다. (책의 278쪽)&lt;/p&gt;

  &lt;p&gt;SSE의 df는 &lt;script type=&quot;math/tex&quot;&gt;(n-[b_{0}\sim b_{p}갯수])&lt;/script&gt;이므로 &lt;script type=&quot;math/tex&quot;&gt;df_{R}-df_{F}=q&lt;/script&gt;(검정하고자 하는 변수 갯수) 라고 볼 수 있다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;앞에서도 나왔듯이 &lt;script type=&quot;math/tex&quot;&gt;E[SSE/(n-(p+1))]=\sigma^2&lt;/script&gt;이고, (기대값은 바로 나오지만, 이에 대한 분포가정을 하려면 error term의 normal 가정이 있어야 한다.)&lt;/p&gt;

&lt;p&gt;귀무가설 하에서 &lt;script type=&quot;math/tex&quot;&gt;E[\frac{SST-SSE}{p}]=\sigma^2&lt;/script&gt;이기에, 귀무가설이 참이라면 이는 1에 가까운 값(단순회귀일때 SSR의 기대값을 구해보자!!!)을 가질 것이다.&lt;/p&gt;

&lt;p&gt;구체적으로 위의 통계량 &lt;script type=&quot;math/tex&quot;&gt;F&lt;/script&gt;는 자유도가 &lt;script type=&quot;math/tex&quot;&gt;(p, n-(p+1))&lt;/script&gt;인 F분포를 따른다. F분포는 이렇게 생김.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181411-0e6496a6-fdb9-11e7-9e85-fb60c94caef6.PNG&quot; alt=&quot;F-dist&quot; /&gt;&lt;/p&gt;

&lt;p&gt;q개의 변수에 대한 검정은 다음을 통한다.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;F=\frac{RSS_{0}-RSS/q}{RSS/(n-p-1)}&lt;/script&gt;여기서 &lt;script type=&quot;math/tex&quot;&gt;RSS_{0}&lt;/script&gt;은 q개 없애고 적합시킨 모델(Reduced model)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;하나의 변수에 대한 검정에서는 &lt;script type=&quot;math/tex&quot;&gt;F=t^2&lt;/script&gt;이다.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Q. 왜 전체에 대한 F검정을 하느냐, 그냥 각 계수에 대한 t-test p-value를 보면 안돼냐?&lt;/p&gt;

&lt;p&gt;A.위험하다. 특히 변수가 많을때. 변수p가 100개 이고 모두가 유의미하지 않은 변수(&lt;script type=&quot;math/tex&quot;&gt;\beta_{i}=0&lt;/script&gt;)일지라도 &lt;strong&gt;5개 변수(0.05) 정도가 확률적으로 ‘유의한’ p-value를  가질수도.(!)&lt;/strong&gt; 그러나 F검정은 변수의 갯수도 고려를 하기에 전체에 대한 p-value를 구할 수 있음.– ANOVA에서 3C2하지 않는 이유와 일맥상통!!!봐봐봐&lt;/p&gt;

&lt;h5 id=&quot;2-그럼-모든p가-유의한가-그중-몇개만-유의한가&quot;&gt;2. 그럼 모든p가 유의한가, 그중 몇개만 유의한가?&lt;/h5&gt;

&lt;p&gt;전체에 대한 F검정이 유의하다 나오면(즉 전부다 쓸모 없지는 않다.), 그중 어떤 변수를 써야할까? 이때 쓰이는게 변수선택법. 6장에서 더 자세히 다룬다. 추가적으로 모델을 평가하기 위한 기준으론 AIC, BIC, Mallow’s &lt;script type=&quot;math/tex&quot;&gt;C_{P}&lt;/script&gt;등이 있다.&lt;/p&gt;

&lt;p&gt;변수선택법에 대해 간단하게 설명하자면&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;전진 선택법 :
    &lt;ul&gt;
      &lt;li&gt;1) 아무 변수도 포함되지 않은 모델에서&lt;/li&gt;
      &lt;li&gt;2) t통계량이 제일 유의한 변수 한개를 넣는다( 기준은? 한 변수에 관해서는 F통계량, t통계량, 오차 제곱합 감소 다 같은 결과를 낸다, 암꺼나로 해도 됨)&lt;/li&gt;
      &lt;li&gt;3)해당 변수를 넣은 상태에서 2번을 계산하여 또 하나를 넣는다. (변수 하나가 기본으로 들어가 있으니 p-value가 달라짐)&lt;/li&gt;
      &lt;li&gt;4) 더이상 중요한 변수가 없으면(t 통계량이 유의한게 없으면) 멈춘다&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;후진 제거법 :
    &lt;ul&gt;
      &lt;li&gt;1) 모든 변수가 있는 모델에서&lt;/li&gt;
      &lt;li&gt;2) 제일 큰 p-value를 가진 변수를 지움&lt;/li&gt;
      &lt;li&gt;3) 남은 p-1개 변수로 또 p-value계산해서 뺀다&lt;/li&gt;
      &lt;li&gt;4) 더이상 뺄 변수가 없으면 멈춘다&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;전진 단계적 회귀(mixed selection)
    &lt;ul&gt;
      &lt;li&gt;1) 아무 변수도 포함되지 않은 모델에서&lt;/li&gt;
      &lt;li&gt;2) t통계량이 제일 유의한 변수 한개를 넣는다&lt;/li&gt;
      &lt;li&gt;3) 해당 변수를 &lt;strong&gt;넣은 상태에서 p-value를 계산해서&lt;/strong&gt; 유의미 하지 않은 변수를 &lt;strong&gt;지운다&lt;/strong&gt; (이때 들어오기 위한 p-value임계점과 나가는 임계점을 다르게 한다. 보통 어렵게 들어오고(&lt;script type=&quot;math/tex&quot;&gt;\alpha=0.1&lt;/script&gt;) 쉽게 뺀다(&lt;script type=&quot;math/tex&quot;&gt;\alpha=0.1&lt;/script&gt;5) )&lt;/li&gt;
      &lt;li&gt;4) 다시 중요한 순대로 새로운 변수를 넣는다.&lt;/li&gt;
      &lt;li&gt;5) 더이상 넣을 변수도, 뺄 변수도 없으면 멈춤&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;당근 mixed인 전진 단계적 회귀가 젤 좋다.&lt;/p&gt;

&lt;h5 id=&quot;3-우리-데이터에-얼마나-잘-적합됬는가&quot;&gt;3. 우리 데이터에 얼마나 잘 적합됬는가&lt;/h5&gt;

&lt;p&gt;당근 MSE와 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;로 구한다. 근데 다중 회귀에선 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;이 cor(X,Y)를 구하는건 더이상 될 수 없고(변수가 1개가 아니니까)  cor(&lt;script type=&quot;math/tex&quot;&gt;\hat Y,Y&lt;/script&gt;)의 제곱과 같다. 앞에서 나왓듯이 least square는 주어진 자료 하에서 이 cor을 최대로 만드는 linear모델을 찾아준다.&lt;/p&gt;

&lt;p&gt;그러나 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;는 변수를 추가하면 할수록 항상 증가한다. 아주 쓸모없는 변수이더라도 least square에 따라 주어진 데이터에서 조금이라도 더 적합을 하게 된다. (몸무게 예측에 안드로메다 태양 흑점수를 추가한다해도!) 이는 주어진 데이터에 지나치게 과적합(overfitting)을 하게 되는것으로, 이러한 성질때문에 모델을 비교할때는 &lt;script type=&quot;math/tex&quot;&gt;R^2&lt;/script&gt;외에 변수의 숫자도 고려한 지표를 사용한다. &lt;strong&gt;변수를 추가함으로써 생기는 위험&lt;/strong&gt;이 (모델의 복잡도 혹은 overfit) &lt;strong&gt;추가함으로써 생기는 설명력&lt;/strong&gt;보다 큰지를 고려하는것이다. AIC, BIC등등&lt;/p&gt;

&lt;p&gt;또 MSE역시 변수의 갯수를 고려한다.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;MSE= \frac{SSE}{n-(p+1)}&lt;/script&gt; 다시 상기. 사용된 변수갯수(p)에 &lt;script type=&quot;math/tex&quot;&gt;b_{0}&lt;/script&gt;까지 해서 p+1개.&lt;/p&gt;

&lt;p&gt;단순한 수치 외에, 사실 그림이 이를 판단하는데에 좋다. (실제로는 잔차그림이 많이 쓰인다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181410-0e137ae6-fdb9-11e7-8e87-1f3560c5c9c5.PNG&quot; alt=&quot;graph-multi2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;그림을 보면 TV와 Radio에 따른 sales에서 애초에 빨간점의 분포가 약간 곡선(convex)를 띄고 있어 ‘선형’이 아님을 볼 수 있다. 이는 TV와 Radio에 둘다 투자할 경우 ‘시너지’가 발생해서 sale이 더 올라간다는 직관적인 생각과도 일치한다. ‘시너지’ 혹은 ‘상호작용’에 대해서는 뒷 부분에서 설명한다.&lt;/p&gt;

&lt;h5 id=&quot;4-우리의-예측은-얼마나-정확할-것인가&quot;&gt;4. 우리의 예측은 얼마나 정확할 것인가?&lt;/h5&gt;

&lt;p&gt;실제 함수 관계가 위처럼 선형이 아닐 수도 있지만, 실제 관계(&lt;script type=&quot;math/tex&quot;&gt;f&lt;/script&gt;)가 선형임에도 우리가 예측한 선형모델(&lt;script type=&quot;math/tex&quot;&gt;\hat f&lt;/script&gt;)과는 차이가 있을 수 있다.&lt;/p&gt;

&lt;p&gt;모델의 정확도를 판단할때는 우선적으로 후자, &lt;strong&gt;즉 실제 관계가 선형인 경우 우리 모델과 얼마나 다를지&lt;/strong&gt; 에 집중한다. (위의 그림처럼 실제 관계가 선형인지 아닌지는 모델이 다 세워진 후에 진단을 한다.) &lt;script type=&quot;math/tex&quot;&gt;f&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;\hat f&lt;/script&gt;가 얼마나 다를지는 &lt;strong&gt;‘신뢰구간’&lt;/strong&gt;(confidence interval)으로 구한다&lt;/p&gt;

&lt;p&gt;또 다른 주요한 예측은 특정한 실제 값&lt;script type=&quot;math/tex&quot;&gt;y_{0}&lt;/script&gt;을 예측하고자 할때 &lt;script type=&quot;math/tex&quot;&gt;y_{0}&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;\hat f&lt;/script&gt;가 얼마나 차이날지 이다. &lt;script type=&quot;math/tex&quot;&gt;y_{0}&lt;/script&gt;은 실제 함수&lt;script type=&quot;math/tex&quot;&gt;f&lt;/script&gt;에서도 random error를 띄며 발생할 것이기에, 이를 예측하는 &lt;strong&gt;예측 신뢰구간(Prediction interval)은 Confidence interval보다 클 수 밖에 없다&lt;/strong&gt;(!)&lt;/p&gt;

&lt;p&gt;이 둘이 헷갈릴 수 있는데, &lt;script type=&quot;math/tex&quot;&gt;f&lt;/script&gt;는 fixed된 unknown함수 선, 즉 특정 x에 대해서 ‘fixed’된 &lt;script type=&quot;math/tex&quot;&gt;f(x)&lt;/script&gt;가 있는 것이고, &lt;script type=&quot;math/tex&quot;&gt;y_{0}&lt;/script&gt;는 &lt;script type=&quot;math/tex&quot;&gt;f(x)+\epsilon&lt;/script&gt;, 즉 그 함수선 위의 점을 중심으로 random error(=irreducible error)를 띄며 여러가지로 나타날 수 있다. 우리는 &lt;script type=&quot;math/tex&quot;&gt;\hat f&lt;/script&gt;을 근거로 예측을 할 수밖에 없기에, &lt;strong&gt;‘개별 값에 대한 예측’ 에 대한 변동은 [&lt;script type=&quot;math/tex&quot;&gt;f&lt;/script&gt;와 차이 나는 &lt;script type=&quot;math/tex&quot;&gt;\hat f&lt;/script&gt;의 변동 + 개별값 자체의 random error]&lt;/strong&gt;이다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;구체적으로 말하자면&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;신뢰구간의 경우&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;\sigma^2[\hat f(x_{0}))]=\sigma^2[\frac{1}{n}+\frac{(x_{0}-\bar x)^2}{\sum(x_{i}-\bar x)^2}]&lt;/script&gt;이고 이때 &lt;script type=&quot;math/tex&quot;&gt;\sigma^2&lt;/script&gt;는 MSE로 추정된다.(이 과정에서 자유도를 2잃고 t분포가 된다)&lt;/p&gt;

  &lt;p&gt;이때 신뢰구간은 &lt;script type=&quot;math/tex&quot;&gt;\hat f(x_{0})\pm t(1-\alpha/2;n-2)*SE[\hat f(x_{0})]&lt;/script&gt;이 된다.&lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;개별 예측값에 대한 예측 신뢰구간의 경우&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;개별값 &lt;script type=&quot;math/tex&quot;&gt;y_{0}&lt;/script&gt;이 추정된 평균&lt;script type=&quot;math/tex&quot;&gt;\hat f(x_{0})&lt;/script&gt;와 얼마나 떨어져 있는지를 &lt;script type=&quot;math/tex&quot;&gt;pred&lt;/script&gt;라고 하면&lt;/p&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;\sigma^2 [pred]=\sigma^2[y_{0}-\hat f(x_{0})]=\sigma^2+\sigma^2[\hat f(x_{0})]&lt;/script&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;=\sigma^2+\sigma^2[\frac{1}{n}+\frac{(x_{0}-\bar x)^2}{\sum(x_{i}-\bar x)^2}]=\sigma^2[1+\frac{1}{n}+\frac{(x_{0}-\bar x)^2}{\sum(x_{i}-\bar x)^2}]&lt;/script&gt;

  &lt;p&gt;이 된다. 이때 &lt;script type=&quot;math/tex&quot;&gt;\sigma&lt;/script&gt;는 MSE로 추정된다.(이 과정에서 자유도를 2잃고 t분포가 된다)&lt;/p&gt;

  &lt;p&gt;이때 신뢰구간은 &lt;script type=&quot;math/tex&quot;&gt;\hat f(x_{0})\pm t(1-\alpha/2;n-2)*SE[pred]&lt;/script&gt;이 된다.&lt;/p&gt;

  &lt;p&gt;(책 57, 62쪽, 책에선 &lt;script type=&quot;math/tex&quot;&gt;\hat Y_{h}&lt;/script&gt;를 추정된 함수, &lt;script type=&quot;math/tex&quot;&gt;\hat Y_{h(new)}&lt;/script&gt;를 개별 값으로 notation씀)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;책의 예시에서 TV에 10000만, radio에 2000만을 투자 할 경우 true &lt;script type=&quot;math/tex&quot;&gt;f(x)&lt;/script&gt;에 대한 95% confidence interval은 [10,985,11,528] 이었다. 이는 &lt;strong&gt;해당 interval을 100개의 dataset에 대해 구할경우 그중 95개가 true &lt;script type=&quot;math/tex&quot;&gt;f(x)&lt;/script&gt;를 포함할것&lt;/strong&gt;이라는 의미.&lt;/p&gt;

&lt;p&gt;한편 특정 city, 즉 개별 예측에 대한 prediction interval은 [7,930, 14,580]으로, 더 넓어졌다. 이는 &lt;strong&gt;95%신뢰 수준으로 true &lt;script type=&quot;math/tex&quot;&gt;y_{0}&lt;/script&gt;(!)을 포함할 것&lt;/strong&gt;이라는 의미.&lt;/p&gt;

&lt;h3 id=&quot;33-그-외-회귀모형에서-고려할-것들&quot;&gt;3.3 그 외 회귀모형에서 고려할 것들&lt;/h3&gt;

&lt;h4 id=&quot;질적변수&quot;&gt;질적변수&lt;/h4&gt;

&lt;p&gt;쉽게 말해 범주를 말한다. ({남자, 여자}, {소득 상, 중, 하} 등등) 이 경우 범주 class의 갯수(남여의 경우 2, 소득의 경우 3)에서 &lt;strong&gt;1을 뺀&lt;/strong&gt; 각각의 변수(더미변수)를 만들어서 적합한다.&lt;/p&gt;

&lt;p&gt;변수는 해당 class에 속하면 1, 아니면 0인 값을 넣는식으로 즉 true냐 false냐를 나타내는 변수를 만든다.&lt;/p&gt;

&lt;p&gt;책의 예를 들어 credit card balance를 예측하기 위한 독립변수로 {인종 아시아인, 백인, 아프리카인}이 있다면, 이런 식의 더미 변수를 만들어준다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181409-0dcdd61c-fdb9-11e7-9267-8c515c3f37e8.PNG&quot; alt=&quot;dummy-var&quot; /&gt;&lt;/p&gt;

&lt;p&gt;즉 [아시아인 인지 아닌지], [백인 인지 아닌지]를 나타내는 변수를 만든것. 3개가 아닌 2개의 변수를 만든 이유는 두개의 변수가 모두 0이면 필연적으로 3번째 class를 의미하는것이기도 하고, 사실 필연적으로 그렇기에 3번째 변수를 넣으면 변수간에 &lt;strong&gt;완벽한 함수관계&lt;/strong&gt;가 생겨버려 문제가 생긴다. (matrix연산에서 inverse matrix가 아예 안만들어 진다.)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;matrix 연산에서 정규방정식은 X’X의 inverse를 구해야 한다. 그러나 rank(X’X)=rank(X)인데 X가 오나벽한 함수관계를 포함하고 있으면&lt;/p&gt;

  &lt;p&gt;(X는 애초에 정방이 아니니 inverse matrix에 대해선 논할 수 없다.)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이 경우 위의 더미 변수들은 {0,1}의 값만을 가질 수 있기에, 결과적으로 각 범주에 따른 3개의 함수선이 나오게 된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181408-0d831e42-fdb9-11e7-8e7e-f2e7cc2ce3ab.PNG&quot; alt=&quot;dummy-var2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이때 맨 오른쪽 식을 보면 알 수 있듯이 &lt;script type=&quot;math/tex&quot;&gt;\beta_{2}&lt;/script&gt;는 백인과 아프리카인의 평균 credit balance의 차이를 의미하게 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Q. 왜 &lt;script type=&quot;math/tex&quot;&gt;x_{i1}=(1,2,3)&lt;/script&gt;의 형태로 안 만들까?&lt;/p&gt;

  &lt;p&gt;A. 그 경우 true, false를 나타내는 0,1아니라 ‘숫자’의 의미가 들어가 버려, 각 범주의 차, 예를 들어 E(아시아인)-E(백인)=E(백인)-E(아프리카인) 등의 명확한 관계를 이미 가정해버리게 된다. 이는 더미변수가 0,1 값을 가지는 이유. 같은 맥락에서 범주가 2개, 즉 더미변수가 한개뿐이라면 0,1이 아니어도 된다. 어차피 선2개일 것이기에, &lt;script type=&quot;math/tex&quot;&gt;\beta_{i1}&lt;/script&gt;가 우리의 coding에 맞게 잘 조절되어 나온다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;이 경우도 각 회귀계수가 0인지를 p-value를 통해 보며 실제 저 분류가 분석에 유의미한지를 볼 수 있는데, 범주가 2개 이상이어서 &lt;strong&gt;더미변수가 여러개인 경우 개별 p-value가 아닌 &lt;script type=&quot;math/tex&quot;&gt;H_{0} : \beta_{1}=\beta{2}=0&lt;/script&gt; 식의 F검정&lt;/strong&gt;을 해야 한다(!)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Q. 왜 개별 검정을 하면 안될까? 몇개의 변수, 예를 들어 1,2,3,4,5개의 클래스의 코딩을 (1,0,0,0), (0,1,0,0), (0,0,1,0), (0,0,0,1)과 같이 했을때, 그 중에 2개만을 취하고 나머진 ‘그 외의 클래스’로 분류해버리면 되는거 아닌가?&lt;/p&gt;

  &lt;p&gt;이는 모델의 적합에선 맞는 말이고, 3장에서 나왓던 계수의 검정에는 오류가 있다.&lt;/p&gt;

  &lt;p&gt;모델의 적합에서는 앞의 1,2 클래스만을 취했을때 (1,0,0,0), (0,1,0,0) 나머지는 자동으로 ‘그외의 클래스’를 의미하여 적합되게 된다.&lt;/p&gt;

  &lt;p&gt;그러나 계수의 검정에서 계수는 1,2,3,4클래스의 5번클래스(base를 5번으로 잡고적합한 경우)와의 평균차이를 의미하는 계수들인데 1,2,그외의 클래스로 적합할 경우 &lt;strong&gt;‘그외의 클래스’와 1,2클래스의 차이를 나타내도록 계산된게 아니라서&lt;/strong&gt; 계수들의 &lt;strong&gt;수치 자체&lt;/strong&gt;가 달라져야하기 때문에, 하나씩 검정하면 안된다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;선형-모델의-확장&quot;&gt;선형 모델의 확장&lt;/h4&gt;

&lt;p&gt;선형 모델의 가장 중요한 가정 2개. 1)additive : 각각의 예측변수(X)들은 서로 독립이다 2) linear : 선형&lt;/p&gt;

&lt;h5 id=&quot;additive&quot;&gt;additive&lt;/h5&gt;

&lt;p&gt;선형 모델은 하나의 &lt;script type=&quot;math/tex&quot;&gt;X_{i}&lt;/script&gt;증가로 인한 Y의 변화는 다른 &lt;script type=&quot;math/tex&quot;&gt;X_{j}&lt;/script&gt;에 관계없이 상수라고 가정하지만, 그러지 않을때도 있다. TV와 radio에 동시에 투자 했을때 시너지로 인해 sale이 각각 그만큼 투자한 것의 합보다 더 많이 증가하는 경우. 이를 통계에선 &lt;strong&gt;상호작용 효과&lt;/strong&gt;라고 한다. 대표적으로 이런 그림.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181410-0e137ae6-fdb9-11e7-8e87-1f3560c5c9c5.PNG&quot; alt=&quot;graph-multi2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이 경우 상호작용을 인정하고, &lt;strong&gt;상호 작용항&lt;/strong&gt;을 넣어준다.&lt;/p&gt;

&lt;p&gt;기존 모델 &lt;script type=&quot;math/tex&quot;&gt;Y=\beta_{0}+\beta_{1}X_{1}+\beta_{2}X_{2}+\epsilon&lt;/script&gt;에서 상화작용항을 넣으면&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;Y=\beta_{0}+\beta_{1}X_{1}+\beta_{2}X_{2}+\beta_{3}X_{1}X_{2}+\epsilon&lt;/script&gt; 이렇게 바뀐다.&lt;/p&gt;

&lt;p&gt;아주 간단하지만, 이 경우 &lt;script type=&quot;math/tex&quot;&gt;X_{1}&lt;/script&gt;의 한단위 증가로 인한 Y의 변동은 더이상 상수&lt;script type=&quot;math/tex&quot;&gt;\beta_{1}&lt;/script&gt;이 아니다. 이는 다음과 같이 나타내면 더 이해하기 편하다&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;Y=\beta_{0}+(\beta_{1}+\beta_{3}X_{2})X_{1}+\beta_{2}X_{2}+\epsilon&lt;/script&gt;

&lt;p&gt;이 경우 &lt;script type=&quot;math/tex&quot;&gt;X_{1}&lt;/script&gt;의 한단위 증가로 인한 Y의 변동은 &lt;script type=&quot;math/tex&quot;&gt;(\beta_{1}+\beta_{3}X_{2})&lt;/script&gt;로, &lt;script type=&quot;math/tex&quot;&gt;X_{2}&lt;/script&gt;에 따라서 변동하게 되었다. &lt;script type=&quot;math/tex&quot;&gt;X_{2}&lt;/script&gt;에 대한 경우도 반대로 똑같이 이해하면 된다. &lt;script type=&quot;math/tex&quot;&gt;\beta_{3}&lt;/script&gt;역시 p-value를 계산하여 상호작용항이 유의한지 안한지를 판단한다. 이 경우 main항(예시에선 TV, Radio)중 하나는 유의하지 않은데 상호작용항(TV * Radio)이 유의하다 나오는 경우가 있을 수 있는데, &lt;strong&gt;계층적 구조 원칙(archical principle)&lt;/strong&gt;에 따라 &lt;strong&gt;p-value가 유의하지 않더라도&lt;/strong&gt; 관련된 모든항을 모델에 포함한다. &lt;script type=&quot;math/tex&quot;&gt;X_{1}X_{2}&lt;/script&gt;자체가 &lt;script type=&quot;math/tex&quot;&gt;X_{1}&lt;/script&gt;과 연관되어 있기에, 이들을 빼는건 의도한 의미를 왜곡하게 된다(!).&lt;/p&gt;

&lt;p&gt;상호작용항은 질적변수*양적변수의 경우도 그대로 작용한다. 질적변수만 있을때는 기울기는 동일하고 절편이 다른 여러개의 직선이었지만(왼쪽 그림), 상호작용항이 있으면 ‘기울기도 다른’여러개의 직선이 나오게 된다. (오른쪽 그림)&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181407-0d3e34e4-fdb9-11e7-9ca2-75308c0ae60a.PNG&quot; alt=&quot;inter-dummy&quot; /&gt;&lt;/p&gt;

&lt;h5 id=&quot;linear&quot;&gt;linear&lt;/h5&gt;

&lt;p&gt;선형성에 대한 가정을 덜어내는것은 다항회귀(polynomial regression)를 통해 이루어 진다. 쉽게 말해 &lt;script type=&quot;math/tex&quot;&gt;x^2, x^3&lt;/script&gt;등도 고려하는 것이다. 다음 장에서 이에 대해 좀더 다룰 것이다.&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181406-0d0a1f4c-fdb9-11e7-9298-7b5878c900d4.PNG&quot; alt=&quot;mpg&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이를 보면 우선, 1차 선형은 잘 안맞는 것을 알 수 있다.&lt;/p&gt;

&lt;p&gt;2차 다항 회귀의 식은 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;mpg=\beta_{0}+\beta_{1}*horsepower+\beta_{2}*horsepower^2+\epsilon&lt;/script&gt;

&lt;p&gt;그러나 이 경우도 &lt;script type=&quot;math/tex&quot;&gt;horsepower^2&lt;/script&gt;를 &lt;script type=&quot;math/tex&quot;&gt;X_{2}&lt;/script&gt;처럼 생각하고, 기존의 선형회귀 처럼 적합하면 된다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Q. 여기서 들었던 의문. 회귀분석에서 변수간 correlate관계, 즉 선형관계는 문제가 되는데, 만약 완벽한 비선형관계, 즉 &lt;script type=&quot;math/tex&quot;&gt;x_2=sin(X_1)&lt;/script&gt;같이 한 변수로 다른 변수가 완벽하게 설명이 되는 경우는 괜찮은건가?&lt;/p&gt;

  &lt;p&gt;A. 독립 변수가 파라미터 벡터 β에 대해서만 선형이기만 하면 여전히 선형 모델이라 부른다. 대표적으로 X와 X^2항도 완벽한 비선형관계를 모델링한 경우. 따라서 완벽한 비선형관계 자체는  ‘colinearity가정’을 위반하지 않는다.&lt;/p&gt;

  &lt;p&gt;그러나 예상할 수 있듯이, &lt;script type=&quot;math/tex&quot;&gt;X&lt;/script&gt;와 &lt;script type=&quot;math/tex&quot;&gt;X^2&lt;/script&gt; 등은 어느정도의 상관관계(선형관계)를 갖는 경우가 많다. 이 경우 다중공선성이 생겨  정규방정식에서 X’X행렬의 역행렬을 구할경우 계산상 문제가 생길 수 잇어, 중심화된 예측변수를 사용한다. 중심화된 예측변수는 다중공선성을 상당히 줄여주는 경우가 많다(p312) (자릿수버림오차에 영향으로, &lt;strong&gt;정규방정식 계산에서 다중공산성이 존재하면 표준화, 혹은 중심화를 해주는 것이 좋다&lt;/strong&gt;.(p303).) 상호작용항들 역시 그들의 추가로 인해 몇몇 예측변수, 또는상호작용항들간에 높은 다중공선성이 잇을 수 있는데, 이때 계산적 정확성을 개선시키기 위해 예측변수의 중심화가 이용된다(p329)&lt;/p&gt;

  &lt;p&gt;정리하자면, &lt;strong&gt;완벽한 비선형관계 자체는  ‘colinearity가정’을 위반하지 않는다&lt;/strong&gt;. 그러나 상관계수, 즉 선형성을 어느정도 가질 위험이 있기에 계산을 용이하게 하기 위해 &lt;strong&gt;중심화 변수가 주로 이용된다.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4 id=&quot;진단&quot;&gt;진단(!)&lt;/h4&gt;

&lt;p&gt;진단의 주요과제는 다음과 같다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;반응변수가 선형이 아닐 수도 있을것.&lt;/li&gt;
  &lt;li&gt;error term이 독립이 아니라 correlated되어 있을 수 있을것.&lt;/li&gt;
  &lt;li&gt;error term이 등분산이 아닐수도 있을것.&lt;/li&gt;
  &lt;li&gt;outlier가 있을수도 있을것&lt;/li&gt;
  &lt;li&gt;High-leverage point가 잇을수도 있을것&lt;/li&gt;
  &lt;li&gt;collinearity가 잇을수도 잇을것&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;여기에선 선형회귀가 최종목적이 아니기에 간단하게만 다루고 넘어간다.&lt;/p&gt;

&lt;h5 id=&quot;1-반응변수가-선형이-아닐-수도-있을것&quot;&gt;1. 반응변수가 선형이 아닐 수도 있을것.&lt;/h5&gt;

&lt;p&gt;선형이라 가정했는데 선형이 아니면..도루묵이 된다. 이를 판단하기 위해선 ‘잔차그림’이 쓰인다. 잔차 (&lt;script type=&quot;math/tex&quot;&gt;e_{i}=y_{i}-\hat y_{i}&lt;/script&gt;)  와 &lt;script type=&quot;math/tex&quot;&gt;y_{i}&lt;/script&gt;에 대한 그림을 그리는 식이다.&lt;/p&gt;

&lt;p&gt;잔차 그림은 우리의 가정 하에서 특별한 패턴 없이 random하게 분포되어 있어야 하는데, U자형 같이 특정한 패턴이 뚜렷하게 보이면 우리의 가정을 수정할 만한 근거가 될 수 있다. non-linear가 의심될 경우 대표적으로 &lt;script type=&quot;math/tex&quot;&gt;\sqrt {X}, X^2&lt;/script&gt;등의 변형을 취해준다. (뒷장에서 더 다룸)&lt;/p&gt;

&lt;h5 id=&quot;2-error-term이-독립이-아니라-correlated되어-있을-수-있을것&quot;&gt;2. error term이 독립이 아니라 correlated되어 있을 수 있을것.&lt;/h5&gt;

&lt;p&gt;우리의 가정은 모든 X수준에서의 error term &lt;script type=&quot;math/tex&quot;&gt;\epsilon_{1},\epsilon_{2},...,\epsilon_{n}&lt;/script&gt;이 서로 uncorrelate되어 있다는것. 즉 &lt;script type=&quot;math/tex&quot;&gt;\epsilon_{i-1}&lt;/script&gt;이 양수가 나오던 음수가 나오던 얼마던지 관계 없이 &lt;script type=&quot;math/tex&quot;&gt;\epsilon_{i}&lt;/script&gt;는 자유롭게 등장한다는 것이다. 만약 실제 error term이 correlated되어 있다면 우리의 추정에 사용되는 표준편차(standard error)를 &lt;strong&gt;더 작게 추정&lt;/strong&gt;하게 된다. 이는 신뢰구간 등에 큰 영향을 미치게 된다.&lt;/p&gt;

&lt;p&gt;극단적인 예로 같은 데이터를 실수로 2번 집어넣게 되면, (각점에 대해 완벽하게 correlated된 점이 1쌍씩 있게됨) 추정된 회귀계수는 동일하나 standard error는 &lt;script type=&quot;math/tex&quot;&gt;\sqrt{(n-2)}&lt;/script&gt;에서 &lt;script type=&quot;math/tex&quot;&gt;\sqrt{(2n-2)}&lt;/script&gt;으로 바뀌기 때문에 작게 추정 되게 된다.(!)&lt;/p&gt;

&lt;p&gt;그러나 time series data등에서는 빈번하게 error term이 correlated되어 있다. 이를 보기 위해선 역시나 잔차그림이 활용된다. time에 따른 잔차를 그려보는 것&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181405-0cd260fc-fdb9-11e7-9506-215322ea3eab.PNG&quot; alt=&quot;time-series&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위 그림을 보면 random하게 지그재그로 분포되어 있는 경우와 시간에 따라 일정한 선이 있는 아래그림이 있다. time series가 아니더라도, &lt;strong&gt;같은 가족에게서 자료가 나온 경우, 같은 생활환경의 사람에서 자료가 수집된 경우&lt;/strong&gt; 등 correlated된 경우가 있을 수 있다. error의 uncorrelation은 선형회귀의 중요한 가정이기에, timeseries를 다루기 위한 여러 방법들이 고안 되었다. 사실 timeseries의 특성에 적합한 모델이 따로 있으므로, 이 경우 회귀분석은 지양한다.&lt;/p&gt;

&lt;h5 id=&quot;3-error-term이-등분산이-아닐수도-있을것&quot;&gt;3. error term이 등분산이 아닐수도 있을것&lt;/h5&gt;

&lt;p&gt;모든 X수준에서의 error term &lt;script type=&quot;math/tex&quot;&gt;\epsilon_{1},\epsilon_{2},...,\epsilon_{n}&lt;/script&gt;은 &lt;script type=&quot;math/tex&quot;&gt;Var(\epsilon_{i})=\sigma^2&lt;/script&gt;라고 가정하였다. 그러나 실제에서는 잔차그림을 그려보면 일정한 범위 내에서 random하게 분포하는게 아니라(이상적인 잔차) 나팔모양으로 퍼져나가는 등 ‘이분산성’을 띄는 경우가 있다. 이 경우 다른 통계방법을 쓰기도 하고, 선형회귀를 유지하는 방안으로는 Y에 대해 변환을 해주는 것으로 &lt;script type=&quot;math/tex&quot;&gt;logY, \sqrt Y&lt;/script&gt;등의 방법이 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181404-0c454032-fdb9-11e7-8c3e-423e436854e2.PNG&quot; alt=&quot;non-equal&quot; /&gt;&lt;/p&gt;

&lt;p&gt;혹은, 자료에 대한 추가적인 정보가 있으면 &lt;strong&gt;weighted least squares&lt;/strong&gt;(머지???추가적으로 찾아보자)를 할 수도 있다. 예를 들어 i수준에서 자료가 &lt;script type=&quot;math/tex&quot;&gt;n_{i}&lt;/script&gt;개 있다면 &lt;script type=&quot;math/tex&quot;&gt;\sigma_{i}^2=\sigma/n_{i}&lt;/script&gt;로 가중치를 줘서 계산하는 형식이다.&lt;/p&gt;

&lt;h5 id=&quot;4-outlier가-있을수도-잇을것--5-high-leverage-point가-잇을수도-있을것&quot;&gt;4. outlier가 있을수도 잇을것. + 5. High-leverage point가 잇을수도 있을것&lt;/h5&gt;

&lt;p&gt;이 둘의 개념이 헷갈릴 수 있는데, outlier는 &lt;strong&gt;종속변수(Y)가 멀리 떨어져 있는 경우이고&lt;/strong&gt;, high-leverage point는 &lt;strong&gt;독립변수(X)가 동떨어져 있는 경우&lt;/strong&gt;이다.(!) (더 깊이 알고싶다면 &lt;a href=&quot;https://onlinecourses.science.psu.edu/stat501/node/337&quot;&gt;여기&lt;/a&gt;) 둘다 좋은건 아닌데, high -leverage point이 더욱 우리의 예측한 선에 상당한 영향을 주는 점이다. 동떨어진 y보다 동떨어진 x가 오히려 예측 선에 큰 영향을 끼치는데, x에 대해 점이 ‘단 하나’ 밖에 없기에 우리의 예측 선이 그 점을 지나가려 노력하기 때문이다. (그래서 지렛대 점이라고 한다) 물론 outlier면서 high leverage point 경우도 많다. 걔네는 우리 예측선에 엄청 영향을 미침.&lt;/p&gt;

&lt;p&gt;비록 예측한 선의 회귀계수 자체에 영향을 못주었다 하더라도, outlier는 MSE에 영향을 미쳐 신뢰구간 등 분석에 영향을 미치게 된다. 분석자는 따라서 outlier가 왜 생겼는지(잘못된 데이터인지, 미처 파악못한 흐름인지) 등을 생각하고 모델에 포함할지 제외할지 결정해야 한다. outlier의 파악에도 잔차그림이 쓰이는데, 얼마나 벗어난것인지를 판단하기 위해 단순 잔차그림이 아닌 &lt;script type=&quot;math/tex&quot;&gt;e_{i}&lt;/script&gt;를 &lt;script type=&quot;math/tex&quot;&gt;SE[e_{i}]&lt;/script&gt;로 나눈 studentized residual이 사용되기도 한다.&lt;/p&gt;

&lt;p&gt;그러나 젤 중요한건 high-leverage point인데 우리의 예측에 엄청나게 영향을 미치기 때문, 이는 변수가1개, 2개일때는 찾기 쉬우나 다중회귀로 가면 눈으로는 볼 수 없다. (그림은 변수가 2개일 경우. 각각 한변수의 관점에서 보았을때는 벗어나는 점을 잡을 수 없다는 것에 주의)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181403-0bf8746e-fdb9-11e7-9b22-ec6fe7f2cb1d.PNG&quot; alt=&quot;high-lev&quot; /&gt;&lt;/p&gt;

&lt;p&gt;따라서 각 관측값의 leverage를 판단하는 통계량이 따로 있다.&lt;/p&gt;

&lt;p&gt;(단순선형회귀의 경우)&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;h_{j}=\frac{1}{n}+\frac{(x_{j}-\bar x)^2}{\sum (x_{i}-\bar x)^2}&lt;/script&gt;

&lt;p&gt;식에서도 x값들의 평균에서 멀리 떨어질 수록 high leverage가 된다는 것을 볼 수 있다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;(다중선형회귀의 경우)&lt;/p&gt;

  &lt;script type=&quot;math/tex; mode=display&quot;&gt;h_{ii}=\begin{pmatrix}H\end{pmatrix}_{ii}&lt;/script&gt;

  &lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;H=X (X^TX)^{-1} X^T&lt;/script&gt; 역시나 계산해보면 single경우와 같아진다&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h5 id=&quot;6-collinearity가-잇을수도-잇을것&quot;&gt;6. collinearity가 잇을수도 잇을것&lt;/h5&gt;

&lt;p&gt;collinearity는 두 변수, 혹은 ‘두개 이상’의 변수가 서로 밀접한 &lt;strong&gt;선형관계&lt;/strong&gt;가 있는것. 만약 X1과 X2가 거의 1:1로 연결이 되어있다면, 이 경우 Y변수에 대한 &lt;strong&gt;해당 변화가 X1에서 온것인지 X2에서 온것인지&lt;/strong&gt; 제대로 알 수 없게되고, 이는 b1, b2에 대한 신뢰계수의 문제로 확장된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181402-0bae37a0-fdb9-11e7-9edc-a2c5db094fe9.PNG&quot; alt=&quot;contour-collinear&quot; /&gt;&lt;/p&gt;

&lt;p&gt;예시 설명은 않고, Limit 과 Rating이 거의 완벽한 선형결합이다는 것만.  위 그림은 Limit과 Age에 대해 적합한것과 Limit과 rating에 대해 적합한 것인데, 여러 회귀계수들에 대해 같은 SSE를 기준으로 등고선을 그린것 이다. 왼쪽 그림의 경우 최저점(least square로 구한 회귀계수)을 중심으로 원만하게 둥글어 자료의 se를 고려해도 어느정도 자신이 있다 할 수 있지만, 오른쪽 그림은 least square에서 조금만 벗어나도 SSE가 천차 만별이어서, &lt;strong&gt;데이터가 조금만 변동(변화)해도 least square점이 천차 만별로 바뀌게 될 것&lt;/strong&gt;임을 예상할 수 있다. 이는 회귀계수 &lt;script type=&quot;math/tex&quot;&gt;\beta_{j}&lt;/script&gt;에 대한 표준편차가 커짐을 의미하고, 이는 &lt;script type=&quot;math/tex&quot;&gt;H_{0}:\beta_{j}=0&lt;/script&gt;을 제대로 기각할 수 없다, 즉 검정의 power가 떨어짐을 의미한다.&lt;/p&gt;

&lt;p&gt;이를 방지하기 위해 collinearity를 측정하고자 하는데, 1) 상관행렬을 본다. 그러나 이 방법은 여러개의 변수가 동시에 correlated된 경우를 잡아내지 못해서 2)VIF(다중 공산성)을 체크한다. VIF는 &lt;strong&gt;선형관계가 완벽하게 없을때 최소 1&lt;/strong&gt;이다. 실제 분석에서는 &lt;strong&gt;5~10을 넘으면 문제가 있다고 본다&lt;/strong&gt;. 심각한 다중공산성을 감지한 경우 1) 단순히 한 변수를 버리거나, 2) 두 변수의 표준화된 값의 평균을 넣는 등 collinear 변수를 결합하는 방식을 택한다.&lt;/p&gt;

&lt;h3 id=&quot;3-4-knnk-nearest-neighborsregression-과의-비교&quot;&gt;3. 4 KNN(K-Nearest Neighbors)regression 과의 비교&lt;/h3&gt;

&lt;p&gt;linear regression은 모수적 방법이다. 앞 장에서도 설명했지만, 모수적(parametric) 방법의 경우 가정된 틀 안의 parameter를 추정하는것으로 문제가 단순화되어 더욱 수월하다는 장점이 있다. 그러나 역시나 가정된 함수가 틀릴경우 도루묵이라는 위험이 있다.&lt;/p&gt;

&lt;p&gt;반대로 비모수적 방법은 특정한 가정을 하지 않고 유연한 적합을 하는 것이다. &lt;strong&gt;대표적인 비모수적 방법이  KNN regression&lt;/strong&gt;이다. 앞장에서 KNN classifier를 설명했었는데, 이와 근본이 같다. 정해진 상수 K에서, 예측변수 &lt;script type=&quot;math/tex&quot;&gt;x_{0}&lt;/script&gt;이 주어지면 가지고 있는 데이터에서 가장 가까운 K개의 데이터를 살펴본다. 그리곤 단순히 그들의 Y값을 평균내어 예측을 하는 것이다. 식으로 나타내면 다음과 같다. (&lt;script type=&quot;math/tex&quot;&gt;N_{0}&lt;/script&gt;이 K개의 점이다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181401-0b695c48-fdb9-11e7-9c3a-0a185692a7a1.PNG&quot; alt=&quot;KNN-reg&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181400-0b30540c-fdb9-11e7-8cfe-0a04d0f5615b.PNG&quot; alt=&quot;KNN-reg2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위 그림은 각각 K=1개, K=9개로 설정한 KNN regression이다. K=1일때는 각 공간에서 주어진 데이터를 완전히 반영하는 계단형식이고(high Var, low bias), K가 커지면 좀더 많은 데이터를 보며 곡선형태(low Var, high bias)가 되어간다. 앞장에서도 말했듯이, 최적의 K개 설정은 bias-variance trade-off에 따라 &lt;strong&gt;그때그때 다르다&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;당연한 얘기지만, 실제 함수가 linear에 가까울땐 linear regression이 더 좋다. 비모수방식의 유연성은 linear를 정확하게 예측하기 힘들다. 비모수 방식은 그자체로 variance가 큰 방식이기에 K를 늘린다 해도 linear regression만큼의 low Var를 만족할 수 없기 때문.&lt;/p&gt;

&lt;p&gt;그러나 놀랍게도 실제 함수가 linear가 아닐때에도, &lt;strong&gt;다중회귀&lt;/strong&gt;에 들어가면 &lt;strong&gt;linear regression이 KNN보다 더 좋은 결과를 낸다.(!)&lt;/strong&gt; 다음의 그림은 변수갯수 p가 1부터 점점 증가함에 따른 linear regression의 test MSE(회색 점선)과 KNN regression의 여러 flexibility에 따른 test MSE(초록색 곡선)이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/35181399-0afcee32-fdb9-11e7-9d2b-8d9ffc500b2f.PNG&quot; alt=&quot;knn-compare&quot; /&gt;&lt;/p&gt;

&lt;p&gt;차원이 2,3차원일때는 KNN이 더 뛰어나지만 차원이 올라갈수록 linear regression은 거의 변화가 없고 KNN은 점점 성능이 눈에 띄게 떨어지게 된다.&lt;/p&gt;

&lt;p&gt;이는 유명한 &lt;strong&gt;‘차원의 저주(!)’&lt;/strong&gt;라는 문제때문이다. 우리개 100개의 training data를 가지고 있을때, p=1, 즉 Y변수까지 해서 2차원일때는 주변 neighbor를 보고 판단할 충분한 자료가 있다. 그러나 차원이 p=20, 즉 21차원이 되버리면, 정확한 판단을 할만한 충분한 비슷한 neighbor 자체가 없어지는 것이다. 즉, 고차원에서는 input &lt;script type=&quot;math/tex&quot;&gt;x_{0}&lt;/script&gt;에서 가장 가까운 K개들이 멀리 떨어져 있는 점들 밖에 없는 것이다. &lt;strong&gt;쉽게 말하자면&lt;/strong&gt; (키: 178, 성별 :남자)인 데이터는 비슷한 near neighbor 데이터가 많겠지만  (키: 178, 성별 :남자, 나이:26, 취미:기타, 수입:300만, 학력:고졸….)인 데이터는 비슷한 near neighbor자체가 없다는 것이다. 이는 결국 KNN의 정확도를 눈에 띄게 떨어뜨리는 결과를 가져온다. 그밖에 linear regression은 해석력이 좋다는 장점 역시 강점으로 작용한다.&lt;/p&gt;
</description>
        <pubDate>Sat, 20 Jan 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/20/ISL-linear-regression_ch3.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/20/ISL-linear-regression_ch3.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[NLP] Character-level Convolutional Networks for Text Classification 논문 리뷰</title>
        <description>&lt;p&gt;char-CNN논문 리뷰&lt;/p&gt;

&lt;p&gt;https://arxiv.org/abs/1509.01626&lt;/p&gt;

&lt;h3 id=&quot;abstract&quot;&gt;Abstract&lt;/h3&gt;

&lt;p&gt;이 논문은 Character-level convolutional networks을 다양한 데이터셋에 시도해보았고 성능을 비교해보았다. 비교 대상은 전통적인 모델인 bag of words, n-grams, 그들의 TF-IDF버젼, 그리고 딥러닝 모델인 RNN, word-based CNN이었고, 비교 결과상당한 성능을 보였다.&lt;/p&gt;

&lt;h3 id=&quot;1-introduction&quot;&gt;1. Introduction&lt;/h3&gt;

&lt;p&gt;text classification 이란? nlp의 전통적인 topic중 하나로 자연어가 미리 지정된 category중 어디에 속할지를 맞추는 것이다. 현재까지는 n-grams과 같은 순서가 있는 단어의 조합을 다루는 등의 ‘단어 단위’의 기술들이 활용되고 있고, 또 성능이 뛰어났다.&lt;/p&gt;

&lt;p&gt;기존의 연구들이 CNN이 언어에 대한 사전 정보 없이도 임베딩된 단어들에 잘 적용될 수 있음을 보여주었다. 그러나 여기에선 text를 철자단위로 다루어 CNN을 시도해보았다. 기존에도 character-level n-gram이나 단어 단위로 CNN을 한 후 철자 단위로 특징을 뽑는 등 철자단위의 nlp 작업들이 있었으나 철자단위에 바로 CNN을 적용한것은 처음시도이다.&lt;/p&gt;

&lt;p&gt;철자 단위의 CNN은, 모든 단어구조는 철자단위로 되어있을 것이기에 &lt;strong&gt;1)&lt;/strong&gt; 단어가 segmentation이 가능한지에 관계없이(tokenize에 대한 어려움을 얘기하는듯) 작동할 수 있고 &lt;strong&gt;2)&lt;/strong&gt; 오타나 이모티콘등과 같은 비정상적인 철자에 대해서도 자연스럽게 배울수 있다는 강점이 있다.&lt;/p&gt;

&lt;h3 id=&quot;2-character-level-convolutional-networks&quot;&gt;2 Character-level Convolutional Networks&lt;/h3&gt;

&lt;h4 id=&quot;21-key-modules&quot;&gt;2.1 Key Modules&lt;/h4&gt;

&lt;p&gt;주된 구성은 1-D input, 즉 1차원 벡터에 대한 1-D convolution과 똑같다. input g(x)와 사이즈가 k, stride가 d인 kernel function f(x)와 convolution h(x)가 있다고 하면&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;h(y)=\sum _{x=1}^{n} [f(x)\cdot g(d \cdot(y-1)+k-(x-1))]&lt;/script&gt;으로 식으로 쓸 수 있는데, 그냥 우리가 알고 있는 1-D CNN…..저기서 &lt;script type=&quot;math/tex&quot;&gt;f \cdot g&lt;/script&gt;는 내적이 아니라 element wise곱을 의미. 그냥 우리가 알고 있는 filter개념…이미지에서 처럼 filter를 여러개 만들어 여러 output $h_{j}$를 만들수 있다.&lt;/p&gt;

&lt;p&gt;여기에 더 깊은 모델을 위한 max-pooling을 해준다. max-pooling외의 방식을 쓴 ConvNets의 경우 6개 이상을 쌓는데 실패했다 한다.&lt;/p&gt;

&lt;p&gt;non-linearity로는 ReLU를 사용 (&lt;script type=&quot;math/tex&quot;&gt;h(x)=max\left\{0,x\right\}&lt;/script&gt;), SGD를 사용.&lt;/p&gt;

&lt;h4 id=&quot;22-character-quantization&quot;&gt;2.2 Character quantization&lt;/h4&gt;

&lt;p&gt;모델의 input으로는 encoding된 알파벳이 들어온다. encoding은 one-hot encoding을 한다.&lt;/p&gt;

&lt;p&gt;모델에서 사용한 ‘철자’로는(alphabet이 굳이a,b,c,d의 개념이 아니었다.) 알파벳 26개, 10개의 숫자, 33개의 다른 부호들(-,;.!?등등)로 총 70개의 character가 있고, 이외의 빈칸을 포함한 ‘철자’가 아닌 것은 zero vector로 처리한다. 논문의 후에 알파벳의 대소문자를 구분한 모델과 비교해볼것이다.&lt;/p&gt;

&lt;h4 id=&quot;23-model-design&quot;&gt;2.3 Model Design&lt;/h4&gt;

&lt;p&gt;large feature와 small feature로 2개의 ConvNet을 구성했고, 모두 6개의 conv layer와 3개의 fully-connected layer가 있다. 3개의 fc 사이에는 정규화를 위해 2개의 dropout이 있고 dropout의 확률은 0.5이다. filter의 stride는 1, pooling은 non-overlapping을 하였으므로 stride는 3.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34938407-28412a9e-f9e0-11e7-858d-441410fe76ca.PNG&quot; alt=&quot;char-cnn-table&quot; /&gt;&lt;/p&gt;

&lt;p&gt;large feature와 small feature는 filter가 몇개의 feature를 잡아낼지를 설정한것, 즉 filter의 수라고 이해하였다(맞나요???)&lt;/p&gt;

&lt;p&gt;이후 6번째 layer를 통해 나온 output을 다음과 같은 output unit을 가진 FC에 넣는다. 마지막 output unit은 문제에 따라 다르다(ex. 목표가 10개의 class로 classification이면 10개의 output unit올 설정)&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34938408-289e1966-f9e0-11e7-9f33-47fe38b04892.PNG&quot; alt=&quot;char-cnn-table2&quot; /&gt;&lt;/p&gt;

&lt;h4 id=&quot;24-data-augmentation-using-thesaurus&quot;&gt;2.4 Data Augmentation using Thesaurus&lt;/h4&gt;

&lt;p&gt;이전의 연구에서 딥러닝 모델을 돌릴때 적절한 data augmentation을 통해 모델이 가져야 하는 invariance property를 가지게 되면(data에 국한되지 않은 general property)  generalization에 성능이 좋다고 밝혀냈다.  텍스트에서는 철자들이 엄격한 순서와 의미를 가지고 있기에ㄹ 이미지처리에서와 같이 signal을 바로 변환해줄 수는 없다. 텍스트 augmentation의 제일 좋은 방법은 사람이 rephrase하는 것이지만, 이는 현실적으로 불가능하다.(data augmentation이란? 쉽게 말해 model을 좀더 robust하게 만들기 위해 같은 데이터에 다양한 변화를 약간씩 주는것. 자세한 이해는 &lt;a href=&quot;http://nmhkahn.github.io/CNN-Practice&quot;&gt;여기&lt;/a&gt;) 따라서 대부분은 그 단어나 구절을 유의어(synonyms)로 바꾸는 형식의 data augmentation을 하였다.&lt;/p&gt;

&lt;p&gt;유의어는 온라인 영어사전인 English thesaurus에서 가져왔다. 여기에는 여러 유의어가 많이 쓰이는 순으로 정렬되어 제시되는데, 몇개의 단어를 바꿀것인지 또 몇번째 순위의 유의어로 바꿀것인지는 각각 0.5확률의 기하분포를 따르게 하였다.&lt;/p&gt;

&lt;h3 id=&quot;3-comparison-models&quot;&gt;3. Comparison Models&lt;/h3&gt;

&lt;h4 id=&quot;31-traditional-methods&quot;&gt;3.1 Traditional Methods&lt;/h4&gt;

&lt;p&gt;전통적인 방법으로는 multinomial logistic regression이 쓰였다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Bag-of-words and its TF-IDF : 상위 빈도 50000개의 단어들을 가지고 출현수를 단어의 feature로한 bag-of-words와 출현수 대신 TF-IDF로 한 모델. 여기서 IDF는 train set의 전체 sample중 해당 단어를 가지고 있는 sample로 계산.&lt;/li&gt;
  &lt;li&gt;Bag-of-ngrams and its TF-IDF : 5-grams 까지 중 가장 frequent한 n-gram 500,000개. TF-IDF는 동일한 과정&lt;/li&gt;
  &lt;li&gt;Bag-of-means on word embedding : train data에 word2vec을 사용한 것에 k-means clustering을 하여, 분류하는것. 5회이상 출현한 모든 단어를 고려하였고 embedding의 demension은 300이었다. 각 bag-of-means(cluster를 말하는듯)의 평균 feature는 count로 하였는데, 5000이 평균이었다.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;32-deep-learning-methods&quot;&gt;3.2 Deep Learning Methods&lt;/h4&gt;

&lt;p&gt;딥러닝의 비교대상으로는 word-based CNN과 LSTM을 하였다.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;word-based CNN : pretrained word representation(word2vec과 lookup table)을 사용했고 embedding size는 똑같이 300이다.(lookup table은 미리 있는 값으로 각 특정값을 매칭해주는 표인듯. 영상처리에 쓰인다. &lt;a href=&quot;http://terms.naver.com/entry.nhn?docId=839052&amp;amp;cid=42344&amp;amp;categoryId=42344&quot;&gt;참고&lt;/a&gt;) 비교를 위해 char-CNN과 레이어 수나 output size는 같다.&lt;/li&gt;
  &lt;li&gt;LSTM : 역시 word-based이고 pretrained word2vec으로 300차원 embedding.  이 모델은 모든 LSTM cell에서 나온 값을 평균내어 feature vector로 삼고, 이를 가지고 multinomial logistic regression을 하였다.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;부가적으로 알파벳 대/소문자를 구분해보았는데, 이는 대체로 성능이 더 좋지 않았다. 아마도 대/소문자에 semantic 차이가 없었기에 regularization으로써 기능을 하지 않았나 추측한다.&lt;/p&gt;

&lt;h3 id=&quot;4-large-scale-datasets-and-results&quot;&gt;4. Large-scale Datasets and Results&lt;/h3&gt;

&lt;p&gt;text data중에는 CNN의 성능을 확인할만한 large-scale datasets 이 없었기에 여기저기서 따와서 만들었다.&lt;/p&gt;

&lt;p&gt;거기에는 news article(내용과 topic label), DBPedia, Yelp review(리뷰 내용과 별몇개인지, 혹은 호1~불호4-즉 2개의 dataset을 여기서 구함) Yahoo! (질문과 답 내용, label) Amazon review (yelp과 같이 review와 별점, 호1~불호4)가 쓰임. &lt;strong&gt;데이터의 양&lt;/strong&gt;은 뒤로갈 수록 방대함.(large-scale일 수록 CNN이 잘할것!) 여러가지 모델들의 최종 성능은 다음과 같다.&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34938406-281004c8-f9e0-11e7-9885-02a3715c27ed.PNG&quot; alt=&quot;char-cnn-result&quot; /&gt;&lt;/p&gt;

&lt;p&gt;파랑이 best, 빨강이 worst&lt;/p&gt;

&lt;h3 id=&quot;5-discussion&quot;&gt;5. Discussion&lt;/h3&gt;

&lt;p&gt;아래 그림은 각 method별, 각 주제별 Char-CNN과의 오류율 차이%로 나타낸것. (양의 방향으로 막대가 간게 Char-CNN이 잘한것)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34938409-29fa6882-f9e0-11e7-87f8-57351116e194.PNG&quot; alt=&quot;char-cnn-graph&quot; /&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Character-level ConvNet is an effective method: word를 찾을 필요 없다는 점에서, 언어 데이터를 다른 데이터와 같은 방식으로 다룰 수 잇다는 강점이 잇다.&lt;/li&gt;
  &lt;li&gt;Dataset size에 따라 데이터 사이즈가 작을때에는 n-gram TFIDF가 여전히 잘했다. 그러나 데이터 scale이 많아질수록 char-CNN이 잘했다.&lt;/li&gt;
  &lt;li&gt;ConvNets may work well for user-generated data : Amazon같이 curated 되지 않은 user-generated text (신경쓰지 않은, 막 쓴, 정도의 의미)에서 char-CNN이 더 잘 작동하였다. 이는 현실문제에 더 작용될 가능성을 의미하지만, 논문에서 추가적인 실험은 하지 않았기에 확신하지 못함.&lt;/li&gt;
  &lt;li&gt;알파벳 대/소를 구분한것이 데이터 양이 많을수록 더 잘 못했는데, 아마 regularzation effect가 아닌가 ‘추측’한다.&lt;/li&gt;
  &lt;li&gt;semantic 분류를 할것인지(아마존과 yelp), 주제 분류를 할것인지(다른 데이터들)의 차이에 따른 성능은 크게 차이가 없었다.&lt;/li&gt;
  &lt;li&gt;Bag-of-means is a misuse of word2vec : word2vec을 단순 분포로 삼아 classification을 하는것은 잘못된 활용인거같다. 결과가 넘 안좋다.&lt;/li&gt;
  &lt;li&gt;There is no free lunch : 모든 경우에 뛰어난 방법은 없었다. 우리 결과를 보고 적용에 참고해라&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;6-conclusion-and-outlook&quot;&gt;6. Conclusion and Outlook&lt;/h3&gt;

&lt;p&gt;Char-CNN은 효과가 있다. 그러나 데이터셋 크기, 어떤 철자를 고를것 등에 따라 차이가 있을것이다.&lt;/p&gt;

</description>
        <pubDate>Mon, 15 Jan 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/01/15/Char-cnn_paper_review.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/01/15/Char-cnn_paper_review.html</guid>
        
        <category>Deep Learning</category>
        
        <category>NLP</category>
        
        
        <category>딥러닝</category>
        
      </item>
    
      <item>
        <title>[stats385] Back Propagation 이해</title>
        <description>&lt;p&gt;node by node로 본것과 matrix form으로 본것. 정리 및 스스로의 이해를 위한 부가설명.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;기본적인-neural-net-구조&quot;&gt;기본적인 neural net 구조&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34932678-b6c46bec-f9cb-11e7-99d2-6ee84e5cefea.PNG&quot; alt=&quot;ann-one&quot; /&gt;&lt;/p&gt;

&lt;p&gt;하나의 hidden layer가 있는 경우.  이 중 맨위의 계산에 대한 수식만을 본것. (notation 써 있는 위치)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;$a_{i}$: input layer에서 온 node ‘하나’.  그림에선 2개가 있다.&lt;/p&gt;

  &lt;p&gt;$w_{ij}$: $a_{i}$에 곱해지는 weight 중 첫번째 요소. 그림에선 6개가 있으나 여기에서는 맨 위의 계산과정만을 따라가고 있다. (1x2와 2x3의 matrix)&lt;/p&gt;

  &lt;p&gt;$z_{j}$: input layer&lt;script type=&quot;math/tex&quot;&gt;_{i}&lt;/script&gt;에서 온 input에 weight을 element wise곱을 해서 합친 값에 bias &lt;script type=&quot;math/tex&quot;&gt;b_{j}&lt;/script&gt;를 더한값.&lt;/p&gt;

  &lt;p&gt;$g_{j}$: input에 weight과 bias를 계산해준 최종값($z_{j}$)에 씌워주는 non-linear function. ReLU나 sigmoid 등등. 이 최종 값이 새로운 input$_{j}$으로써 활용된다.&lt;/p&gt;

  &lt;p&gt;$w_{jk}$: $a_{j}$에 곱해지는 weight 중 첫번째 요소. 그림에선 3개가 있다. (1x3와 3x1의 matrix)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;따라서 ${i}$레이어에서 나와서 ${j}$ hidden layer를 거쳐 최종 ${k}$ layer의 output $a_{k}$가 나오는 과정을 식으로 나타내면 다음과 같다.&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34932680-b6f461e4-f9cb-11e7-8c20-49c75370ad96.PNG&quot; alt=&quot;back-prop1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;식을 보면 알 수 있지만 당연히 최종 output $a_{k}$에는 $i$ 레이어에서 계산되었던 값들과 $j$ hidden layer에서 계산되었던 값들이 마치 재귀함수처럼 다 숨어 있다.&lt;/p&gt;

&lt;p&gt;우리의 목표는 최종 output $a_{k}$가 우리의 target, (답이라고도 할 수 있는) $t_{k}$와 차이가 많이 나지 않도록 하는 것이다.&lt;/p&gt;

&lt;p&gt;최종 target과 우리의 output의 차이, 즉 error를 계산하는 방법은 여러가지가 있는데, 가장 대표적으로 다음의 식이 쓰인다.  (notation이 헷갈릴 수 있는데, ${k} \in K$는 최종 layer에 있는 output들을 모두 말한 것이다. 여기선 2개의 output이 있다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+E+%26%3D%26+%5Cfrac%7B1%7D%7B2%7D+%5Csum_%7Bk+%5Cin+K%7D%28a_k+-+t_k%29%5E2+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} E &amp;amp;=&amp;amp; \frac{1}{2} \sum_{k \in K}(a_k - t_k)^2 \end{array}}&quot; /&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34932670-b4ecb96e-f9cb-11e7-925e-5338057adfc2.PNG&quot; alt=&quot;loss-func&quot; /&gt;&lt;/p&gt;

&lt;p&gt;neural net을 학습시키는 것의 가장 큰 부분은 위의 error를 minimize하는 parameter의 세트 &lt;script type=&quot;math/tex&quot;&gt;\theta = \left\{ \boldsymbol{W} ,\mathbf{b} \right\}&lt;/script&gt; 를 찾아내는 것이다. (W,b가 bold체인것을 명심. 모든 parameter를 포함하는 notation이다)&lt;/p&gt;

&lt;p&gt;이 문제는 nn의 핵심개념인 gradient descent를 이용하여 푸는데, 즉 $\theta$의 모든 parameter에 대해 $\frac{\partial E}{\partial \theta}$를 구하고(gradient를 구하고), &lt;img src=&quot;https://s0.wp.com/latex.php?latex=w_%7Bjk%7D%5Cleftarrow+w_%7Bjk%7D+-+%5Ceta+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bjk%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;w_{jk}\leftarrow w_{jk} - \eta \frac{\partial E }{\partial w_{jk}}&quot; /&gt;이런 식으로 그 방향으로 parameter를 조금씩 조정(descent)해주는 것이다. ($\eta$는 learning rate)&lt;/p&gt;

&lt;h2 id=&quot;back-propagation-이해&quot;&gt;back propagation 이해&lt;/h2&gt;

&lt;p&gt;$\frac{\partial E}{\partial \theta}$, 즉 error에 미치는 각 parameter의 영향은&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+E+%26%3D%26+%5Cfrac%7B1%7D%7B2%7D+%5Csum_%7Bk+%5Cin+K%7D%28a_k+-+t_k%29%5E2+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} E &amp;amp;=&amp;amp; \frac{1}{2} \sum_{k \in K}(a_k - t_k)^2 \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;error의 식에 직접적으로 관여하는 $a_{k}$를 계산하는데 사용된 마지막 Weight (그림에선 $w_{jk}$)&lt;/li&gt;
  &lt;li&gt;최종 output $a_{k}$속에 숨어 있어 좀더 간접적으로 작용하는 이전의 수많은 Weight들 (그림에선 $w_{ij}$)가 있다.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;1-output-layer-weights&quot;&gt;1. output layer weights&lt;/h3&gt;

&lt;p&gt;우선 좀더 직관적인 마지막 레이어에 있는 weight의 gradient부터 살펴보자. 즉, $\frac{\partial E}{\partial W_{jk}}$를 계산해보자.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bjk%7D%7D+%26%3D%26+%5Cfrac%7B1%7D%7B2%7D+%5Csum_%7Bk+%5Cin+K%7D%28a_k+-+t_k%29%5E2+%5C%5C++%26%3D%26+%28a_k+-+t_k%29%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+w_%7Bjk%7D%7D%28a_k+-+t_k%29+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial w_{jk}} &amp;amp;=&amp;amp; \frac{1}{2} \sum_{k \in K}(a_k - t_k)^2 \  &amp;amp;=&amp;amp; (a_k - t_k)\frac{\partial}{\partial w_{jk}}(a_k - t_k) \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;여기에서, 그리고 다음 여러 수식에는 간단한 chain rule이 쓰인다. chain rule은 간단하게 다음과 같이 나타낼 수 있다. (아시는분은 스킵)&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;- Chain Rule -&lt;/strong&gt;&lt;/p&gt;

  &lt;p&gt;$\frac{\partial f(some func)}{\partial x}$을 구할때&lt;/p&gt;

  &lt;p&gt;$somefunc=A$로 치환해주고&lt;/p&gt;

  &lt;p&gt;$\frac{\partial f(some func)}{\partial x}=\frac{\partial f(A)}{\partial A}*\frac{\partial A}{\partial x}$의 형태로 단순화해서 구하는 것이다. (수식은 더 길어졌지만 실제 계산은 더 편하다)&lt;/p&gt;

  &lt;p&gt;예를 들어보자 $\frac{\partial f(x)}{\partial x}$가 아닌 $\frac{\partial f(x^2)}{\partial x}$를 구할때,&lt;/p&gt;

  &lt;p&gt;$\frac{\partial f(x^2))}{\partial x}=\frac{\partial f(A)}{\partial A}*\frac{\partial x^2}{\partial x}$&lt;/p&gt;

  &lt;p&gt;​             $=f^{‘}(A)*2$으로 푸는 것이다.&lt;/p&gt;

  &lt;p&gt;물론 $f(x^2)$를 다 전개해서 $x$에 대해 미분해도 되지만 somefunc이 복잡해질 수록 chain rule로 구하는게 계산이 더 수월하다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;다시 돌아와서 &lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bjk%7D%7D+%26%3D%26+%5Cfrac%7B1%7D%7B2%7D+%5Csum_%7Bk+%5Cin+K%7D%28a_k+-+t_k%29%5E2+%5C%5C++%26%3D%26+%28a_k+-+t_k%29%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+w_%7Bjk%7D%7D%28a_k+-+t_k%29+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial w_{jk}} &amp;amp;=&amp;amp; \frac{1}{2} \sum_{k \in K}(a_k - t_k)^2 \  &amp;amp;=&amp;amp; (a_k - t_k)\frac{\partial}{\partial w_{jk}}(a_k - t_k) \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;해당 식에서 summation기호가 사라진것은 마지막 layer의 계산에서 여러 weight가 곱해지지고 그 값을 더한거지만 $\partial w_{jk}$를 하면 남는 것은 $w_{jk}$가 관여한 식밖에 없기 때문이다. 또 $t_{k}$는 상수이고 $a_{k}=g(z_{k})$이므로&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bjk%7D%7D+%26%3D%26+%28a_k+-+t_k%29%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+w_%7Bjk%7D%7Da_k+%5C%5C++%26%3D%26+%28a_k+-+t_k%29%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+w_%7Bjk%7D%7Dg_k%28z_k%29+%5C%5C++%26%3D%26+%28a_k+-+t_k%29g_k%27%28z_k%29%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+w_%7Bjk%7D%7Dz_k%2C+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl}\frac{\partial E }{\partial w_{jk}} &amp;amp;=&amp;amp; (a_k - t_k)\frac{\partial}{\partial w_{jk}}a_k \  &amp;amp;=&amp;amp; (a_k - t_k)\frac{\partial}{\partial w_{jk}}g_k(z_k) \  &amp;amp;=&amp;amp; (a_k - t_k)g_k'(z_k)\frac{\partial}{\partial w_{jk}}z_k, \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이다. (마지막 줄에서 다시 chain rule이 쓰였다.) 이제 $\frac{\partial z_{k}}{\partial {W}_{jk}}$만 구하면 되는데  &lt;img src=&quot;https://s0.wp.com/latex.php?latex=z_k+%3D+b_j+%2B+%5Csum_j+g_j%28z_j%29w_%7Bjk%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;z_k = b_j + \sum_j g_j(z_j)w_{jk}&quot; /&gt; 이고 따라서 &lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5Cfrac%7B%5Cpartial+z_%7Bk%7D%7D%7B%5Cpartial+w_%7Bjk%7D%7D+%3D+g_j%28z_j%29+%3D+a_j&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\frac{\partial z_{k}}{\partial w_{jk}} = g_j(z_j) = a_j&quot; /&gt;, 이므로 최종적으로 정리된 식은&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bjk%7D%7D+%26%3D%26+%28a_k+-+t_k%29g_k%27%28z_k%29a_j+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial w_{jk}} &amp;amp;=&amp;amp; (a_k - t_k)g_k'(z_k)a_j \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이 중 k, 즉 마지막 레이어와 연관된 계산을 모두 $\delta_{k}$묶으면&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cdelta_k+%26%3D%26+%28a_k+-+t_k%29g_k%27%28z_k%29%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \delta_k &amp;amp;=&amp;amp; (a_k - t_k)g_k'(z_k)\end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bjk%7D%7D+%3D+%5Cdelta_k+a_j+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial w_{jk}} = \delta_k a_j \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;으로 최종 정리할 수 있다. 여기서 $\delta_{k}$는 마지막 non-linear function을 back-propagation한 것이다. 어렵당..원문(
Here the $\delta_{k}$terms can be interpreted as the network output error after being back-propagated through the output activation function, thus creating an error “signal”. Loosely speaking, Equation (5) can be interpreted as determining how much each $w_{jk}$ contributes to the error signal by weighting the error signal by the magnitude of the output activation from the previous (hidden) layer associated with each weight )&lt;/p&gt;

&lt;p&gt;덤으로 output layer bias $b_{k}$는 위의 계산과정에서 &lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+b_k%7D+z_k+%3D+%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+b_k%7D+%5Cleft%5B+b_k+%2B+%5Csum_j+g_j%28z_j%29%5Cright%5D+%3D+1&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\frac{\partial}{\partial b_k} z_k = \frac{\partial}{\partial b_k} \left[ b_k + \sum_j g_j(z_j)\right] = 1&quot; /&gt; 이므로&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+b_k%7D+%26%3D%26+%28a_k+-+t_k%29g_k%27%28z_k%29%281%29+%5C%5C++%26%3D%26+%5Cdelta_k+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial b_k} &amp;amp;=&amp;amp; (a_k - t_k)g_k'(z_k)(1) \  &amp;amp;=&amp;amp; \delta_k \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이다. 직관적으로 bias는 이전 layer들에서 온 값들과 관계없이 마지막에 더해지는 거니까, $k$번째 layer의 계산들하고만 연관이 있다는것을 확인할 수 있다.&lt;/p&gt;

&lt;h3 id=&quot;2-gradients-for-hidden-layer-weights&quot;&gt;2. Gradients for Hidden Layer Weights&lt;/h3&gt;

&lt;p&gt;앞부분은 다 똑같다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bij%7D%7D%26%3D%26%5Cfrac%7B1%7D%7B2%7D+%5Csum_%7Bk+%5Cin+K%7D%28a_k+-+t_k%29%5E2+%5C%5C++%26%3D%26+%5Csum_%7Bk+%5Cin+K%7D+%28a_k+-+t_k%29+%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+w_%7Bij%7D%7Da_k++%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial w_{ij}}&amp;amp;=&amp;amp;\frac{1}{2} \sum_{k \in K}(a_k - t_k)^2 \  &amp;amp;=&amp;amp; \sum_{k \in K} (a_k - t_k) \frac{\partial}{\partial w_{ij}}a_k  \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;summation이 여기서 사라지지 않은것에 유의! 왜냐면 이전 layer에서 온 weight는 모든 hidden layer$j$의 node를 계산하는데 쓰였기에 미분해도 모두 남아있다. 다시 $a_{k}=g_{k}(z_{k})$이므로&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bij%7D%7D%26%3D%26+%5Csum_%7Bk+%5Cin+K%7D+%28a_k+-+t_k%29+%5Cfrac%7B%5Cpartial+%7D%7B%5Cpartial+w_%7Bij%7D%7Dg_k%28z_k%29+%5C%5C++%26%3D%26+%5Csum_%7Bk+%5Cin+K%7D+%28a_k+-+t_k%29g%27_k%28z_k%29%5Cfrac%7B%5Cpartial+%7D%7B%5Cpartial+w_%7Bij%7D%7Dz_k++%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial w_{ij}}&amp;amp;=&amp;amp; \sum_{k \in K} (a_k - t_k) \frac{\partial }{\partial w_{ij}}g_k(z_k) \  &amp;amp;=&amp;amp; \sum_{k \in K} (a_k - t_k)g'_k(z_k)\frac{\partial }{\partial w_{ij}}z_k  \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;여기까진 거의 똑같은 계산과정이다. 근데 $z_{k}$는 $w_{jk}$와 직접적으로 관계를 맺고 있고 $w_{ij}$는 해당 식 안에서 간접적으로 관계를 맺고 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+z_k+%26%3D%26+b_k+%2B+%5Csum_j+a_jw_%7Bjk%7D+%5C%5C++%26%3D%26+b_k+%2B+%5Csum_j+g_j%28z_j%29w_%7Bjk%7D+%5C%5C++%26%3D%26+b_k+%2B+%5Csum_j+g_j%28b_i+%2B+%5Csum_i+z_i+w_%7Bij%7D%29w_%7Bjk%7D%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} z_k &amp;amp;=&amp;amp; b_k + \sum_j a_jw_{jk} \  &amp;amp;=&amp;amp; b_k + \sum_j g_j(z_j)w_{jk} \  &amp;amp;=&amp;amp; b_k + \sum_j g_j(b_i + \sum_i z_i w_{ij})w_{jk}\end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;고로 다시한번 chain rule을 써줘야 한다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+z_k+%7D%7B%5Cpartial+w_%7Bij%7D%7D+%26%3D%26+%5Cfrac%7B%5Cpartial+z_k%7D%7B%5Cpartial+a_j%7D%5Cfrac%7B%5Cpartial+a_j%7D%7B%5Cpartial+w_%7Bij%7D%7D+%5C%5C++%26%3D%26+%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+a_j%7Da_jw_%7Bjk%7D%5Cfrac%7B%5Cpartial+a_j%7D%7B%5Cpartial+w_%7Bij%7D%7D+%5C%5C++%26%3D%26+w_%7Bjk%7D%5Cfrac%7B%5Cpartial+a_j%7D%7B%5Cpartial+w_%7Bij%7D%7D+%5C%5C++%26%3D%26+w_%7Bjk%7D%5Cfrac%7B%5Cpartial+g_j%28z_j%29%7D%7B%5Cpartial+w_%7Bij%7D%7D+%5C%5C++%26%3D%26+w_%7Bjk%7Dg_j%27%28z_j%29%5Cfrac%7B%5Cpartial+z_j%7D%7B%5Cpartial+w_%7Bij%7D%7D+%5C%5C++%26%3D%26+w_%7Bjk%7Dg_j%27%28z_j%29%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+w_%7Bij%7D%7D%28b_i+%2B+%5Csum_i+a_i+w_%7Bij%7D%29+%5C%5C++%26%3D%26+w_%7Bjk%7Dg_j%27%28z_j%29a_i+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial z_k }{\partial w_{ij}} &amp;amp;=&amp;amp; \frac{\partial z_k}{\partial a_j}\frac{\partial a_j}{\partial w_{ij}} \  &amp;amp;=&amp;amp; \frac{\partial}{\partial a_j}a_jw_{jk}\frac{\partial a_j}{\partial w_{ij}} \  &amp;amp;=&amp;amp; w_{jk}\frac{\partial a_j}{\partial w_{ij}} \  &amp;amp;=&amp;amp; w_{jk}\frac{\partial g_j(z_j)}{\partial w_{ij}} \  &amp;amp;=&amp;amp; w_{jk}g_j'(z_j)\frac{\partial z_j}{\partial w_{ij}} \  &amp;amp;=&amp;amp; w_{jk}g_j'(z_j)\frac{\partial}{\partial w_{ij}}(b_i + \sum_i a_i w_{ij}) \  &amp;amp;=&amp;amp; w_{jk}g_j'(z_j)a_i \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;따라서 최종값은&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bij%7D%7D%26%3D%26+%5Csum_%7Bk+%5Cin+K%7D+%28a_k+-+t_k%29g%27_k%28z_k%29w_%7Bjk%7D+g%27_j%28z_j%29a_i+%5C%5C++%26%3D%26+g%27_j%28z_j%29a_i+%5Csum_%7Bk+%5Cin+K%7D+%28a_k+-+t_k%29g%27_k%28z_k%29w_%7Bjk%7D+%5C%5C++%26%3D%26+a_i+g%27_j%28z_j%29+%5Csum_%7Bk+%5Cin+K%7D+%5Cdelta_k+w_%7Bjk%7D+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial w_{ij}}&amp;amp;=&amp;amp; \sum_{k \in K} (a_k - t_k)g'_k(z_k)w_{jk} g'_j(z_j)a_i \  &amp;amp;=&amp;amp; g'_j(z_j)a_i \sum_{k \in K} (a_k - t_k)g'_k(z_k)w_{jk} \  &amp;amp;=&amp;amp; a_i g'_j(z_j) \sum_{k \in K} \delta_k w_{jk} \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;여기에 다시 j레이어와 관련된, 즉 j index가 들어간 모든 term을 $\delta_{j}$로 묶어주면&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+w_%7Bij%7D%7D%26%3D%26+a_i+g%27_j%28z_j%29+%5Csum_%7Bk+%5Cin+K%7D+%5Cdelta_k+w_%7Bjk%7D+%5C%5C++%26%3D%26+%5Cdelta_j+a_i+%5C%5C++%5Ctext%7Bwhere%7D+%5C%5C++%5Cdelta_j+%26%3D%26+g%27_j%28z_j%29+%5Csum_%7Bk+%5Cin+K%7D+%5Cdelta_k+w_%7Bjk%7D+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial E }{\partial w_{ij}}&amp;amp;=&amp;amp; a_i g'_j(z_j) \sum_{k \in K} \delta_k w_{jk} \  &amp;amp;=&amp;amp; \delta_j a_i \  \text{where} \  \delta_j &amp;amp;=&amp;amp; g'_j(z_j) \sum_{k \in K} \delta_k w_{jk} \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이는 결국 임의의$l$ 번째 레이어의 weight gradient를 구하고 싶으면 error를 우리의 계산과정을 역으로 미분하고 앞에서 온 input $a_{l-1}$을 곱해주면 된다는것. 이부분 어렵당..원문(
This suggests that in order to calculate the weight gradients at any layer$l$ in an arbitrarily-deep neural network, we simply need to calculate the backpropagated error signal that reaches that layer$\delta_{l}$ and weight it by the feed-forward signal $a_{l-1}$feeding into that layer! )&lt;/p&gt;

&lt;p&gt;덤으로 bias 는 이리 구해진다. 사실, 위의 식$\delta_{j}a_{j}$에서 $a_{j}$부분만 빼주면 된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://s0.wp.com/latex.php?latex=%5CLarge%7B%5Cbegin%7Barray%7D%7Brcl%7D+%5Cfrac%7B%5Cpartial+z_k+%7D%7B%5Cpartial+b_i%7D+%26%3D%26+w_%7Bjk%7Dg_j%27%28z_j%29%5Cfrac%7B%5Cpartial+z_j%7D%7B%5Cpartial+b_i%7D+%5C%5C++%26%3D%26+w_%7Bjk%7Dg_j%27%28z_j%29%5Cfrac%7B%5Cpartial%7D%7B%5Cpartial+b_i%7D%28b_i+%2B+%5Csum_i+a_i+w_%7Bij%7D%29+%5C%5C++%26%3D%26+w_%7Bjk%7Dg_j%27%28z_j%29%281%29%2C+%5C%5C++%5Ctext%7Bgiving%7D+%5C%5C++%5Cfrac%7B%5Cpartial+E+%7D%7B%5Cpartial+b_i%7D%26%3D%26+g%27_j%28z_j%29+%5Csum_%7Bk+%5Cin+K%7D+%5Cdelta_k+w_%7Bjk%7D+%5C%5C++%26%3D%26+%5Cdelta_j+%5Cend%7Barray%7D%7D&amp;amp;bg=ffffff&amp;amp;fg=4e4e4e&amp;amp;s=0&quot; alt=&quot;\Large{\begin{array}{rcl} \frac{\partial z_k }{\partial b_i} &amp;amp;=&amp;amp; w_{jk}g_j'(z_j)\frac{\partial z_j}{\partial b_i} \  &amp;amp;=&amp;amp; w_{jk}g_j'(z_j)\frac{\partial}{\partial b_i}(b_i + \sum_i a_i w_{ij}) \  &amp;amp;=&amp;amp; w_{jk}g_j'(z_j)(1), \  \text{giving} \  \frac{\partial E }{\partial b_i}&amp;amp;=&amp;amp; g'_j(z_j) \sum_{k \in K} \delta_k w_{jk} \  &amp;amp;=&amp;amp; \delta_j \end{array}}&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;matrix-form-backpropagation-이해하기&quot;&gt;Matrix Form Backpropagation 이해하기&lt;/h2&gt;

&lt;p&gt;역시 차원이 많아지면 matrix가 보기에 짱.&lt;/p&gt;

&lt;p&gt;$   Input=x​$, $Output=f(Wx+b)​$은 여전히 유효하다. 아니, 여기서는 bias가 없다. (실제로 빈번히 이렇게 쓰는듯)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/sudeepraja/sudeepraja.github.io/master/images/neuron.PNG&quot; alt=&quot;Neural Network&quot; /&gt;&lt;/p&gt;

&lt;p&gt;식으로 정리하면 (볼드체 안썻지만 모두 상수가 아니다)&lt;/p&gt;

&lt;div style=&quot;text-align:center&quot;&gt;Input=$x_{0}$

Hidden Layer1 output$=x_{1}=f_{1}(W_{1}x_{0})$

Hidden Layer2 output$=x-{2}=f_{2}(W_{2}x_{1})$

Output$=x_{3}=f_{3}(W_{3}x_{2})$&lt;/div&gt;

&lt;p&gt;여기에서도 다음과 같은 식으로 error를 계산한다&lt;/p&gt;

&lt;p&gt;$E=\frac{1}{2}\left|x_{3}-t\right|_{2}^2$ 여기서 subletter2는 유클리드 놈을 의미한다.&lt;/p&gt;

&lt;p&gt;input $x_{0}$을 넣어서 output $x_{3}$이 나왔고, 이를 토대로 $W_{1},W_{2},W_{3}$를 바꿀 것이다.  역시나 같은 방식으로,&lt;/p&gt;

&lt;p&gt;$w=w−α_{w}\frac{∂E}{∂w}$ for all the weights $w$이렇게 구한다.&lt;/p&gt;

&lt;p&gt;이제 $W_{3}$ , 즉 마지막 weight의 gradient 부터 구해보자. 참고로 앞의 그림에서  $W_{3}$의 크기는 (2x3), $x_{2}$의 크기는 (3x1)였다.&lt;/p&gt;

&lt;p&gt;$E=\frac{1}{2}\left|x_{3}-t\right|_{2}^2$   (다시 상기)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34932672-b56698a6-f9cb-11e7-9397-6da352d5da50.PNG&quot; alt=&quot;matix1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;첫줄에서 $t$는 상수이므로 편미분에서 사라지고, 다시 chain rule을 사용해서 결국 이전 layer의 값인 $x_{2}^{T}$만이 남았다. (위 식에서 전치$T$는 matrix 연산의 특징이라 이해하면 된다. 사실 손으로 다 해보면 전치가 붙어야됨을 볼 수 있다. 자세한 내용은 &lt;a href=&quot;https://atmos.washington.edu/~dennis/MatrixCalculus.pdf&quot;&gt;Matrix Calculus&lt;/a&gt;참고. 추가 &lt;a href=&quot;http://taewan.kim/post/backpropagation_matrix_transpose/&quot;&gt;Transpose를 손으로&lt;/a&gt;) 이는 앞에서 node by node로 보았을때와 거의 유사하다.&lt;/p&gt;

&lt;p&gt;여기서 ∘는  Hadamard product라고 단순 내적형태의 행렬곱이 아니라 같은 위치에 있는 원소끼리의 곱을 의미한다.&lt;/p&gt;

&lt;p&gt;다음으로 $W_{2}$에 대해 보자.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34932673-b5a95ede-f9cb-11e7-9651-3fbd30005f19.PNG&quot; alt=&quot;matix2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;세번째 줄까진 $W_{3}$와 똑같으나 $W_{3}x_{2}$가 $W_{2}$로 바로 미분이 안되고 안에 내재되어 있던 계산까지 들어가 미분을 하였다. (node by node에선 여기서 summation기호가 있었으나, 여기선 어차피 matix, 즉 전체를 포함하는 개념이라 summation이 안쓰였다.)&lt;/p&gt;

&lt;p&gt;이제 슬슬 힘듬….이제 마지막 $W_{1}$에 대해 보면&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34932674-b630132a-f9cb-11e7-9c51-e1f4fa585e38.PNG&quot; alt=&quot;matix3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;ㅋㅋ수식이 많이 불친절해졌다. 그러나 $W_{2}$를 계산할때와 마찬가지로 마지막 미분에서 한번더 쪼개서 계산을 하였다는 것은 완전히 동일하다.&lt;/p&gt;

&lt;h3 id=&quot;정리&quot;&gt;정리&lt;/h3&gt;

&lt;p&gt;위의 계산들을 정리해보자면, $L$개의 layer가 있고 그에 따라 L개의 Weight $W_{1},..,W_{L}$과 각각의 non-linear function이 있으면,&lt;/p&gt;

&lt;p&gt;Forward Pass(원 방향 계산)는&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;x_{i}=f_{i}(W_{i}x_{i-1})&lt;/script&gt;

&lt;p&gt;이렇게 이루어 지고, Error는 다음과 같이 계산된다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;E=\frac{1}{2}\left\|x_{L}-t\right\|_{2}^2&lt;/script&gt;

&lt;p&gt;Backward Pass에서는 마지막 layer의 backprop과 그 이전 layer들의 backprop으로 나뉘는데, 요렇다.&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34932675-b6608500-f9cb-11e7-8efc-50dd5b92e2b1.PNG&quot; alt=&quot;matix4&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위에서 정의한 $\delta$들을가지고 요렇게 weight 를 update를 할 수 있다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34932677-b6906c34-f9cb-11e7-8e12-f9c2d53c3e56.PNG&quot; alt=&quot;matix5&quot; /&gt;&lt;/p&gt;

&lt;p&gt;참조: 행렬미분 : https://datascienceschool.net/view-notebook/8595892721714eb68be24727b5323778/&lt;/p&gt;

&lt;p&gt;행렬 back prop: https://sudeepraja.github.io/Neural/&lt;/p&gt;

&lt;p&gt;node back prop: https://theclevermachine.wordpress.com/2014/09/06/derivation-error-backpropagation-gradient-descent-for-neural-networks/&lt;/p&gt;

</description>
        <pubDate>Mon, 15 Jan 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/01/15/Back-Propagation-%EC%9D%B4%ED%95%B4.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%94%A5%EB%9F%AC%EB%8B%9D/2018/01/15/Back-Propagation-%EC%9D%B4%ED%95%B4.html</guid>
        
        <category>Deep Learning</category>
        
        <category>Math</category>
        
        
        <category>딥러닝</category>
        
      </item>
    
      <item>
        <title>[ISL] 2장 - An Overview of Statistical Learning</title>
        <description>&lt;p&gt;첫시간이니 만큼, 아주 기본적이고 개괄적인 내용들부터 시작합니다. 틀린 내용이 있다면 가차없이 처단바랍니다.&lt;/p&gt;

&lt;h2 id=&quot;preface&quot;&gt;preface&lt;/h2&gt;

&lt;p&gt;시작하기에 앞서, 이 책은 ESL(Elementary of Statistical Learning)에서 수정을 통해 나온 책이다. ISL은 데이터 시대에 접어들면서, statistical learning이 학문적 분야를 넘어 각 분야에 적용되고 있는 흐름에 맞추어 변형된 책이다.&lt;/p&gt;

&lt;p&gt;쉽게 말해, 연구자들의 입문서가 아닌 방법을 ‘‘적용’‘하고자 하는 사람들을 위한 입문서이다. 따라서 여러 모델들이 어떻게 구성되어 있고, 어떤 강점이 있는지, 어떤 단점이 있는지, 어떤 상황에 어떤 모델을 적용해야 하는지는 다루고 있지만, 왜 그런 구성이 되었는지에 대한 이론적인 설명은 깊게 들어가지 않으며, 특히 ‘matrix연산’은 상당부분 피하고 있다.&lt;/p&gt;

&lt;p&gt;(추가적인 이론적 배경을 위한 탐구가 필요할것 같다..)&lt;/p&gt;

&lt;h2 id=&quot;간략한-책구성&quot;&gt;간략한 책구성&lt;/h2&gt;

&lt;p&gt;study plan에서도 적어놨지만, 무엇을 공부할것인지, 간략하게 알아보고 가자.&lt;/p&gt;

&lt;p&gt;2과 : statistical learning에 대한 개괄과 기본 개념들을 설명한다. KNN도 간략하게 설명된다&lt;/p&gt;

&lt;p&gt;3,4과 : classical linear model에 대해 다룬다. 구체적으로는 3과에서 linear regression을, 4과에서는 logistic regression을 다룰것이다. (logistic의 경우 &lt;a href=&quot;https://en.wikipedia.org/wiki/Generalized_linear_model&quot;&gt;generalized linear model&lt;/a&gt;에 속한다. 쉽게 말해 로짓(log odds)과 linear관계가 있음)&lt;/p&gt;

&lt;p&gt;5과 : 모델의 성능을 측정하는 방법, cross-validation이나 bootstrap등에 대해 배울 것이다. 교육세션에서 배웠던것과 비슷하다.&lt;/p&gt;

&lt;p&gt;6과 :  linear method에 대해 좀더 배우게 된다. model selection, ridge, lasso등에 대해 다룬다. (드디어!)&lt;/p&gt;

&lt;p&gt;7과 : non-linear method에 대해 다룬다. 난항이 예상된다&lt;/p&gt;

&lt;p&gt;8과 : 인기만점 tree-based model에 대해 다룬다. bagging, boosting, RF등을 다룬다.&lt;/p&gt;

&lt;p&gt;9과: 들어는 봤으나 설명하진 못하는, SVM(support vector machine)에 대해 다룬다.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;시작-statistical-learning이란&quot;&gt;시작! (statistical learning이란?)&lt;/h2&gt;

&lt;p&gt;statistical learning의 가장 일반적인 목표는 x들과 y의 어떠한 ‘관계’가 있을것이라 ‘가정’하고, 이를 밝히는 것이다. 좀 더 구체적으로 말하자면, 우리에게 $ x_{ 1 }, x_{ 2 },.., x_{ p }$, 즉 p개의 input이 주어졌을때, 우리의 목표 $y$ 를 예측하는 것이다.(사실 x와 y의 관계를 ‘추론’하는 것도 아주 큰 분야 중 하나이지만, 여기선 예측에 중점을 둔다.)  이는 수식으로 말하면 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;Y= f(x)&lt;/script&gt;

&lt;p&gt;여기서 $f$는 어떠한 관계든 가능하다.&lt;/p&gt;

&lt;p&gt;대표적으로 어떤 사람의 키($x_{ 1 }$), 성별($x_{ 2}$), 나이($ x_{ 3}$)이 주어졌을때 그 사람의  몸무게($Y$)를 예측하는 식일 것이다. 그러나, 실제 현실에서는 당연히 키와 성별, 나이만 가지고 키를 딱 예측할 수 없다. 수많은 인과관계가 얽혀 있어, 키랑 성별, 나이를 통해 키를 어느정도 짐작할수 있을뿐, 오차가 당연히 있을것이다. 이러한 오차를 포함해주기 위해, 통계학에서는 &lt;em&gt;error term&lt;/em&gt; ‘$\epsilon$’ 을 넣어준다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;Y= f(x) + \epsilon&lt;/script&gt;

&lt;p&gt;여기서 X는 &lt;strong&gt;예측변수, 독립변수, 변수&lt;/strong&gt;(predictors, independent variables,  variables) 등의 이름으로 불리고, 목표인 Y는 &lt;strong&gt;반응변수, 종속변수&lt;/strong&gt;(response or dependent variable) 등으로 불린다.  또 &lt;strong&gt;$\epsilon$ ($error term$)&lt;/strong&gt;은 우리가 고려하지 못한, 혹은 현실의 어떠한 기이한 작용들로 생겼을 만한 수많은 오차들을 다 포함하며, 평균이 0일 것이라고 ‘가정’한다.  $\epsilon$은 우리가 가정한 모델로는 아무리 잘 만들어도 줄일 수 없는, 즉 irreducible error를 의미한다.&lt;/p&gt;

&lt;p&gt;그러나 우리의 가정대로 정말 키와 몸무게가 어떤 관계가 딱 존재한다 하더라도, 우리는 그 $f$를 알 수 없다. 왜? 우리의 정보는 한정적이니까.  고로 우리는 우리가 가진 자료를 가지고 $f$를 ‘추정’하게 된다. 그리고 그 추정된 관계를 가지고 Y를 추정한다. 이때 실재와 우리의 추정을 구분하기 위해 $\hat{f}$ 와 같이 표현한다.  즉 우리가 만들어낼 관계식은 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\hat Y=\hat f(x)&lt;/script&gt;

&lt;h4 id=&quot;그럼-f를-어떻게-추정할까&quot;&gt;그럼, $f$를 어떻게 추정할까?&lt;/h4&gt;

&lt;p&gt;$f$를 추정하는 방법으로는 &lt;strong&gt;parametric 방법&lt;/strong&gt;과 &lt;strong&gt;non-parametric방법&lt;/strong&gt; 이 있는데, parametric방법은 X와 Y간에 특정한 관계(대표적으로 예를 들면 선형관계)가 있다고 미리 가정하고 그 틀에 맞추어 추정을 한 후 이를 다시 우리의 가정과 비교하는 방법이다. 해당 가정 사항의 parameter 몇개만 예측하는 것으로 문제가 축소되고, 무엇보다 해당 가정사항 안에서 많은 분석들과 예측을 할 수 있다는 powerful하다는 강점이 있으나 가정이 틀렸을 경우 분석 자체가 도루묵이라는 위험성이 있다.&lt;/p&gt;

&lt;p&gt;반면 non-parametric 방법은 $f$에 대한 어떤 가정도 없이 데이터만을 보고 데이터의 특성을 잘 나타내는 $f$를 찾는 방법으로, 가정이 틀릴 위험이 없다는 강점이 있으나 기본적으로 많은 데이터를 필요로 하고, parametric 방법 만큼 다양한 분석을 할 수 없다는 약점이 있다. 여기서에서는 parametric 방법에 좀더 집중할 것이다.&lt;/p&gt;

&lt;h4 id=&quot;flexibility에-따른-다양한-model들&quot;&gt;flexibility에 따른 다양한 model들&lt;/h4&gt;

&lt;p&gt;$f$를 추정하는 여러가지 방법들(method들)이 있는데, 이들을 나누는 가장 큰 기준은 그 방법들의 &lt;strong&gt;flexibility&lt;/strong&gt;이다. flexibility란 말그대로 유연성, 즉 우리가 가진 데이터에 얼마나 유연하게 적합하여  $f$를 추정하는가를 의미하는 것이다. 그러나 flexible하다고 다 좋은건 아닌데, flexible하면 할 수록 해석력(Interpretability)를 잃어버리기 때문이다. 다양한 분석 방법들의 flexible, Interpretability간의 관계를 나타낸 그림은 다음과 같다. 해당 방법들은 뒷장에서 다룰것이기에, 자세한 설명은 생략한다.(사실 아직 잘 모른다.)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34830228-262b5be2-f6db-11e7-8fa3-7649ef864dd6.PNG&quot; alt=&quot;flex-inter-tradeoff&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;assessing-model-accuracy&quot;&gt;Assessing Model Accuracy&lt;/h2&gt;

&lt;p&gt;앞에도 말했듯이 하나의 데이터를 다루고자 할때 여러가지 방법들과 모델들이 쓰일수가 있는데, 그럼 그 모델들을 어떻게 평가해야 할까? 우선 첫째로, 우리의 모델이 우리가 가지고 있는 데이터를 얼마나 잘 맞추는가를 볼 수 있다.  회귀문제에서는, 이를 평가하는 지표로 &lt;strong&gt;MSE&lt;/strong&gt;라는 것을 가장 많이 쓴다. MSE의 식은 다음과 같다.&lt;/p&gt;

&lt;p&gt;&lt;script type=&quot;math/tex&quot;&gt;MSE =\frac { 1 }{ n } \sum _{ i=1 }^{ n }({y}_{i} − \hat f({x}_{i}))^2&lt;/script&gt;
$y_{i}$는 i번째 실제 우리가 가지고 있는 데이터고, $\hat f(x_{i})$는 i번째 변수들을 통해 우리가 예측한 y값이다.&lt;/p&gt;

&lt;p&gt;($\hat Y=\hat f(x)$ 이 식을 상기하자) 고로, (((예측한 y값과 실제 y값의 오차)의 제곱)의 평균)을 계산한 지표이다. 그림으로 쉽게 보자면, 아래 그림에서 파란색 선이 우리가 예측한 y값들의 모임, 회색선이 실제값과의 차이이다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34830490-ea5cece2-f6db-11e7-9234-4fd206e010d1.PNG&quot; alt=&quot;linear-regression&quot; /&gt;&lt;/p&gt;

&lt;p&gt;낮은 MSE값은 우리의 모델이 주어진 데이터를 잘 설명하고 있다는 것을 의미한다. MSE는 뒷장에서 여러 방식으로 사용되는 아주 중요한 지표이다. 그러나 이는 모델을 평가하는 지표로써는 아주 일차원적인 지표이다. 왜냐면, 우리는 &lt;strong&gt;주어지지 않은&lt;/strong&gt;자료들을 잘 예측하고 싶은 것이지, &lt;strong&gt;주어진&lt;/strong&gt;자료를 잘 예측하는 것은 우리의 목표가 아니다. 쉬운 예를 들자면, 우리는 지난 6개월간의 주식 데이터를 보고 다음날의 주식의 가격을 알고 싶은 것이지, 일주일 전의 주식 가격을 예측하고 확인하려는게 아니다. 즉, 주어진 $y_{1},..,y_{n}$를 잘 맞추고 싶은게 아니라 아직 접해보지 못한 데이터를 통해 $y_{0}$를 확인하고 싶은 것이다. (여기서 0은 아직 접하지 못한 데이터를 통틀어 말한다.)&lt;/p&gt;

&lt;p&gt;여기서 주어진 자료들은 training data, 훗날 모델을 직접 돌리며 주어질 자료를 test data라고 부른다.&lt;/p&gt;

&lt;p&gt;고로 사실상 모델의 성능은, test data를 얼마나 잘 맞추느냐, 즉 test data에 대한 오차가 적을 수록 좋다고 할 수 있다. test data에 대한 오차는 test MSE라고 말하며 다음과 같이 구할 수 있다.&lt;/p&gt;

&lt;p&gt;$Avg(y_{0}-\hat f(x_{0}))^2$  (다시, 여기서 0은 아직 접하지 못한 데이터를 통틀어 말한다.)&lt;/p&gt;

&lt;p&gt;test data는 아직 주어지지 않은 데이터라는 점에서, 이를 미리 계산하고 낮추기란 쉽지 않다. 이러한 한계를 완화하고자 하는 다양한 트릭들(cross-validation 등등)이 5장에 나올것이다.&lt;/p&gt;

&lt;p&gt;얼핏 보았을때는, 주어진 자료들을 잘 맞추면, 나중에 주어질 자료들도 잘 맞추지 않을까? 라는 생각이 든다. 그러나 여기서, 아주 중요한 개념이 등장한다.&lt;/p&gt;

&lt;h2 id=&quot;bias-variance-trade-off&quot;&gt;Bias-Variance Trade-Off&lt;/h2&gt;

&lt;p&gt;한번쯤은 들어봤을 만한, ML job-interview에도 꼭 등장하는 단골 문제다.&lt;/p&gt;

&lt;p&gt;이 문제의 가장 핵심 개념은, lowest training MSE가 lowest test MSE를 보장하지 못하며, 심지어는 다른 모델들보다 성능이 더 나빠질 수도 있다는 것이다.&lt;/p&gt;

&lt;p&gt;용어를 먼저 정의하자.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Bias : the error that is introduced by approximating a real-life problem. 우리가 $f$를 추정하고자 할때 단순히 각 점들을 잇는 지그재그의 선을 긋지 않고 나름의 모델을 세워 단순화 시켜 예측을 할것이다. 이런 단순화 작업에 필연적으로 동반하며 생기는 오차가 바로 bias이다. 예를 들어 우리가 선형회귀를 적합하고자 한다면, 우리 모델의 ‘선형성’ 으로 인해 필연적으로 오차가 생길 것이다.(‘선형성’이라는 가정은 엄청나게 큰 가정이다.) 이는 어떻게 적합하느냐에 따라 조금씩 그 값이 달라지겠지만, 아무리 잘 적합해도 ‘선형성’으로 인해 줄어들지 않는 오차가 있다. 당연히 &lt;strong&gt;flexible할 수록&lt;/strong&gt;, 즉 덜 단순화시킨 모델일 수록 &lt;strong&gt;bias는 줄어들 것이다&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  &lt;p&gt;처음에는 bias는 잔차인줄 알았는데, 아니었다. 아래의 식에서도 나와 있듯이,  $Bias(\hat f(x))=E(\hat f(x)-f(x))=E(\hat f(x))-f(x)$로 받아들여야 한다. 즉 실제 truth 함수인 ‘$f(x)$’와 우리가 추정한 ‘$\hat f(x)$의 기대값’(무수히 많은 데이터셋에대해 무수히 많은 적합을 시켜보았을때의 생기는 여러 모델들의 평균)과의 ‘차’로 받아들여야 한다.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
  &lt;li&gt;Variance : the amount by which $\hat f$ would change if we estimated it using a different training data set. 즉 우리가 다른 training data set을 사용할때마다 우리가 추정할 $\hat f$가 얼마나 많이 변동할 것인가 이다. 쉽게 말해 데이터에 얼마나 의존적인가이다. &lt;strong&gt;flexible할 수록&lt;/strong&gt;, 모델의 &lt;strong&gt;variance는 늘어날 것이다&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;이론적으로, $Avg(y_{0}-\hat f(x_{0}))^2=Var(\hat f(x_{0}))+[Bias(\hat f(x_{0}))]^2+Var(\epsilon)$ 이라는 식을 도출할 수 있다.&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;$y=f(x)+\epsilon$ 이고, $\epsilon$은 위에서 언급했듯이 해당 모델에서 고려하지 못한 irreducible error이다.&lt;/p&gt;

  &lt;p&gt;$E(\epsilon)=0$, $\therefore$ $E(y)=f(x), Var(y)=Var(\epsilon)$,  $\because$$f(x)$는 unknown fixed function의 한 값, 즉 상수.&lt;/p&gt;

  &lt;p&gt;$Bias(\hat f(x))=E(\hat f(x)-f(x))=E(\hat f(x))-f(x)$&lt;/p&gt;

  &lt;p&gt;$E[{y}-\hat f({x})]^2=E[y^2 -2y\hat f(x)+\hat f(x)^2]$&lt;/p&gt;

  &lt;p&gt;​			$= E(y^2)-2E(y\hat f(x))+E(\hat f(x)^2)$&lt;/p&gt;

  &lt;blockquote&gt;
    &lt;p&gt;$E(y^2)=Var(y)+[E(y)]^2 $    		$(Var(X)=E(X^2)-(E(x))^2)$&lt;/p&gt;

    &lt;p&gt;​	    $= Var(\epsilon)+(f(x))^2$&lt;/p&gt;

    &lt;p&gt;$E(y\hat f(x))=E[(f(x)+\epsilon)*\hat f(x)]$&lt;/p&gt;

    &lt;p&gt;​       		  &lt;script type=&quot;math/tex&quot;&gt;= E[f(x)*\hat f(x)+\epsilon*\hat f(x)]&lt;/script&gt;&lt;/p&gt;

    &lt;p&gt;​		  $=f(x)E(\hat f(x))+E(\epsilon*\hat f(x))$&lt;/p&gt;

    &lt;p&gt;​		 $=f(x)E(\hat f(x))+E(\epsilon)*E(\hat f(x))$, $\because $irreducible error $ \epsilon $와 우리가 추정한 값 $\hat f(x)$은 $indep.$&lt;/p&gt;

    &lt;p&gt;​	 $=f(x)E(\hat f(x))$&lt;/p&gt;

    &lt;p&gt;$E(\hat f(x)^2)=Var(\hat f(x))+[E(\hat f(x))]^2$&lt;/p&gt;
  &lt;/blockquote&gt;

  &lt;p&gt;$\therefore E[{y}-\hat f({x})]^2=E[y^2 -2y\hat f(x)+\hat f(x)^2]= E(y^2)-2E(y\hat f(x))+E(\hat f(x)^2)$&lt;/p&gt;

  &lt;p&gt;​					$=  Var(\epsilon)+(f(x))^2-2[f(x)E(\hat f(x))]+Var(\hat f(x))+[E(\hat f(x))]^2$&lt;/p&gt;

  &lt;p&gt;​					$= Var(\epsilon)+Var(\hat f(x))+[f(x)-E(\hat f(x))]^2$&lt;/p&gt;

  &lt;p&gt;​					$= Var(\epsilon)+Var(\hat f(x))+Bias(\hat f(x))^2$.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;​&lt;/p&gt;

&lt;p&gt;이 중 $Var(\epsilon)$은 우리가 고려하지 못한, irreducible error의 Variance이다.  즉 우리의 목표인 &lt;strong&gt;test MSE를 줄이기 위해서는 모델의 Variance와 Bias를 모두 가능한 낮춰야&lt;/strong&gt; 한다. 그러나, 이는 앞의 설명에서 예상할 수 있듯이 쉽지 않다.&lt;/p&gt;

&lt;p&gt;Bias-Variance Trade-off란, &lt;strong&gt;모델의 flexibility에 따라 bias와 variance는 필연적으로 trade-off 관계에 있다는 것&lt;/strong&gt;을 나타낸다.&lt;/p&gt;

&lt;p&gt;빠른 이해를 위해 그림을 보자.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34830504-fa8ede2c-f6db-11e7-90fc-ac67cef60fe0.PNG&quot; alt=&quot;bias-variance1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위의 왼쪽 그림에서, 하얀색(?검은색?)점은 우리가 관찰한 실제 값들이고, 검은색 선은 실제 X와 Y와의 관계, 즉 $f$이다. (물론 해당 실제 관계는 현실에서는 미리 알 수 없다.) 그리고 황색, 하늘색, 초록색 선들은 각각 다른 flexibility를 가지고 주어진 training data에서 나름의 $f$를 추정한 선들($\hat f$)이다. 황색선이 가장 덜 flexible하고, 하늘색이 중간정도로 flexible하고, 초록색이 가장 많이 flexible하다. 주어진 자료를 가장 잘 설명(혹은 예측)하는 선은 초록색, 즉 주어진 자료에 맞춰서 구불구불하게 꼬은 선일 것이다. (이는 smoothing spline이라는 방법을 통해 그은 선이다. 7장에 나온다.) 그러나 실제의 관계, 즉 검은색선을 가장 잘 예측하는 선은 파란색 선이다.&lt;/p&gt;

&lt;p&gt;이는 오른쪽 그림을 통해 잘 나타나 있는데, 오른쪽 그림에서 U자 곡선은 test MSE, S자 곡선은 training MSE이다. x축은 flexibility를 나타내는 정도를 의미한다.(df에 대해서 어케 해석해야 될까요???) 모델이 flexible해지면 해질수록, 즉 주어진 데이터에 맞추어 꼬불꼬불해지면 해질수록 training MSE는 지속적으로 감소한다. 그러나 test MSE, 즉 우리의 진짜 목표는 처음에는 감소하다가, 어느순간 다시 증가하게 된다. training MSE는 작은데 test MSE는 커지는 이러한 상황은 &lt;strong&gt;overfitting&lt;/strong&gt;이라 부른다&lt;/p&gt;

&lt;p&gt;다시 한번 상기. $Avg(y_{0}-\hat f(x_{0}))^2=Var(\hat f(x_{0}))+[Bias(\hat f(x_{0}))]^2+Var(\epsilon)$&lt;/p&gt;

&lt;p&gt;우리의 목표인 test MSE를 줄이려면, 줄일 수 없는 $Var(\epsilon)$을 제외하고, 우리 모델의 Variance도 가능한 줄어야 하고, Bias도 가능한 줄어야 한다.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;더 flexible한 method를 사용하게 되면 bias는 줄고, variance는 늘어난다&lt;/strong&gt;. 다만, 처음에는 bias가 줄어드는 정도가 variance가 늘어나는 정도보다 더 컸기에, 더욱 flexible한 방법을 사용하는 것이 더 낮은 test MSE를 만들어 내었다. 그러나 어느 시점, 즉 적당한 수준을 넘어 더욱 flexible한 방법을 사용하고자 하면 bias가 줄어드는 정도보다 variance가 늘어나는 정도가 더 크기에, 결과적으로 test MSE는 더 늘어나게 된다.&lt;/p&gt;

&lt;p&gt;그럼, &lt;strong&gt;어느 정도 flexible한게 ‘적당한’ flexibility인가?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;답은 &lt;strong&gt;‘그때그때 다르다’&lt;/strong&gt; 이다.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;만약 실제 truth, 즉 $f$가 선형에 거의 가까운 관계였다면, 아주 약간만 flexible한 방법이 최적의 결과를 가져올 것이다.&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34830505-fae9a1b8-f6db-11e7-9933-c844c94fce25.PNG&quot; alt=&quot;bias-variance2&quot; /&gt;&lt;/li&gt;
  &lt;li&gt;반대로 만약 실제의 $f$가 그 자체로 구불구불한 모양이 ‘truth’라면, 자연스레 더욱 flexible한 모델이 최적의 결과를 가져올 것이다.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34830503-fa24fa34-f6db-11e7-9bd7-f0e4b7c60c7e.PNG&quot; alt=&quot;bias-variance3&quot; /&gt;&lt;/p&gt;

&lt;p&gt;이 처럼, bias와 variance는 trade-off의 관계이고, 어느정도의 수준이 제일 좋은지는 상황에 따라 다르기 때문에, 분석자는 항상 이를 염두하고 어느 모델이 좋을지를 생각해봐야 한다.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;assessing-model-accuracy-at-classification&quot;&gt;Assessing Model Accuracy at Classification&lt;/h2&gt;

&lt;p&gt;앞서서는 회귀, 즉 regression의 경우에 대한 모델 평가방법에 대해 말했다. 그럼 이제 classification의 경우에 대한 모델 평가 방법에 대해 알아보자.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Q. Regression과 Classification의 차이는?&lt;/li&gt;
  &lt;li&gt;A. 간단하다. 반응변수(y)가 양적변수일때는 regression 문제, 반응변수가 질적변수일때는 classification 문제이다.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;p개의 예측변수 $x_{ 1 },x_{ 2 },..,x_{ p }$ 가 있을때 해당 자료가 어느 class에 속할지를 예측하는 것이 classification문제이다. 예를 들면 몸무게, 키가 주어졌을때 해당 사람이 ‘남자’에 속할지, ‘여자’에 속할지를 맞추는 것이다.&lt;/p&gt;

&lt;p&gt;여기서의 평가방법도 위의 MSE와 개념적으로 크게 다르지 않은데, 여기에서는 실제 답, 즉 실제 class에 맞게 분류를 했는지 안했는지를 보고 오류율을 구하면 된다. 이를 식으로 나타내면 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;\frac { 1 }{ n } \sum _{ i=1 }^{ n }I(y_{i} \neq \hat y_{i})&lt;/script&gt;

&lt;p&gt;여기서 $\hat {y}_{i}$는 ‘몇번째 클래스에 속하는지’에 대한 class label이다. $I()$는 indicator function으로, 쉽게 말하자면 안의 조건문이 참이라면 1, 거짓이라면 0을 반환한다고 보면 된다. 따라서 위의 식은 ‘전체 n개중 몇개나 틀리게 label을 부여했는가’를 의미한다 보면 된다.&lt;/p&gt;

&lt;p&gt;역시 여기서도 결국 중요한건 test data에 대한 error rate, 즉 $Avg(I(y_{0} \neq \hat y_{0}))$이다.&lt;/p&gt;

&lt;h2 id=&quot;bayes-classifier&quot;&gt;Bayes Classifier&lt;/h2&gt;

&lt;p&gt;test data에 대한 error rate를 줄이기 위해서는 Bayes Classifier라 불리는 아주 간단한 원리의 classification을 하면 된다.  Bayes Classifier는 $x_{0}$라는 input이 주어졌을때 $Y$가 어느 클래스에 속할지 확률(즉 conditional probability)을 구하고 그 확률이 최대가 되는 class에 분류를 하는 것이다. 이를 식으로 나타내자면 다음과 같다.&lt;/p&gt;

&lt;script type=&quot;math/tex; mode=display&quot;&gt;Pr(Y=j|X=x_{0}),    (j=1,2,...,K)&lt;/script&gt;

&lt;p&gt;총 K개의 클래스가 있을때,  $x_{0}$라는 condition, 즉 조건이 있을때 해당 자료가 1번째 클래스에 속할 확률, 2번째 클래스에 속할 확률,…, 등을 전부 구해, 속할 확률이 가장 큰 클래스에 배정해주면 된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34830553-2523029e-f6dc-11e7-903e-4c5fc6a4e7d0.PNG&quot; alt=&quot;bayes-classifier&quot; /&gt;&lt;/p&gt;

&lt;p&gt;대충 이러한 그림으로 나오는는데, 이는 $x_{1},x_{2}$가 주어지는 경우의 classification이다. 모든 점에 대해 노랑색 클래스에 속할지 파랑색 클래스에 속할지 확률을 구하고 그에 따라 classification해준 것이다. 물론 해당 확률은 그 input일때 해당 클래스에 속하는 경우가 더 많다는 것이다. 특정 input의 경우 100% 한 클래스에 속할수도 있겠지만(그림에서 맨 오른쪽, 혹은 맨 아래의 점들은 모두 파란색이므로 이때의 conditional probability 
&lt;script type=&quot;math/tex&quot;&gt;Pr(Y=파랑|X=x{0})&lt;/script&gt;
는 1이다.) 애초에 모집단의 분포 자체가 섞여 있을 수도 있다(그림에서 정 중앙라인 부분). 그럴 경우 100% 그 클래스에 속하는 것은 아니고, 해당 경우 
&lt;script type=&quot;math/tex&quot;&gt;Pr(Y=파랑|X=x{0})&lt;/script&gt;
는 1보다 작다.&lt;/p&gt;

&lt;h2 id=&quot;knnk-nearest-neighbors&quot;&gt;KNN(K-Nearest Neighbors)&lt;/h2&gt;

&lt;p&gt;그러나 Bayes Classification에서 구하고자 하는 conditional probability는 실제 구하기가 힘들다. 우리는 실제 모집단의 분포를 모르기에, 실제의 conditional probability도 알 수 없기 때문이다. (이는 conditional probability를 구하는 Bayes Theorem에 대한 이해와 부가적인 설명 필요한데, 다소 세부적인 내용이라 판단되어 참조링크만 걸어둔다.  unbiased한 conditional probability를 구하기 위해선 엄청나게 많은 수의 데이터가 필요하기 때문이라는 것. &lt;a href=&quot;https://arxiv.org/abs/1404.0933&quot;&gt;Bayes  and Naive Bayes Classifier&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;이에 따라 우리는 conditional probability를 추정하고자 하는 다양한 방법들을 사용하는데, 가장 대표적인 것이 KNN이다. 여기서 K는 양수인 하나의 숫자인데, input이 들어왔을때 우리의 training data를 기준으로 K-nearest, 즉 K개의 가장 가까운 이웃 데이터를 살펴보고(가까운을 무슨 기준으로 평가할까?=&amp;gt;분석자의 판단. 코사인유사도던  유클리드놈이던) 이를 토대로 conditional probability를 계산하는 것이다. 다시 위의 그림을 기준으로 설명하자면, K=5일 경우 가장 가까운 5개의 데이터를 살펴보고 데이터가 각각 [‘노랑색’, ‘노랑색’,’파랑색’, ‘파랑색’,’파랑색’]클래스 였다면 파랑색 클래스에 속할 것이라 판단하는 것이다.&lt;/p&gt;

&lt;p&gt;K를 몇으로 설정할 것인지에 따라 결과가 천차만별인데, 여기에선 K를 몇으로 하느냐에 따라 위에서 언급한 flexibility의 개념이 결정된다.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34830550-2472b470-f6dc-11e7-8714-907251493a3a.PNG&quot; alt=&quot;KNN&quot; /&gt;&lt;/p&gt;

&lt;p&gt;위의 그림에서 점선은 Bayes Classifier이고 왼쪽 그림은 K=1인 경우의 KNN, 오른쪽은 K=100인경우의 KNN결과 이다.&lt;/p&gt;

&lt;p&gt;K=1일 경우 단 한개의 점만을 보고 판단을 하여 결과적으론  주어진 데이터에 따라 쉽게 변동하는 flexible한 모델이 되고, K=100개일 경우 엄청 많은 데이터를 보고 판단하기에, 매우 variance가 적은 flexibility가 적은 모델이 되서 그림에서 처럼 사실상 직선에 가까운 형태가 된다. (flexibility가 커지면 Variance는 커지고 Bias는 줄어든다는 것을 다시 상기하자.)&lt;/p&gt;

&lt;p&gt;이 경우에도 역시나 Bias-Variance Trade-off의 개념이 적용되며, 아래 그림을 보면 마찬가지로 ‘적당한’수준의 flexibility을 넘을 경우 Test Error는 늘어나는 U자 형태임을 볼 수 있다.&lt;img src=&quot;https://user-images.githubusercontent.com/31824102/34830551-24d023b2-f6dc-11e7-85ed-08f79d537363.PNG&quot; alt=&quot;KNN2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;즉 여기서도 ‘적당한’수준의 flexibility를 찾아 모델을 수립하는 것이 중요한 관건이다. 이 과제를 풀기 위한 다양한 방법들이 논의되고 있는데, 이는 5장에서 다룰 것이다.&lt;/p&gt;

</description>
        <pubDate>Fri, 12 Jan 2018 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/12/ISL-An_Overview_of_Statistical_Learning_ch2.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2018/01/12/ISL-An_Overview_of_Statistical_Learning_ch2.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
      <item>
        <title>[ISL] 1장 - ISL스터디 플랜</title>
        <description>&lt;h2 id=&quot;1개요&quot;&gt;1.개요&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;ML 이론서 중 유명하고, 인기있는 그리고 비교적 입문과정인 이론서로 알고 있습니다. 원래는 ESL(elementary to statistical learning)이 원조이고 좀더 깊은 내용을 다루고 있는 것으로 알고 있는데, 배탈이 나지 않기 위해 물 탄 버전인 ISL부터 함께 공부하고자 합니다&lt;/li&gt;
  &lt;li&gt;따라서 본 스터디는 ISL을 통하여 ML이론에 대해 발을 담궈보는것을 목표로 하고, 최종적으로는 ESL을 함께 공부하며 ML이론에 대한 기반을 탄탄하게 세워보자는데 목표가 있습니다. (방학 내에는 절대 다 못봅니다)&lt;/li&gt;
  &lt;li&gt;R을 통한 단순한 구현(사실 library..)코드가 함께 있는 것으로 알고 있는데, 좀더 intensive하게 나가자면 python을 통해 직접 구현해보는것? 등 세부적인 방향을 논의할 수 있습니다.
    &lt;ol&gt;
      &lt;li&gt;장점: 비교적 입문서 입니다. 수식도 깊게 쓰여져 있지 않고, 초심자를 대상으로 씌여졌습니다(고 들었습니다).&lt;/li&gt;
      &lt;li&gt;단점: ESL의 물탄 버젼 입니다. 제가 알기로 ESL이 원조이고, 해당 저서에서 깊은 부분과 수식을 몇개 쳐내고 쉽게 씌여진게 ISL이라고 합니다. 따라서 ISL-&amp;gt;ESL의 먼 여정을 떠나야 합니다. 그런만큼 속도도 비교적 빠르게 나가기를 희망합니다.&lt;/li&gt;
      &lt;li&gt;단점2 : 물탄버젼임에도 불구하고 어려울 수 있습니다….따라서 빠른 진도로 인해 상당한 노력을 요할 수 있습니다. 또한 발제자가 아니더라도 모두가 해당 부분을 동일하게 공부하고, 충분히 공유한 후 발제가 이뤄지길 희망합니다.&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;2-순서&quot;&gt;2. 순서&lt;/h2&gt;

&lt;p&gt;내용을 참고하기 쉽게, 세부목차까지 가져왔습니다. 총 10chapter입니다.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;PREFACE VII&lt;/p&gt;

  &lt;p&gt;1 INTRODUCTION 1&lt;/p&gt;

  &lt;p&gt;2 STATISTICAL LEARNING 15&lt;/p&gt;

  &lt;p&gt;2.1 WHAT IS STATISTICAL LEARNING? . . . . . . . . . . . . . . . . . 15&lt;/p&gt;

  &lt;p&gt;2.2 ASSESSING MODEL ACCURACY . . . . . . . . . . . . . . . . . . . 29&lt;/p&gt;

  &lt;p&gt;2.3 LAB: INTRODUCTION TO R . . . . . . . . . . . . . . . . . . . . . 42&lt;/p&gt;

  &lt;p&gt;2.4 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52&lt;/p&gt;

  &lt;p&gt;IX&lt;/p&gt;

  &lt;p&gt;X CONTENTS&lt;/p&gt;

  &lt;p&gt;3 LINEAR REGRESSION 59&lt;/p&gt;

  &lt;p&gt;3.1 SIMPLE LINEAR REGRESSION . . . . . . . . . . . . . . . . . . . 61&lt;/p&gt;

  &lt;p&gt;3.2 MULTIPLE LINEAR REGRESSION . . . . . . . . . . . . . . . . . . 71&lt;/p&gt;

  &lt;p&gt;3.3 OTHER CONSIDERATIONS IN THE REGRESSION MODEL . . . . . . . . 82&lt;/p&gt;

  &lt;p&gt;3.4 THE MARKETING PLAN . . . . . . . . . . . . . . . . . . . . . . 102&lt;/p&gt;

  &lt;p&gt;3.5 COMPARISON OF LINEAR REGRESSION WITH K-NEAREST&lt;/p&gt;

  &lt;p&gt;NEIGHBORS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104&lt;/p&gt;

  &lt;p&gt;3.6 LAB: LINEAR REGRESSION . . . . . . . . . . . . . . . . . . . . . 109&lt;/p&gt;

  &lt;p&gt;3.7 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120&lt;/p&gt;

  &lt;p&gt;4 CLASSIFICATION 127&lt;/p&gt;

  &lt;p&gt;4.1 AN OVERVIEW OF CLASSIFICATION . . . . . . . . . . . . . . . . . 128&lt;/p&gt;

  &lt;p&gt;4.2 WHY NOT LINEAR REGRESSION? . . . . . . . . . . . . . . . . . 129&lt;/p&gt;

  &lt;p&gt;4.3 LOGISTIC REGRESSION . . . . . . . . . . . . . . . . . . . . . . . 130&lt;/p&gt;

  &lt;p&gt;4.4 LINEAR DISCRIMINANT ANALYSIS . . . . . . . . . . . . . . . . . 138&lt;/p&gt;

  &lt;p&gt;4.5 A COMPARISON OF CLASSIFICATION METHODS . . . . . . . . . . . 151&lt;/p&gt;

  &lt;p&gt;4.6 LAB: LOGISTIC REGRESSION, LDA, QDA, AND KNN . . . . . . 154&lt;/p&gt;

  &lt;p&gt;4.7 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168&lt;/p&gt;

  &lt;p&gt;5 RESAMPLING METHODS 175&lt;/p&gt;

  &lt;p&gt;5.1 CROSS-VALIDATION . . . . . . . . . . . . . . . . . . . . . . . . 176&lt;/p&gt;

  &lt;p&gt;5.2 THE BOOTSTRAP . . . . . . . . . . . . . . . . . . . . . . . . . 187&lt;/p&gt;

  &lt;p&gt;5.3 LAB: CROSS-VALIDATION AND THE BOOTSTRAP . . . . . . . . . . . 190&lt;/p&gt;

  &lt;p&gt;5.4 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197&lt;/p&gt;

  &lt;p&gt;6 LINEAR MODEL SELECTION AND REGULARIZATION 203&lt;/p&gt;

  &lt;p&gt;6.1 SUBSET SELECTION . . . . . . . . . . . . . . . . . . . . . . . . 205&lt;/p&gt;

  &lt;p&gt;6.2 SHRINKAGE METHODS . . . . . . . . . . . . . . . . . . . . . . . 214&lt;/p&gt;

  &lt;p&gt;6.3 DIMENSION REDUCTION METHODS . . . . . . . . . . . . . . . . 228&lt;/p&gt;

  &lt;p&gt;6.4 CONSIDERATIONS IN HIGH DIMENSIONS . . . . . . . . . . . . . . 238&lt;/p&gt;

  &lt;p&gt;6.5 LAB 1: SUBSET SELECTION METHODS . . . . . . . . . . . . . . . 244&lt;/p&gt;

  &lt;p&gt;XII CONTENTS&lt;/p&gt;

  &lt;p&gt;6.6 LAB 2: RIDGE REGRESSION AND THE LASSO . . . . . . . . . . . . 251&lt;/p&gt;

  &lt;p&gt;6.6.1 RIDGE REGRESSION . . . . . . . . . . . . . . . . . . . . 251&lt;/p&gt;

  &lt;p&gt;6.7 LAB 3: PCR AND PLS REGRESSION . . . . . . . . . . . . . . . 256&lt;/p&gt;

  &lt;p&gt;6.8 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259&lt;/p&gt;

  &lt;p&gt;7 MOVING BEYOND LINEARITY 265&lt;/p&gt;

  &lt;p&gt;7.1 POLYNOMIAL REGRESSION . . . . . . . . . . . . . . . . . . . . . 266&lt;/p&gt;

  &lt;p&gt;7.2 STEP FUNCTIONS . . . . . . . . . . . . . . . . . . . . . . . . . 268&lt;/p&gt;

  &lt;p&gt;7.3 BASIS FUNCTIONS . . . . . . . . . . . . . . . . . . . . . . . . . 270&lt;/p&gt;

  &lt;p&gt;7.4 REGRESSION SPLINES . . . . . . . . . . . . . . . . . . . . . . . 271&lt;/p&gt;

  &lt;p&gt;7.5 SMOOTHING SPLINES . . . . . . . . . . . . . . . . . . . . . . . 277&lt;/p&gt;

  &lt;p&gt;7.6 LOCAL REGRESSION . . . . . . . . . . . . . . . . . . . . . . . . 280&lt;/p&gt;

  &lt;p&gt;7.7 GENERALIZED ADDITIVE MODELS . . . . . . . . . . . . . . . . . 282&lt;/p&gt;

  &lt;p&gt;7.8 LAB: NON-LINEAR MODELING . . . . . . . . . . . . . . . . . . . 287&lt;/p&gt;

  &lt;p&gt;7.9 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297&lt;/p&gt;

  &lt;p&gt;8 TREE-BASED METHODS 303&lt;/p&gt;

  &lt;p&gt;8.1 THE BASICS OF DECISION TREES . . . . . . . . . . . . . . . . . 303&lt;/p&gt;

  &lt;p&gt;8.2 BAGGING, RANDOM FORESTS, BOOSTING . . . . . . . . . . . . . 316&lt;/p&gt;

  &lt;p&gt;8.3 LAB: DECISION TREES . . . . . . . . . . . . . . . . . . . . . . . 324&lt;/p&gt;

  &lt;p&gt;8.4 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332&lt;/p&gt;

  &lt;p&gt;9 SUPPORT VECTOR MACHINES 337&lt;/p&gt;

  &lt;p&gt;9.1 MAXIMAL MARGIN CLASSIFIER . . . . . . . . . . . . . . . . . . . 338&lt;/p&gt;

  &lt;p&gt;9.2 SUPPORT VECTOR CLASSIFIERS . . . . . . . . . . . . . . . . . . . 344&lt;/p&gt;

  &lt;p&gt;9.3 SUPPORT VECTOR MACHINES . . . . . . . . . . . . . . . . . . . 349&lt;/p&gt;

  &lt;p&gt;9.4 SVMS WITH MORE THAN TWO CLASSES . . . . . . . . . . . . . . 355&lt;/p&gt;

  &lt;p&gt;9.5 RELATIONSHIP TO LOGISTIC REGRESSION . . . . . . . . . . . . . . 356&lt;/p&gt;

  &lt;p&gt;9.6 LAB: SUPPORT VECTOR MACHINES . . . . . . . . . . . . . . . . 359&lt;/p&gt;

  &lt;p&gt;9.7 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368&lt;/p&gt;

  &lt;p&gt;10 UNSUPERVISED LEARNING 373&lt;/p&gt;

  &lt;p&gt;10.1 THE CHALLENGE OF UNSUPERVISED LEARNING . . . . . . . . . . . 373&lt;/p&gt;

  &lt;p&gt;10.2 PRINCIPAL COMPONENTS ANALYSIS . . . . . . . . . . . . . . . . 374&lt;/p&gt;

  &lt;p&gt;10.3 CLUSTERING METHODS . . . . . . . . . . . . . . . . . . . . . . . 385&lt;/p&gt;

  &lt;p&gt;10.4 LAB 1: PRINCIPAL COMPONENTS ANALYSIS . . . . . . . . . . . . 401&lt;/p&gt;

  &lt;p&gt;XIV CONTENTS&lt;/p&gt;

  &lt;p&gt;10.5 LAB 2: CLUSTERING . . . . . . . . . . . . . . . . . . . . . . . . 404&lt;/p&gt;

  &lt;p&gt;10.6 LAB 3: NCI60 DATA EXAMPLE . . . . . . . . . . . . . . . . . 407&lt;/p&gt;

  &lt;p&gt;10.7 EXERCISES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;갈 길이 멉니다 하하..그러나 하나같이 도움되는 내용들입니다.&lt;/p&gt;

&lt;p&gt;방학 목표는 ch.9까지 입니다. 1,2과는 사실상 intro이기에 아주 간략하게 다루고 넘어갈 것입니다.&lt;/p&gt;

&lt;h2 id=&quot;3-스터디-진행&quot;&gt;3. 스터디 진행&lt;/h2&gt;

&lt;blockquote&gt;
  &lt;p&gt;1주차: 1,2장, 3장&lt;/p&gt;

  &lt;p&gt;2주차: 3~4장&lt;/p&gt;

  &lt;p&gt;3주차: 5~6장&lt;/p&gt;

  &lt;p&gt;4주차: 7장&lt;/p&gt;

  &lt;p&gt;5주차: 8장&lt;/p&gt;

  &lt;p&gt;6주차: 9장&lt;/p&gt;

  &lt;p&gt;7주차: 밀린 부분, 혹은 10장&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
  &lt;li&gt;한명씩 돌아가며 발제를 맡습니다. 그러나 발제는 말그대로 발제이고, 모두가 다함께 해당 부분을 공부합니다.&lt;/li&gt;
  &lt;li&gt;발제가 끝나면, 다함께 공유하자는 취지에서 적극적인 피드백을 합니다. 사실상 발제가 주가 아니라 토의가 주입니다.&lt;/li&gt;
  &lt;li&gt;여력이 된다면 좀더 수식적인 이해나 numpy등을 통한 구현도 생각할 수 있을 것 같습니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;예상되는 한계&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;상당히 긴 여정입니다. 게다가 양에 비해 속도도 빠르기 때문에 도중에 지치기 쉽습니다. 무엇보다 한 챕터라도 못읽었을 시 뒷부분을 이해하지 못하여 낙오될 가능성이 다분합니다.&lt;/li&gt;
  &lt;li&gt;이론적 기반이 부족합니다(저는). 따라서 집단지성의 힘을 빌어 모두가 함께 생각하고, 구글링하고, 서로가 서로를 가르쳐주어야합니다. 공유지의 비극이 일어날 경우, 모두가 잘못된 이론을 이해하는 참사가 벌어질 수 있습니다.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;저는 ISL을 공부하고 싶은 사람일 뿐 매우 모르기에,  함께 공부하고싶은 분들의 의견을 함께 반영하여 수정하면 좋을것 같습니답&lt;/strong&gt;&lt;/p&gt;

</description>
        <pubDate>Sat, 30 Dec 2017 00:00:00 +0000</pubDate>
        <link>https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2017/12/30/ISL-study_plan.html</link>
        <guid isPermaLink="true">https://godongyoung.github.io/%EB%A8%B8%EC%8B%A0%EB%9F%AC%EB%8B%9D/2017/12/30/ISL-study_plan.html</guid>
        
        <category>An Introduction to Statistical Learning</category>
        
        <category>Machine Learning</category>
        
        
        <category>머신러닝</category>
        
      </item>
    
  </channel>
</rss>