<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Keita Starts Data Science - Medium]]></title>
        <description><![CDATA[Keita just started learning data science with little knowledge about programing in June 2019. You will see how it goes. - Medium]]></description>
        <link>https://medium.com/keita-starts-data-science?source=rss----574f68d45f6b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Keita Starts Data Science - Medium</title>
            <link>https://medium.com/keita-starts-data-science?source=rss----574f68d45f6b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:27:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/keita-starts-data-science" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Wine Prices Across Swiss-French Border]]></title>
            <link>https://medium.com/keita-starts-data-science/wine-prices-across-swiss-french-border-3c69ec90aa06?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/3c69ec90aa06</guid>
            <category><![CDATA[france]]></category>
            <category><![CDATA[global-trade]]></category>
            <category><![CDATA[wine]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[switzerland]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 22:16:12 GMT</pubDate>
            <atom:updated>2021-04-18T22:15:32.002Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I would like to express my sincere gratitude to the wine makers and those who work for the supply chain, as well as those who promoted the global free trade</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqrlSK6kBHssJJyHhdzNEg.jpeg" /></figure><p>We pay the same price for the same good in a perfect market. It is, however, not the case for many items that we consume in our daily lives. In this article I am going to look at the prices of wine, which are oftentimes mysterious, across the border between France and Switzerland.</p><h3>Summary</h3><p>In this article I briefly examine the difference between french wine prices at Coop.ch and the lowest prices of same wines in retail shops in France. With simple OLS regressions, Coop prices look competitive except for Bordeaux red wines; that may be explained by the geographical distance. The bargain prices at Coop are in many cases less expensive than even the lowest prices in France. It is also noted that wine industry in France may not be as digitalized as those in other countries, and the pricing data available online might limit the analysis.</p><h3>Data</h3><p>I looked at wines available at Coop.ch: 175 red, 44 white, and 80 sparkling wines. Retail prices in France are obtained from wine-sercher.com. The lowest price may not be of the exact same vintage; if only back vintage far from that of Coop’s is available in France, the wine was removed from the analysis. The wines available at Coop.ch are those from large-scale producers and do not represent the entire wine market. The prices in French wine shops are only from those available in wine-serchers.com and may not represent the entire market in France too.</p><p>Of 175 red wines, the largest number of 75 comes from Bordeaux, while 41 Rhone wines account for the second largest share. Coop.ch also has 39 Sud-est, 12 Bourgogne, and 9 Beaujolais wines in its inventory. Wine-sercher has price information in France for 108 wines of of 175.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*lVGNdR4eMxGYHy8rTdLtoA.png" /><figcaption>Source: Coop.ch</figcaption></figure><p>Coop.ch has 44 French white wines: 19 Alsace, 10 Sud-est, 7 Bourgogne, 4 Bordeaux, 3 Loire, and 1 Rhone. Price information in French retail shops are available for 22 white wines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Hi_6We5Ztn1ZK3QsYUr4Tg.png" /><figcaption>Source: Coop.ch</figcaption></figure><p>Out of 80 sparkling wines at Coop.ch, 68 are Champagne. Alsace accounts for 3 and 9 are from other regions in France. Price information was available for 53 wines in France.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*-wZZireXFYqSHyLJtG2nDg.png" /><figcaption>Source: Coop.ch</figcaption></figure><h3>Analysis</h3><p>From the scatter chart, we can tell that obviously for the majority of the red wines are priced higher in Coop.ch than the lowest prices in France. When a 20% is applied, however, the Coop pricing looks much more competitive and you can find good deals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*P3587G17-YyL2nJT9LrASg.png" /><figcaption>Source: Coop.ch and wine-sercher.com</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*Lx9SZspXf3kAmQZtTBoaAg.png" /><figcaption>Source: Coop.ch and wine-sercher.com</figcaption></figure><p>As you run a simple OLS, you find that Bordeaux red wines tend to be more expensive in Coop.ch, by 9.7 franc, than the lowest price in France. With the coefficients on dummies for being other regions, the difference in prices is not statistically significant for Bourgogne, Rhone, and Sud-est.</p><p>The picture for white wines look more mixed. In the lower price range, it looks more expensive in Coop.ch but in the higher end Coop.ch has competitive prices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*lSdFpr7qA3XWDRU56-NDqg.png" /><figcaption>Source: Coop.ch and wine-sercher.com</figcaption></figure><p>The sparkling wine prices look similar to those of red wines; in general the pricing at Coop.ch is more expensive than the lowest price in French retail shops. With some discount, however, Coop.ch becomes more competitive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*zQmZDwoc5fE3bWJX9Q3WbA.png" /><figcaption>Source: Coop.ch and wine-sercher.com</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*JCoz9xJFFIfalvS1IAEamw.png" /><figcaption>Source: Coop.ch and wine-sercher.com</figcaption></figure><p>A simple OLS does not find any statistically significant price difference between Coop.ch and retail shops in France.</p><h3>Conclusion</h3><p>I looked at the difference of wine prices between Coop.ch and retail shops in France. Among wines sold at Coop.ch, only Bordeaux red wines are significantly more expensive than the lowest price in France. At a time of a bargain, pricing at Coop.ch is highly competitive.</p><h3>Some Other Impressions</h3><ul><li>There seem to be export-only producers, whose wines are not found in the domestic market</li><li>The French wine industry may not be as digitalized as those in other countries, and price information online looks rather scarce</li><li>I am thankful to those who makes items available outside of the country of origin. I am also thankful for those who promote the free trade as a consumer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*1nxe49nv6zYsEPJx7BqbAw.png" /><figcaption>We always hope to see this</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c69ec90aa06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/wine-prices-across-swiss-french-border-3c69ec90aa06">Wine Prices Across Swiss-French Border</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science初歩からAlgorithmを学ぶ その3]]></title>
            <link>https://medium.com/keita-starts-data-science/data-science%E5%88%9D%E6%AD%A9%E3%81%8B%E3%82%89algorithm%E3%82%92%E5%AD%A6%E3%81%B6-%E3%81%9D%E3%81%AE3-b44ccd3b88fe?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/b44ccd3b88fe</guid>
            <category><![CDATA[divide-and-conquer]]></category>
            <category><![CDATA[quicksort]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 22:09:17 GMT</pubDate>
            <atom:updated>2020-02-11T14:27:20.614Z</atom:updated>
            <content:encoded><![CDATA[<p>数列を並べ換えるアルゴリズムばかり書いていますが、とりあえず飽きずに続けています。今回学んだのはQuick Sortというアルゴリズムで、今までのものと異なり、確率論が絡んできます。</p><p>Quick Sortが何をするかというと、数列の一項（「ピボット」と呼びます）を選び、その値より小さい項をその左側に、それより大きな項を右に放り込むというものです。このアルゴリズムをピボットの左右の数列にそれぞれ使うということを繰り返してゆけば、最終的に昇順に並べ替えられた数列を得ることができますね。</p><p>もし数列の中身が既知であれば、中央値をピボットにしてゆけば良いのですが、未知の数列を扱うときはランダムにピボットを取ってきます。最も不運なケースでは、数列の最小値/最大値をピボットにとり続け、その場合は<em>n(n-1)/2</em>のコスト、すなわち<em>Θ(n²)</em>となりますが、これが起こる確率は<em>1/n!</em>なので考えなくて良いでしょう。ここではコストの期待値を考えます。</p><p>コストは、アルゴリズムが二つの数字を比べる回数（<em>X</em>とします）として考えられます。さて、数列の<em>Zi</em>と<em>Zj</em>という二つの数字が比べられる確率はどのくらいでしょうか。もし<em>Zi</em>と<em>Zj</em>との間の項がピボットに選ばれた場合、そのピボットの値と<em>Zi</em>及び<em>Zj</em>が比較され、左右に振り分けられるため、<em>Zi</em>と<em>Zj</em>が直接比べられることはありません。<em>Zi</em>と<em>Zj</em>が比べられるのはそのどちらかがピボットとして選ばれた場合だけです。なお、<em>Zi</em>と<em>Zj</em>の外側の数字がピボットとして選ばれた場合は、<em>Zi</em>と<em>Zj</em>は左右どちらか同じ側に含まれることになり、確率に影響はありません。というわけで、<em>Zi</em>と<em>Zj</em>が比べられる確率は<em>2/(j-i+1)</em>となります。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*FwF2qlR_sOPzOLrp9CGO6g.png" /></figure><p>というわけで、この確率を全ての<em>Zi</em>と<em>Zj</em>について足し上げてゆけば、Xの期待値が出てきます。式変形しながら、上から抑えてゆくと、コストの期待値は<em>Θ(nlgn)</em>になることがわかります。<em>Θ(n²)</em>より加速度が小さいですね。</p><p>というわけで、ここからコードを書いてゆきます。</p><pre>def <strong>quick_sort</strong>(array):<br>    length = len(array)<br>    <br>    if length &lt;= 1:<br>        return array<br>    <br>    if length == 2:<br>        if array[0] &gt; array[1]:<br>            return [array[1], array[0]]<br>        else:<br>            return array<br>        <br>    else:<br>        pivot = np.random.randint(0, length)<br>        small = []<br>        large = []<br>        <br>        for element in array:<br>            if element &lt; array[pivot]:<br>                small.append(element)<br>            elif element &gt; array[pivot]:<br>                large.append(element)<br>                <br>        if not small:<br>            return [array[pivot]] + <strong>quick_sort</strong>(large)<br>        elif not large:<br>            return <strong>quick_sort</strong>(small) + [array[pivot]]<br>        else:<br>            return <strong>quick_sort</strong>(small) + [array[pivot]] + <strong>quick_sort</strong>(large)</pre><p>さて、上のコードでは左右の数列を”small”と”large”という二つの変数に格納してアルゴリズムを繰り返してゆきますが、in-placeすなわち元の数列の他に定数分しかデータを保存しない形でコードを書くとメモリにやさしいと聞いたことがあるので、そのコードも書いてみます。端的にいえば、元の数列を並べ替えてゆくアルゴリズムです。</p><pre>def <strong>quick_sort_in_place</strong>(array, start, end):<br>    if start &lt; end:<br>        <br>        if start + 1 == end:<br>            if array[start] &gt; array[end]:<br>                larger = array[start]<br>                array[start] = array[end]<br>                array[end] = larger<br>        <br>        pivot = np.random.randint(start, end+1)<br>        pivot_value = array[pivot]<br>        <br>        array = np.insert(array, end+1, pivot_value)<br>        array = np.delete(array, pivot)<br>        <br>        border = start - 1<br>        <br>        for i in range(start, end):<br>            if array[i] &lt; pivot_value:<br>                border += 1<br>                border_value = array[i]<br>                array[i] = array[border]<br>                array[border] = border_value<br>        array = np.insert(array, border+1, pivot_value)<br>        array = np.delete(array, end+1)<br>        <br>        array = <strong>quick_sort_in_place</strong>(array, start, border+1)<br>        array = <strong>quick_sort_in_place</strong>(array, border+2, end)</pre><pre>    return array</pre><p>さて、パフォーマンスを比べてみましょう。前回書いた<em>Θ(nlgn)</em>のMerge Sortのアルゴリズム、<em>Θ(n²)</em>のInsertion Sortを比較対象にしてみます。ちゃんとInsertion Sortだけ傾きが大きくなっていますね。Quick SortはMerge Sortより安いことがわかりますが、in-placeだと高くなりますね。<em>Θ(nlgn)</em>に出てこない係数（定数）の差が効いているようです。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*JntGe1Jz7EtL6SczZ6mBog.png" /><figcaption>Source: Author’s calculation</figcaption></figure><p>さて、Quick Sortのコストの期待値は計算しましたが、実際にどのくらいばらけるのでしょうか。項数2¹⁰の数列で試行を繰り返して分布を見てみます。結果はこんな感じでした。Merge-Sortもかなりばらけるんですね。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*U7zzSQ2Vpi7ZY8ML4XX9kQ.png" /><figcaption>Source: Author’s calculation</figcaption></figure><h4>追記</h4><p>In-Place Quicksortが遅かったのはnumpyのファンクションを使っていたからでした。ただ、それを直してもMerge Sortと同じくらいにしかなりませんでした。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*46EcIrlrCUx6ge7NWVQBvQ.png" /><figcaption>Source: Author’s calculation</figcaption></figure><pre>def <strong>quick_sort_in_place</strong>(array, start, end):<br>    if start &lt; end:<br>        <br>        if start + 1 == end:<br>            if array[start] &gt; array[end]:<br>                larger = array[start]<br>                array[start] = array[end]<br>                array[end] = larger<br>        <br>        pivot = np.random.randint(start, end+1)<br>        pivot_value = array[pivot]<br>        <br>        array[pivot] = array[-1]<br>        array[-1] = pivot_value<br>        <br>        border = start - 1<br>        <br>        for i in range(start, end):<br>            if array[i] &lt; pivot_value:<br>                border += 1<br>                border_value = array[i]<br>                array[i] = array[border]<br>                array[border] = border_value<br>        array[-1] = array[border+1]<br>        array[border+1] = pivot_value<br>        <br>        array = <strong>quick_sort_in_place</strong>(array, start, border+1)<br>        array = q<strong>uick_sort_in_place</strong>(array, border+2, end)</pre><pre>    return array</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b44ccd3b88fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/data-science%E5%88%9D%E6%AD%A9%E3%81%8B%E3%82%89algorithm%E3%82%92%E5%AD%A6%E3%81%B6-%E3%81%9D%E3%81%AE3-b44ccd3b88fe">Data Science初歩からAlgorithmを学ぶ その3</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science初歩からAlgorithmを学ぶ その2]]></title>
            <link>https://medium.com/keita-starts-data-science/data-science%E5%88%9D%E6%AD%A9%E3%81%8B%E3%82%89algorithm%E3%82%92%E5%AD%A6%E3%81%B6-%E3%81%9D%E3%81%AE2-caf1c265593c?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/caf1c265593c</guid>
            <category><![CDATA[divide-and-conquer]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Wed, 05 Feb 2020 21:50:43 GMT</pubDate>
            <atom:updated>2020-02-05T21:50:43.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OinKCn5IlCzF1DgsoJm-dQ.jpeg" /><figcaption>日本へのお土産はWasenhaus, Julia Bertramなどドイツを中心に3ケース</figcaption></figure><p>年末年始は欧州、日本を6週間のわたって旅してData Scienceはお休みしていましたが、最近再開しました。相変わらず、基礎体力訓練のようなことをやっています。</p><p>今回の課題は、ランダムな重複のない数列を与えられ、逆順の数字のペアの数を数えるというもの。逆順というのは、２整数 i&lt;j について、数列の i番目の数が j番目より大きい場合を言うようです。</p><p>数列の項数 n について、総当たりで比較する場合は非常に単純で、n(n-1)/2だけ計算すれば良いのですね。コストはΘ(n²)です。コードも単純で、loopを二つかませれば良いだけ。数行で終わってしまいます。</p><pre>def bf_inversion_count(array):<br>    count = 0<br>    for i in range(len(array)):<br>        j = i + 1<br>        while j &lt; len(array):<br>            if array[i] &gt; array[j]:<br>                count +=1<br>            j += 1<br>    return count</pre><p>さて、総当たりより効率的な方法はないでしょうか。以前書いたMerge-Sortのコードをいじれば良さそうです。数列を二分割してゆき、かかるコストはこんな感じで表現できます。</p><p>T(n) = 2T(n/2) + f(n)</p><p>項数nの数列の中の逆転ペアを数えるコストT(n)は、二分割した項数n/2の数列の中の逆転ペアを数えるコストT(n/2)の2回分と、分割された数列二つにまたがった逆転ペアを数えるコストf(n)の和です。Merge-Sortを応用すればf(n)はnに比例する関数とすることができ、すなわちf(n)=Θ(n)とできそうです。となるとT(n)=Θ(nlgn)ですね。</p><p>Functionは、並べ替えられた数列と元の数列の中に含まれる逆転ペアの数を返すようにします。分割された数列二つの間で逆転ペアを数える方法もMerge-Sortに少し手を加えるだけ。二つの数列をそれぞれ昇順に並べ替えたものの、それぞれ一番左の数を取り出して比べ、若い方を取り出して数列を作ってゆきますが、その際に右の数列から数字を取り出すことになった場合に左の数列に残っている数を数えます。それを足してゆけば二つの数列にまたがる逆転ペアが数えられますね。</p><pre>def sc_inversion_count(array):<br>    <br>    length = len(array)<br>    <br>    if length == 2:<br>        if array[0] &gt; array[1]:<br>            return np.array([array[1], array[0]]), 1<br>        else:<br>            return array, 0<br>    <br>    elif length &gt; 2:<br>        array_l = array[:int(length/2)]<br>        array_r = array[int(length/2):]<br>        array_l_df = sc_inversion_count(array_l)<br>        array_r_df = sc_inversion_count(array_r)<br>        array_l_sorted = array_l_df[0]<br>        array_r_sorted = array_r_df[0]<br>        count = array_l_df[1] + array_r_df[1]</pre><pre>        l = 0<br>        r = 0<br>        <br>        sorted_list = []<br>        <br>        for i in range(length):<br>            if r == int(length/2):<br>                sorted_list.append(array_l_sorted[l])<br>                l += 1</pre><pre>            elif l == int(length/2):<br>                sorted_list.append(array_r_sorted[r])<br>                r += 1             <br>                <br>            elif array_l_sorted[l] &gt; array_r_sorted[r]:<br>                sorted_list.append(array_r_sorted[r])<br>                r += 1<br>                count += len(array_l_sorted) - l<br>                <br>            elif array_l_sorted[l] &lt; array_r_sorted[r]:<br>                sorted_list.append(array_l_sorted[l])<br>                l += 1<br>        <br>        return np.array(sorted_list), count</pre><p>さて、総当たり式と分割式のパフォーマンスを比べてみましょう。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*XpR6LnXTTrrfd3U-scLBTg.png" /><figcaption>Source: Author’s calculation</figcaption></figure><p>数列が長くなるに従って、分割方式の方がコストが安くなりますね。めでたしめでたし。というわけでまだまだ勉強頑張ります。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caf1c265593c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/data-science%E5%88%9D%E6%AD%A9%E3%81%8B%E3%82%89algorithm%E3%82%92%E5%AD%A6%E3%81%B6-%E3%81%9D%E3%81%AE2-caf1c265593c">Data Science初歩からAlgorithmを学ぶ その2</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science初歩からAlgorithmを学ぶ]]></title>
            <link>https://medium.com/keita-starts-data-science/data-science%E5%88%9D%E6%AD%A9%E3%81%8B%E3%82%89algorithm%E3%82%92%E5%AD%A6%E3%81%B6-38a10c281cbf?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/38a10c281cbf</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Wed, 11 Dec 2019 09:23:22 GMT</pubDate>
            <atom:updated>2020-01-08T06:30:47.253Z</atom:updated>
            <content:encoded><![CDATA[<p>夏からData Scienceの応用的な分野を学んできましたが、思い立ってAlgorithmについて初歩から勉強し始めました。今週から<a href="https://www.coursera.org/learn/algorithms-divide-conquer/home/welcome">CourseraのStanfordのコース</a>を聴講しています。</p><p>端的に言えば色々な処理をいかに効率的にプログラムするかということを追求するのだと理解しています。Pythonでコードを書きますが、既存のLibrary、Functionを使わず、四則演算だけで課題に答えてゆきます。小学校の算数のようで面白いです。</p><p>さて、今回の課題は平面上の点の集合を与えられ、その中で二点間の距離が最短になる二点を探せ、というものです。素朴な解法は全ての点の組み合わせについて座標を使って二点間の距離を求め、一番小さいものを見つけるというものですね。</p><pre>def find_closest_brute_force(array):<br>    <br>    dict_final = {}<br>    dict_final[&quot;p1&quot;] = array[0]<br>    dict_final[&quot;p2&quot;] = array[1]<br>    dict_final[&quot;distance&quot;] = np.sqrt((array[0][0]-array[1][0])**2+(array[0][1]-array[1][1])**2)<br>    <br>    for i in range(len(array)-1):<br>        for j in range(i+1, len(array)):<br>            distance = np.sqrt((array[i][0]-array[j][0])**2<br>                               +(array[i][1]-array[j][1])**2)<br>            if distance &lt; dict_final[&quot;distance&quot;]:<br>                dict_final[&quot;p1&quot;] = array[i]<br>                dict_final[&quot;p2&quot;] = array[j]<br>                dict_final[&quot;distance&quot;] = distance</pre><pre>    return dict_final</pre><p>こんな感じで、for loopを二重に使えば正解を得られます。n個の点が与えられたとき、n(n-1)/2回計算をすれば良いわけです。この解法だと、点の数が多くなるに連れて、二乗でかかる時間は増えてゆきます。もっと効率的な方法はないのでしょうか。</p><p>最初に全ての点をx座標に関して昇順に並べ替えます。総当たりで並べ替えるとn(n-1)/2回の計算が必要となりますが、それより効率的な方法があります。最も近い点を見つけるコードを書く前に、この並べ替えのコードを書いてみます。</p><p>並べ替え前の点の集合を二つに分割し、その二つの集合の中で並べ替えを行い、それぞれの集合の一番小さい数字を比べ、小さい方を取り出します。それを取り出した後、さらに二つの集合の一番小さい数字同士を比べ、並べます。n回比較を行うと、並べ替えられた点の集合が得られます。</p><p>二つの集合のそれぞれの中で並べ替えをする作業について考えていませんでしたね。それは各集合をさらに二分割して、同じ処理をすれば良いのです。それをマトリョーシカ的に繰り返して、最後は1つか2つの点の集合まで細分化できます。分割はlog2n回すれば良いわけですね。というわけで、並べ替えにはnlog2nのコストがかかるわけです。これは二乗よりは増加率が大人しいですね。</p><pre>def sort_nest(array):<br>    <br>    length = len(array)<br>    <br>    if length == 2:<br>        if array[0][0] &gt; array[1][0]:<br>            return np.array([array[1], array[0]])<br>        else:<br>            return array<br>    <br>    elif length &gt; 2:<br>        array_l = array[:int(length/2)]<br>        array_r = array[int(length/2):]<br>        array_l_sorted = sort_nest(array_l)<br>        array_r_sorted = sort_nest(array_r)</pre><pre>        l = 0<br>        r = 0<br>        <br>        sorted_list = []<br>        <br>        for i in range(length):<br>            if r == int(length/2):<br>                sorted_list.append(array_l_sorted[l])<br>                l += 1</pre><pre>            elif l == int(length/2):<br>                sorted_list.append(array_r_sorted[r])<br>                r += 1             <br>                <br>            elif array_l_sorted[l][0] &gt; array_r_sorted[r][0]:<br>                sorted_list.append(array_r_sorted[r])<br>                r += 1<br>                <br>            elif array_l_sorted[l][0] &lt; array_r_sorted[r][0]:<br>                sorted_list.append(array_l_sorted[l])<br>                l += 1<br>        <br>        return np.array(sorted_list)</pre><p>さて、準備ができたので最も近い二点の組み合わせを見つけるコードを書いていきます。方針は、与えられた点の集合を二分割し、その中で最も近い二点のペアを見つけて、二つのペアを比べるというもの。先ほど書いたコードでX座標に関して昇順に並べ替えられた点の集合を分割してゆくことにします。ただし、最も近い点のペアが分割された両側の二点のペアである可能性があるので、それを手当します。</p><pre>def find_closest_nest(array):<br>    X = sort_nest(array, 0)<br>    length = len(X)<br>    if length &lt; 4:<br>        return find_closest_brute_force(array)<br>    <br>    else:<br>        array_l = X[:int(length/2)]<br>        array_r = X[int(length/2):]</pre><pre>        dict_l = find_closest_nest(array_l)<br>        dict_r = find_closest_nest(array_r)<br>                    <br>        if dict_l[&quot;distance&quot;] &gt; dict_r[&quot;distance&quot;]:<br>            dict_both = dict_r<br>        else:<br>            dict_both = dict_l<br>        <br>        Y = sort_nest(array, 1)<br>        <br>        Y_list = []<br>        for i in range(length):<br>            if X[int(length/2-1)][0]-dict_both[&quot;distance&quot;] &lt; Y[i][0] &lt; X[int(length/2-1)][0]+dict_both[&quot;distance&quot;]:<br>                Y_list.append(Y[i])</pre><pre>        Y = np.array(Y_list)<br>        if len(Y) == 1:<br>            dict_final = dict_both<br>        elif len(Y) &lt; 8:<br>            dict_y = find_closest_brute_force(Y)<br>            if dict_both[&quot;distance&quot;] &gt; dict_y[&quot;distance&quot;]:<br>                dict_final = dict_y<br>            else:<br>                dict_final = dict_both            <br>        else:<br>            for i in range(len(Y)-7):<br>                dict_y = find_closest_brute_force(Y[i:i+7])       <br>                if dict_both[&quot;distance&quot;] &gt; dict_y[&quot;distance&quot;]:<br>                    dict_final = dict_y<br>                else:<br>                    dict_final = dict_both<br>    <br>        return dict_final</pre><p>二点が分割された両側にある場合、その二点はX座標について分割する線から非常に近くあるはずです。具体的には、両側の点の集合の内部で最も近い点の間の距離をδとすると、分割されたX座標から両側にδ離れた点までを見れば良さそうです。</p><p>ここで、分割前の点の集合のうち、分割されるX座標から左右にδまでの範囲にある点を考えます。それをY座標に関して昇順で並べ替えます。こうして得られる点の集合をY’とします。もし最も近い点のペアが分割後の左右に分かれる場合、その点のペアはY座標に関してδ以下の範囲にあるはずです。</p><p>左右それぞれの中にお互いにδより近い点は無いので、点の重なりを許す場合でも、Y’の中の任意の点について、それが含まれる2δ×δの長方形の範囲には最大8個の点しか存在し得ません。というわけで、Y’の中からY座標に関して昇順に8個ずつの点を取り、その中で最も近い点のペアを見つけ、それと左右分割後の点の集団の中での最も近い点のペアと距離を比べることにします。これで最も近い点が左右に分かれた場合を手当できますね。</p><p>総当たり方式と分割方式にかかる時間を比べると、前者はn二乗のコストがかかるのに対して、後者はnlognのコストにとどまります。点の数が多くなれば多くなるほど分割方式が有利になってきますね。テストするとこんな感じで綺麗に出ます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*eg0l0NWB7XAgE7mz3UkG-A.png" /><figcaption>source: author’s calculation</figcaption></figure><p>というわけで、計算の仕方を変えることで、処理にかかるコストが段違いになるというのを実感します。そういうことを考えながらプログラムを書きましょう、ということですね。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38a10c281cbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/data-science%E5%88%9D%E6%AD%A9%E3%81%8B%E3%82%89algorithm%E3%82%92%E5%AD%A6%E3%81%B6-38a10c281cbf">Data Science初歩からAlgorithmを学ぶ</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Scienceなんちゃって人工知能]]></title>
            <link>https://medium.com/keita-starts-data-science/data-science%E3%81%AA%E3%82%93%E3%81%A1%E3%82%83%E3%81%A3%E3%81%A6%E4%BA%BA%E5%B7%A5%E7%9F%A5%E8%83%BD-3aef3f7eaf70?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/3aef3f7eaf70</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 15:46:58 GMT</pubDate>
            <atom:updated>2019-10-22T15:46:06.912Z</atom:updated>
            <content:encoded><![CDATA[<p>6ヶ月先の米国のGDPギャップを人工知能を使って予測するモデルを作ってみました。結論は、やはり難しいというものです。Recurrent Neural Networks (RNN)というモデルを用いました。致命的な問題は、やはり経済構造や経済危機の原因は時とともに変化することと、利用可能なデータが限られていることでしょうか。それと現実的に、私のmid-2012 Macbook Proでは色々試行しているとメモリがパンパンになって動かなくなり、ストレスが溜まることも…</p><p>RNNは端的には、一つのインプットに複数の時点のデータを含んでモデルを回し、先の時点のデータからの記憶を次の時点のデータを使うときに引き継いでゆくというものです。今回の場合は1970年代後半からの米国の経済・市場データ（週次）を使いましたが、52週分（1年分）のデータを1バッチとして扱い、あるバッチの中の第1週の状態を第2週に引き継ぎ、そこから第3週へ引き継ぎ…というのを繰り返しました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fz42-fbStJuO6GlQlXs-1A.png" /><figcaption>Unfolded basic recurrent neural network (Wikipedia)</figcaption></figure><p>さて、コード描いてみたんですが、RNNは初めてなので層を何枚噛ませるかとかよくわかりません。下のLSTM層がRNNのキモなんですがここでは3枚にしています。</p><pre>regressor = Sequential()</pre><pre><strong>regressor.add(LSTM(units=50, <br>                   return_sequences=True, <br>                   input_shape=(X_train_rnn.shape[1], <br>                                X_train_rnn.shape[2])))</strong><br>regressor.add(Dropout(drop_out))<br>    <br><strong>regressor.add(LSTM(units=50, return_sequences=True))</strong><br>regressor.add(Dropout(drop_out))<br>    <br><strong>regressor.add(LSTM(units=50))</strong><br>regressor.add(Dropout(drop_out))</pre><pre>regressor.add(Dense(units=1))</pre><pre>regressor.compile(optimizer=&#39;adam&#39;, loss=&#39;mean_squared_error&#39;)</pre><pre>regressor.fit(X_train_rnn, <br>              y_train_rnn, <br>              epochs=50, <br>              batch_size=50)</pre><p>というわけで試してみました。LSTM層の数を変えて、それぞれ10回ずつの試行です。2007年くらいを境に訓練用データとテスト用データが切り替わるので、その後を見てみて下さい。2~3枚のLSTM層を噛ませるだけでは予測が全く安定しません。6枚以上だと何だか収束しているように見えます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wYONqVFkmiYRcxRHUpb_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQLgoIQeAxDKKNPlOni3Sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibQEkrm8MrlYJVc4oQI0PA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3eXN6A-ythRDs2BgrMFkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mc-Ytorm60Mj5GJvvC8Vqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5rvQ6JhZKB2AQ5g2lPlbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_9ycrdGzyyCaeXPO664Nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvHJ0LngHD7TgFEKnVsh4A.png" /><figcaption>Source: FRED, author’s calculation</figcaption></figure><p>Root Mean Squared Errorを見てみましょう。LSTM2層では明らかに誤差が大きく、振れ幅も過大ですね。LSTM6層あたりから安定して低下しているのが見てとれます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Q6G6PQ5nb9RAOJRior8HsA.png" /><figcaption>Source: FRED, author’s calculation</figcaption></figure><p>しかし明らかにoverfittingなんですね。二つの線、訓練期間は実際の数値にぴったり寄り添っていますが、テスト期間はかなり乖離しています。一番手っ取り早くoverfittingを手当てする方法の一つがdrop-outと呼ばれるもので、テスト用データでモデルを回す際に、指定された比率でニューロンを無視します。その比率をいじってみます。</p><p>LSTM層の数ほど明確な違いは見られませんが、比率を0.6以上に上げてゆくと弊害がありそうです。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0YshjcMQhGJpaoEWLkbzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xki7ME38jzAg3xn0qONbUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AnJFAkVQhK9gMXWd8lZoRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJr8iecPpt2gTXLCv0vMiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pza2UbdTKFZVhRwc8LnMiw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rPl2AdR-tfJwqqQDnPXg5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSzTkgw_aqRJxuzriqDQeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZmGF21vkaJhoyGWknhPYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IswqtR8vRXGVlZLy7pRog.png" /><figcaption>Source: FRED, author’s calculation</figcaption></figure><p>先の例と同じようにRoot Mean Squared Errorを見てみましょう。やはり大き過ぎるdrop-out比率は誤差を大きくしますね。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*srFNAjoAY7YxJJ-pGuPDfw.png" /><figcaption>Source: FRED, author’s calculation</figcaption></figure><p>というわけでどれだけ調整しても、正確にGDPギャップを当てにゆくことはできませんでした。これが簡単に出来ればエコノミストの仕事はなくなってしまうわけなのですが。</p><p>Data Scientistとエコノミストのアプローチには大きな違いがあります。乱暴に言うと、前者はあるターゲットの数値を予測する正確さを目指し、モデルの中身がどれだけ難解で解釈不可能でも、結果さえ正確であれば幸せです。後者はどちらかと言うと因果関係を明らかにすることで、ある前提条件のもとで将来を予測することに注力します。</p><p>というわけで、上記のような当たらないけど中身がよくわからないモデルを作っているdata scientistは要らない子なんですよね。精進します。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aef3f7eaf70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/data-science%E3%81%AA%E3%82%93%E3%81%A1%E3%82%83%E3%81%A3%E3%81%A6%E4%BA%BA%E5%B7%A5%E7%9F%A5%E8%83%BD-3aef3f7eaf70">Data Scienceなんちゃって人工知能</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science大統領選挙再考]]></title>
            <link>https://medium.com/keita-starts-data-science/data-science%E5%A4%A7%E7%B5%B1%E9%A0%98%E9%81%B8%E6%8C%99%E5%86%8D%E8%80%83-b051825e9221?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/b051825e9221</guid>
            <category><![CDATA[trump]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Wed, 11 Sep 2019 02:16:34 GMT</pubDate>
            <atom:updated>2019-09-11T02:16:33.767Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Scienceのプログラムも最終週を迎え、最後のプロジェクトに取り組んでいます。題材は米国大統領選挙。<a href="https://medium.com/keita-starts-data-science/the-divided-states-of-america-f42e904e76f0">以前に分析した</a>のは2016年のみでしたが、今回は2012年の選挙及び2010~2017年の国勢調査のデータをもとに、米国政治環境の変化を見ようと試みています。</p><p>問いは「米国内の政治的分断は選挙区ごとの人口構成の変化に伴うものなのか、それとも人口構成はあまり変わらない一方で選挙自体の性質が変化したのか」というものです。例えば民主党の支持基盤である都市部に、民主党の主義に親和性のある人口が流入して、都市部で民主党がより強くなり、非都市部で共和党が支持を伸ばすということも考えられます。</p><p>使用するデータは前回同様、US Census American Community Surveyの郡レベルの人口/世帯構成比率（人口/世帯総数ではなく）で、アラスカ州を除き、2010年から2017年全ての年で揃っている297個の変数を用いました。ところどころ虫食いの部分をXGBoostでimputeしています。</p><p>モデルは幾つか試してXGBoost Regressorを選択しました。Hyper parameterのtuningも試行錯誤しましたが、成績は向上せず、early stoppingを採用するのみにしました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Dbzw-QYp2OmgZFBTKtuT6g.png" /><figcaption>Source: US Census</figcaption></figure><p>モデルでは共和党候補（2016年はトランプ氏）と民主党候補（同クリントン氏）のマージンを非説明変数にします。郡ごとの投票総数をサンプルごとの重みづけに用いました。左図に示すように純粋なモデルの成績は、重みづけによって悪化します。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*elufrLLLbVF-dWfR-wr4ug.png" /><figcaption>Source: US Census</figcaption></figure><p>しかし、この重みづけにより、人口の大きな郡/市でより正確な予想がなされるようになり、投票数に直した誤差は減少します。左図では重みづけした青い分布が、重みづけ無しの赤い分布よりより狭い範囲に収まっているのがわかります。</p><p>というわけで、ここから実際に分析してゆきます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijUDLsGGkcpdYPr-bABDag.jpeg" /></figure><p>さて、最初に試したのは、2016年の選挙モデルを作り、そこに過去の国勢調査のデータを代入してみるというもの。もし郡レベルの人口動態の変化が民主党・共和党支持基盤の分離をもたらしているとすれば、2010年から年を追うごとにマージンが広がっていることになるでしょう。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*fN8TSUoxS_y45sOQyqKIeg.png" /><figcaption>Source: US Census</figcaption></figure><p>左図では、X軸に2010年のデータを代入した結果を、Y軸には2010年と2016年のデータを代入した結果の差をとりました。右肩上がりの傾向があれば民主党・共和党を支持する地区が両極に寄ってゆこうとする傾向があると言えそうですが、必ずしもそうではなさそうですね。なお、共和党支持層の郡（赤い点）がより上下に広く分散しているのは、それらの群が民主党支持層の郡/市と比べて規模が小さく、人口動態のデータの振れ幅が大きいことによるものではないかと推測します。</p><p>2016年のモデルに2010年から2017年までのデータを代入して州ごとに集計したのが下のチャートです。簡単に言うと、もし2016年の大統領選挙が他の年に行われたら結果はどうなっただろうか、という試行です。2014年に民主党の支持がピークをつけている州が幾つか見られるのは、或いは全国的な経済環境に関わる変数によるものでしょうか。注目はフロリダ州、トランプ氏が1.2％の競り勝った2016年から、2017年には共和党に有利な環境になっていることが示されています。逆にペンシルバニア州では、前回の選挙では0.7％の差に泣いた民主党が伸びる環境になってきています。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raBGshawCUKKNLt2DoFfGQ.png" /><figcaption>Source: US Census</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4NBq5r-3QWDtdGCJ0BO8w.jpeg" /></figure><p>次に見たのは、2012年、2016年のモデルがどれだけの誤差を伴ったかです。誤差が小さければ小さいほど、国勢調査のデータが選挙結果をより正確に説明していることになります。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*uFjeP5UEOToMSZcZW3BVJw.png" /><figcaption>Source: US Census</figcaption></figure><p>それぞれ100回の試行を行なった結果、平均平方二乗誤差は有意に2016年のモデルの方が小さいことが言えました。2016年の選挙ではより人種間、異なる所得層間、都市部/非都市部の対立、分離が明確に結果に表れているということができるでしょう。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOYgkRjqZzzRu6Svo6w5Lg.jpeg" /></figure><p>最後に、2012年、2016年の二つのモデルに2016年の国勢調査のデータを代入してみます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*zbITD28Uq_2nMP-PJQMNkg.png" /><figcaption>Source: US Census</figcaption></figure><p>X軸が2012年モデルに2016年のデータを代入した結果の得票率差、Y軸には2016年モデルに同年のデータを代入した結果と2012年モデルの差をとっています。2012年モデルで共和党支持となった多くの群で2016年モデルの方が共和党支持が強まっていることがわかります。逆に民主党支持層ではそれほど大きなモデル間の差は無いようです。トランプ氏が共和党支持基盤の潜在力をしっかり引き出したということでしょうか。</p><p>さて、ここまで幾つかの切り口から米国大統領選挙を分析してきましたが、2010年以降の人口動態の変化が選挙結果に与えた影響として特筆すべきものは見つかりませんでした。しかし2016年に僅差で勝敗が分かたれた接戦州で、特にフロリダ州やペンシルバニア州では国勢調査のデータから読み取れる環境の変化が手がかりになるかも知れません。なおACS5年推定の2018年データは12月19日に公開されます。新たなデータをモデルに代入してみるとより次の選挙に近い環境の分析ができるでしょう。</p><p>巷で言われる民主党・共和党支持地域間の分断（紫のアメリカから赤と青のアメリカへ）は2016年の選挙でトランプ氏が共和党の支持基盤でさらに勢いを強めたことによるところが大きく、一方で民主党支持地域でクリントン氏がより得票を伸ばしたとは言えないようです。さて、来年の選挙はおそらくトランプ氏が再選を目指すでしょう。民主党候補は真紅に染まった郡を薄くすることができるのか、青を藍色にすることができるのか、見てゆきましょう。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b051825e9221" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/data-science%E5%A4%A7%E7%B5%B1%E9%A0%98%E9%81%B8%E6%8C%99%E5%86%8D%E8%80%83-b051825e9221">Data Science大統領選挙再考</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Divided States of America]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/keita-starts-data-science/the-divided-states-of-america-f42e904e76f0?source=rss----574f68d45f6b---4"><img src="https://cdn-images-1.medium.com/max/1296/1*nFABgNf6HP9NN6RXEiC_hQ.png" width="1296"></a></p><p class="medium-feed-snippet">The people in the United States are not well united when it comes to politics. While having different opinions and expressing their ideas&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/keita-starts-data-science/the-divided-states-of-america-f42e904e76f0?source=rss----574f68d45f6b---4">Continue reading on Keita Starts Data Science »</a></p></div>]]></description>
            <link>https://medium.com/keita-starts-data-science/the-divided-states-of-america-f42e904e76f0?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/f42e904e76f0</guid>
            <category><![CDATA[trump]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[presidential-election]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[politics]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 21:32:04 GMT</pubDate>
            <atom:updated>2019-09-18T15:14:13.554Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Data Science大統領選挙を見ました]]></title>
            <link>https://medium.com/keita-starts-data-science/data-science%E5%A4%A7%E7%B5%B1%E9%A0%98%E9%81%B8%E6%8C%99%E3%82%92%E8%A6%8B%E3%81%BE%E3%81%97%E3%81%9F-3baf0bf5ba3e?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/3baf0bf5ba3e</guid>
            <category><![CDATA[presidential-election]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[donald-trump]]></category>
            <category><![CDATA[hillary-clinton]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Fri, 16 Aug 2019 03:51:55 GMT</pubDate>
            <atom:updated>2019-08-16T03:51:55.064Z</atom:updated>
            <content:encoded><![CDATA[<p>だんだんと周りで来年の米大統領選挙の話題が盛り上がり始めています。誰が民主党の候補になるのか、現職のトランプ大統領に勝てるのか。毎週話題には事欠きません。そんなこともあり、この国の現状を理解するために国勢調査のデータと照らし合わせて2016年の大統領選挙の結果を分析してみました。</p><p>使ったのはUS Census <a href="https://www.census.gov/data/developers/data-sets/acs-5year.html">American Community Survey</a>です。そのうちでもData Profileと呼ばれる主要なデータを使いました。分析はCounty（郡）もしくはCity（市）単位で、プエルトリコとアラスカは除きました。プエルトリコは国勢調査のデータはあるものの住民は国政・大統領選挙の選挙権がありません。<a href="https://ja.wikipedia.org/wiki/%E9%9D%9E%E8%87%AA%E6%B2%BB%E9%83%A1_(%E3%82%A2%E3%83%A9%E3%82%B9%E3%82%AB%E5%B7%9E)">アラスカの区割り</a>は分析者泣かせです。</p><p>データお掃除はとても骨が折れたのですが、もしコードにご興味のある方はこちらの<a href="https://github.com/keita-dc/FlatironProject5">github</a>をご覧下さい。お掃除が終わったら、いつも通り訓練用とテスト用のデータを分けて、標準化、それからRandom Forestを使ってみます。なお、Xには後でCountyと照合できるよう、最初の2行にIDを入れています。</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, <br>                                                    stratify=y)<br>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train.iloc[:, 2:])<br>X_test_scaled = scaler.transform(X_test.iloc[:, 2:])</pre><pre>rfc = RandomForestClassifier(class_weight=&quot;balanced&quot;)<br>rfc.fit(X_train_scaled, y_train)<br>print(&quot;train: &quot;, rfc.score(X_train_scaled, y_train))<br>print(&quot;test: &quot;, rfc.score(X_test_scaled, y_test))</pre><p>すると、何もしなくてもテストのスコアが0.94を上回ります。これが何を意味するかというと、トランプ現大統領が勝ったCountyとヒラリー候補が得票を伸ばしたCountyの国勢調査のデータに大きな差異があり、モデルがその差異に注目して、選挙結果を的確に判断したということでしょう。さて、どんなデータをモデルは使ったのでしょうか。</p><pre>rfc_features = pd.merge(pd.DataFrame(rfc.feature_importances_, <br>                                     index=X.iloc[:, 2:].columns, <br>                                     columns=[&quot;importance&quot;]<br>                                    ).sort_values(by=&quot;importance&quot;,<br>                                                  ascending=False),<br>                        var_description, <br>                        how=&quot;left&quot;,<br>                        right_index=True, <br>                        left_index=True)</pre><pre>fig, ax = plt.subplots(nrows=5, ncols=4, figsize=(20, 20))<br>fig.suptitle(&quot;Random Forest Top Features&quot;, fontsize=30)<br>for i in range(20):<br>    bp = ax[i//4, i%4].boxplot([X.loc[y==1, rfc_features.index[i]],<br>                                X.loc[y==0, rfc_features.index[i]]],<br>                               vert=False,<br>                               labels=[&quot;T&quot;, &quot;H&quot;],<br>                               notch=True, <br>                               patch_artist=True,<br>                               widths=0.7<br>                              )<br>    for patch, color in zip(bp[&#39;boxes&#39;], [&quot;red&quot;, &quot;blue&quot;]):<br>        patch.set_facecolor(color)<br>        patch.set_alpha(0.6)</pre><pre>    ax[i//4, i%4].set_yticklabels([])<br>    ax[i//4, i%4].set_title(&quot;\n&quot;.join(wrap(rfc_features.label[i],<br>                                           35)),<br>                            fontsize=18)<br>plt.tight_layout()<br>fig.subplots_adjust(top=0.9)<br>plt.show()</pre><p>民主党（ヒラリー候補）は青、共和党（トランプ現大統領）は赤が党の色です。X軸は人口/世帯数に占める特定のグループの割合です。例えば一番に来ているのは白人人口の非ヒスパニック人口に占める割合で、現大統領を支持したCountyは70％以上に集中しているのに対し、ヒラリー候補を支持した地域では40~75%が厚くなっています。二番目は公共交通機関を使って通勤する人の比率（母数は16歳以上の労働者）で、赤いCountyではほぼ公共交通手段が無いのでしょうね。三番目は5~9区画の集合住宅に住む世帯の割合、これは都市部の多い青いCountyで比率が高くなっています。四番目は黒人人口の非ヒスパニック人口に占める割合で、一番の白人比率と正反対ですね。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4x9PEis47Wy-oieuUmiBw.png" /><figcaption>Source: US Census</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*3L1hQdlHx-W2l4M2ZJeiGw.png" /><figcaption>Source: US Census</figcaption></figure><p>ROCカーブを見ると、左上の隅にぴったりくっつく理想的なカーブに近いですね。</p><p>なお、Confusion Matrixを見ると若干偽陽性（ヒラリー候補の勝った地区でトランプ現大統領の価値を予測）が偽陰性より高いのですが、これは赤いCountyの数が青いCountyより多く、クラス間のバランスが悪いことも作用しているところでしょうか。（青い地区は都市部に多く、County数は少ないものの総人口が少なくはありません）</p><p>今回260の変数を使ったので、説明変数間での相関もあり、解釈が一筋縄で行きません。ここから変数を減らしてゆくことを考えます。使うのはEnsamble MethodのうちBoostingと呼ばれるもので、最小化するコスト関数の中にモデルを縛るための項を導入します。一般にoverfittingを抑えることに使われますが、変数が少なくなることで結果の解釈が容易になります。</p><pre>xgc_scores = {}<br>xgc_feature_sets = []<br>k=0<br>for i in range(0, 100, 10):<br>    for j in range(0, 100, 10):<br>        xgc = XGBClassifier(reg_alpha=i, reg_lambda=j)<br>        xgc.fit(X_train_scaled, y_train)</pre><pre>xgc_features = pd.merge(pd.DataFrame(<br>                                xgc.feature_importances_, <br>                                index=X.iloc[:, 2:].columns,<br>                                columns=[&quot;importance&quot;]<br>                                    ).sort_values(by=&quot;importance&quot;,<br>                                                  ascending=False), <br>                                var_description, <br>                                how=&quot;left&quot;,<br>                                right_index=True, <br>                                left_index=True)<br>        xgc_scores[k] = [i,<br>                         j,<br>                         xgc.score(X_train_scaled, y_train),<br>                         xgc.score(X_test_scaled, y_test),<br>                         np.sum(xgc_features.importance&gt;0)]<br>        xgc_feature_sets.append(xgc_features)<br>        k += 1</pre><pre>xgc_reg_score = pd.DataFrame(xgc_scores, <br>                             index=[&quot;alpha&quot;,<br>                                    &quot;lambda&quot;,<br>                                    &quot;train&quot;,<br>                                    &quot;test&quot;,<br>                                    &quot;n_features&quot;<br>                                   ]).T</pre><pre>plt.scatter(xgc_reg_score.n_features, <br>            xgc_reg_score.train,<br>            s=10<br>           )<br>plt.scatter(xgc_reg_score.n_features,<br>            xgc_reg_score.test,<br>            s=10<br>           )<br>plt.title(&quot;XGBoost Classifier No of Features and Scores&quot;)<br>plt.ylabel(&quot;Accuracy Score&quot;)<br>plt.xlabel(&quot;Number of Features&quot;)<br>plt.xlim(170, 0)<br>plt.legend([&quot;Train&quot;,&quot;Test&quot;])<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*dDlEe09VT-pBXAmqBHyLbA.png" /><figcaption>Source: US Census</figcaption></figure><p>縛りを強くしてゆくに従い、変数の数が減ってゆくのがわかります。テスト用データのスコアからは変数が50程度まで減ったところでもモデルの正確性は落ちず、訓練用データのスコアとの差が縮まりoverfittingが解消されています。変数が15になったところでもスコアは0.9と高い水準です。ここで、絞り込まれた変数に何が入っているのか見てみましょう。</p><pre>fig, ax = plt.subplots(nrows=5, ncols=3, figsize=(20, 20))<br>fig.suptitle(&quot;Regularized XGBoost Top Features&quot;, fontsize=30)<br>for i in range(15):<br>    ax[i//3, i%3].hist(X.loc[y==1, xgc_feature_sets[-1].index[i]],<br>                       color=&quot;red&quot;,<br>                       alpha=0.2, <br>                       density=True)<br>    ax[i//3, i%3].hist(X.loc[y==0, xgc_feature_sets[-1].index[i]], <br>                       color=&quot;blue&quot;,<br>                       alpha=0.2, <br>                       density=True)<br>    ax[i//3, i%3].set_yticklabels([])<br>    ax[i//3, i%3]<br>        .set_title(&quot;\n&quot;<br>        .join(wrap(xgc_feature_sets[-1].label[i]+&quot;: &quot;+&quot;{:0.2f}&quot;<br>             .format(xgc_feature_sets[-1].importance[i]),40)),<br>                   fontsize=20)<br>    <br>plt.tight_layout()<br>fig.subplots_adjust(top=0.9)<br>plt.show()</pre><p>先ほどのRandom Forestの変数のチャートは、260のうち上位20を選んだものでしたが、この下の15の変数はモデルの全てです。3番と5番は白人人口の比率に関するもので、合計23％を説明します。単独で1番の公共交通機関使用者比率は18％、個数20戸以上のアパートに住む世帯数はやはり青いCountyの方が多く、13番の5~9戸の集合住宅比率と合わせて17％を説明します。11％を説明する中国系住民の比率は赤いCountyではゼロに近いことが多いようです。6番目は天然資源関係の仕事をする人たちの比率で、赤いCountyでは高くなっています。次は賃貸住宅に住む比率で、やはり都市部の多い青いCountyで高いことが多いようです。8番目は黒人比率、この辺りからかなり説明力は弱くなってきます。9、12、15番目は住宅維持費ですが、青いCountyの方が高い傾向にあるようです。関連して10番目、50万ドルから100万ドルの住宅というのはあまり非都市部には無いことからか、青いCountyが高く出ており、14番目の戸建て住宅の比率は赤いCountyが高いようです。11番目、灯油の使用ですが、これは地域性のあるもので、Maine、Vermont、New Hampshireなど北東部の民主党の支持が強い地域で使うところがあるようです。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCJnfK4anMomC4M7Mu7FnA.png" /><figcaption>Source: US Census</figcaption></figure><p>何となくヒラリー候補支持層とトランプ現大統領の支持層が住む地域の違いが感じられてきたでしょうか。あるCountyについて15の変数が与えられるだけで、9割がたどちらか当てられてしまうというのは、この国がいかに分断されているかを示すものですね。</p><p>ちなみに、モデルがどこの予想を外すか見てみましょう。地図の青い部分はモデルが赤を予想して実際は青かった地域、赤はその逆です。色が濃いほど間違い率が高くなります。例えばMiamiは全ての試行でモデルはヒラリー候補の勝利を予想し、実際はトランプ現大統領が勝ちました。Maineの沿岸部は民主党がほぼ全てのCountyを取りましたが、接戦で、モデルが間違えるのも仕方がないところ。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8USmkurajSa7bjupd99enw.png" /><figcaption>Source: US Census</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*z5sgawOQ8byBXDW-WK9y-Q.png" /><figcaption>Source: US Census</figcaption></figure><p>DCの周辺部を見てみると、Marylandの成績は良い方なのですが、青を予想して共和党が勝った地域が多いようです。逆にVirginiaでは民主党がモデルの予想を覆して、接戦に勝利することができたCountyが散見します。Pennsylvania南東部からNew Jerseyにかけてもモデルには難しい予測だったようです。</p><p>というわけで、皆さんもちゃんと投票に行きましょう。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3baf0bf5ba3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/data-science%E5%A4%A7%E7%B5%B1%E9%A0%98%E9%81%B8%E6%8C%99%E3%82%92%E8%A6%8B%E3%81%BE%E3%81%97%E3%81%9F-3baf0bf5ba3e">Data Science大統領選挙を見ました</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Split with Scikit-learn]]></title>
            <link>https://medium.com/keita-starts-data-science/time-series-split-with-scikit-learn-74f5be38489e?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/74f5be38489e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-data]]></category>
            <category><![CDATA[split]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 22:02:23 GMT</pubDate>
            <atom:updated>2019-08-15T22:02:23.465Z</atom:updated>
            <content:encoded><![CDATA[<p>In time series machine learning analysis, our observations are not independent, and thus we cannot split the data randomly as we do in non-time-series analysis. Instead, we usually split observations along with the sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J3uLoLH-vFX2Eyuf" /><figcaption>Photo by <a href="https://unsplash.com/@sonjalangford?utm_source=medium&amp;utm_medium=referral">Sonja Langford</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We split data into training set and test set in everyday machine learning analyses, and oftentimes we use scikit-learn’s random splitting function.</p><pre>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y)</pre><p>In time series analysis, however, we are not able to use this simple command, since observations in our time series datasets are not independent. The characteristics of time series data, such as autoregressive nature, trend, seasonality, or cyclicality, would not allow a random split to be valid. As a simple example, if your observations are autocorrelated, having an observation at time <em>t </em>in the training set and another observation at time <em>t+1</em> in the test set would cause a trouble. A model which knows the former naturally predict the latter well. In that case, the test score will be too optimistic about the predictive power of the model.</p><p>We separate the test data from training data as a certain part of the end of the dataset. If you have observation over 10 years, for example, you may use first 7 years for training and the last 3 years for testing the model. The code is simple.</p><pre>X_train = X[:int(X.shape[0]*0.7)]<br>X_test = X[int(X.shape[0]*0.7):]<br>y_train = y[:int(X.shape[0]*0.7)]<br>y_test = y[int(X.shape[0]*0.7):]</pre><p>In this way we can train our models with less concerns about the validation. The same can be said about hyper-parameter tuning through cross-validation. The basic approach for that in non-time-series data is called K-fold cross-validation, and we split the training set into <em>k</em> segments; we use <em>k-1</em> sets for training for a model with a certain set of hyper-parameters and measure the performance over the remaining set. We try it for <em>k</em> times over different combination of segments. For this scikit-learn’s <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html">GridSearchCV</a> is handy. Yet, for the same reason stated above, we cannot use this convenient function for time series data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*2YREIb_Hv5ZKzUYcWSZZOA.png" /><figcaption><a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_indices.html#sphx-glr-auto-examples-model-selection-plot-cv-indices-py">scikit-learn documentation</a></figcaption></figure><p>Scikit-learn offers a function for time-series validation, <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html">TimeSeriesSplit</a>. The function splits training data into multiple segments. We use the first segment to train the model with a set of hyper-parameter, to test it with the second. Then we train the model with first two chunks and measure it with the third part of the data. In this way we do <em>k-1 </em>times of cross-validation. Grid-search of hyper-parameter with TimeSeriesSplit requires some manual coding.</p><pre>from <a href="https://scikit-learn.org/stable/modules/classes.html#module-sklearn.model_selection">sklearn.model_selection</a> import TimeSeriesSplit<br>tscv = TimeSeriesSplit(n_splits=5)<br>i = 1<br>score = []<br>for tr_index, val_index in tscv.split(X_train):<br>    X_tr, X_val = X_train[tr_index], X_train[val_index]<br>    y_tr, y_val = y_train[tr_index], y_train[val_index]<br>    for mf in np.linspace(100, 150, 6):<br>        for ne in np.linspace(50, 100, 6):<br>            for md in np.linspace(20, 40, 5):<br>                for msl in np.linspace(30, 100, 8):<br>                    rfr = RandomForestRegressor(<br>                        max_features=int(mf),<br>                        n_estimators=int(ne),<br>                        max_depth=int(md),<br>                        min_samples_leaf=int(msl))<br>                    rfr.fit(X_tr, y_tr)<br>                    score.append([i,<br>                                  mf, <br>                                  ne,<br>                                  md, <br>                                  msl, <br>                                  rfr.score(X_val, y_val)])<br>    i += 1</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f5be38489e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/time-series-split-with-scikit-learn-74f5be38489e">Time Series Split with Scikit-learn</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science米国Output Gapを測ってみました]]></title>
            <link>https://medium.com/keita-starts-data-science/data-science%E7%B1%B3%E5%9B%BDoutput-gap%E3%82%92%E6%B8%AC%E3%81%A3%E3%81%A6%E3%81%BF%E3%81%BE%E3%81%97%E3%81%9F-2a18ba2adda7?source=rss----574f68d45f6b---4</link>
            <guid isPermaLink="false">https://medium.com/p/2a18ba2adda7</guid>
            <category><![CDATA[output-gap]]></category>
            <category><![CDATA[economy]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[usa]]></category>
            <dc:creator><![CDATA[Keita Miyaki]]></dc:creator>
            <pubDate>Mon, 12 Aug 2019 03:02:25 GMT</pubDate>
            <atom:updated>2019-08-12T03:02:25.353Z</atom:updated>
            <content:encoded><![CDATA[<p>先週の後半、米国の不景気の予測ができないか試行錯誤していたのですが、まともに説明変数を集められる1970年以降の不景気が数える程しかないのが大きなネックになってうまくゆきませんでした。ということで、アウトプット・ギャップの符号を被説明変数にしてモデルを組むことにしました。</p><p>いつものライブラリ、モジュールをインポートします。今回使ったのはRandom Forestでした。手順はデータを集めて標準化、Principal Component Analysisでプロセスして変数を絞り、モデルに突っ込むというストレートな手法です。</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import os<br>import pandas as pd<br>import requests<br>import seaborn as sns</pre><pre>from dotenv import load_dotenv<br>from functools import reduce<br>from sklearn.decomposition import PCA<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import confusion_matrix<br>from sklearn.preprocessing import StandardScaler</pre><pre>%matplotlib inline<br>plt.style.use(&quot;ggplot&quot;)<br>sns.set_context(&quot;talk&quot;)</pre><p>ものぐさなのでデータはFREDから一括で取得できるものだけを。API鍵はgithubを使っているので.gitignoreに入れている.envから読みます。1970年代前半からデータがあるものを探してリストにしました。</p><pre>load_dotenv(&quot;&quot;)<br>FREDkey = os.getenv(&quot;FREDkey&quot;)<br>varlist = [&quot;WILL5000INDFC&quot;,<br>           &quot;NIKKEI225&quot;,<br>           &quot;CPIAUCSL&quot;,<br>           &quot;CPIFABSL&quot;,<br>           &quot;CPIHOSSL&quot;,<br>           &quot;IC4WSA&quot;,<br>           &quot;INDPRO&quot;,<br>           &quot;IPMAN&quot;,<br>           &quot;HOUST&quot;,<br>           &quot;HSN1F&quot;,<br>           &quot;RELACBW027SBOG&quot;,<br>           &quot;MSPNHSUS&quot;,<br>           &quot;USSTHPI&quot;,<br>           &quot;AHETPI&quot;,<br>           &quot;PCE&quot;,<br>           &quot;PCEND&quot;,<br>           &quot;DAUTOSAAR&quot;,<br>           &quot;PI&quot;,<br>           &quot;A229RX0&quot;,<br>           &quot;DEXJPUS&quot;,<br>           &quot;DTWEXM&quot;,<br>           &quot;DGS30&quot;,<br>           &quot;DGS10&quot;,<br>           &quot;DGS2&quot;,<br>           &quot;DGS5&quot;,<br>           &quot;DTB3&quot;,<br>           &quot;MORTGAGE30US&quot;,<br>           &quot;AAA&quot;,<br>           &quot;BAA&quot;,<br>           &quot;BAMLCC0A0CMTRIV&quot;,<br>           &quot;FEDFUNDS&quot;,<br>           &quot;TB3SMFFM&quot;,<br>           &quot;UMCSENT&quot;,  <br>           &quot;CIVPART&quot;,<br>           &quot;TCU&quot;,<br>           &quot;UNRATE&quot;,<br>           &quot;LNS14000002&quot;,<br>           &quot;LNS15000000&quot;,<br>           &quot;UEMPMEAN&quot;,<br>           &quot;USCONS&quot;,<br>           &quot;NFCI&quot;,<br>           &quot;USRECDM&quot;,<br>           &quot;GDPPOT&quot;,<br>           &quot;GDPC1&quot;,<br>           &quot;GOLDPMGBD228NLBM&quot;,<br>           &quot;WTISPLC&quot;,<br>           &quot;CMRMTSPL&quot;,<br>           &quot;TERMCBAUTO48NS&quot;,<br>           &quot;TERMCBPER24NS&quot;,<br>           &quot;NONREVSL&quot;,<br>           &quot;CEFDFSA066MSFRBPHI&quot;,<br>           &quot;M1SL&quot;,<br>           &quot;MABMM301USM189S&quot;,<br>           &quot;TOTALSA&quot;,<br>           &quot;INTDSRUSM193N&quot;,<br>           &quot;PSAVERT&quot;,<br>           &quot;TOTCI&quot;,<br>           &quot;TOTLL&quot;,<br>           &quot;TOTBKCR&quot;,<br>           &quot;DPRIME&quot;,<br>           &quot;MSACSR&quot;,<br>           &quot;PPIACO&quot;,<br>           &quot;PERMIT&quot;,<br>           &quot;DSPIC96&quot;,<br>           &quot;TLAACBW027SBOG&quot;,<br>           &quot;M12MTVUSM227NFWA&quot;,<br>           &quot;AWHMAN&quot;,<br>           &quot;CCSA&quot;,<br>           &quot;TCD&quot;,<br>           &quot;CSCICP03USM665S&quot;<br>          ]</pre><p>API callをfor loopで。全てのデータを日時に直し、まとめてから後に週次に。先に週次で取得すると、データの曜日が違うと面倒なので、これもものぐさです。</p><pre>datalist=[]<br>for var in varlist:<br>    resp = requests.get(<br>        &quot;<a href="https://api.stlouisfed.org/fred/series/observations?series_id={}&amp;api_key={}&amp;file_type=json">https://api.stlouisfed.org/fred/series/observations?series_id={}&amp;api_key={}&amp;file_type=json</a>&quot;<br>        .format(var, <br>                FREDkey))<br>    df = pd.DataFrame(resp.json()[&#39;observations&#39;])<br>    df.date = pd.to_datetime(df.date)<br>    df = df.loc[df.value!=&quot;.&quot;]<br>    df.value = df.value.astype(float)<br>    df.index = df.date<br>    df.drop(columns=[&quot;realtime_end&quot;, &quot;realtime_start&quot;, &quot;date&quot;],<br>            axis=1,<br>            inplace=True)<br>    df.columns=[var]<br>    df= df.resample(&quot;1D&quot;).interpolate(method=&#39;linear&#39;)<br>    datalist.append(df)<br>df_merged = reduce(lambda left, right: pd.merge(left, right, on=&#39;date&#39;, how=&#39;outer&#39;), datalist)</pre><p>Yield curveの2-10年、10-30年や株式インデックスのボラティリティを計算し、アウトプット・ギャップの被説明変数を作ります。</p><pre>df_merged[&quot;2-10&quot;] = df_merged.DGS10 - df_merged.DGS2<br>df_merged[&quot;10-30&quot;] = df_merged.DGS30 - df_merged.DGS10<br>df_merged[&quot;positive_gap&quot;] = df_merged.GDPC1.pct_change(365) - df_merged.GDPPOT.pct_change(365) &gt; 0<br>df_merged[&quot;gap&quot;] = df_merged.GDPC1.pct_change(365) - df_merged.GDPPOT.pct_change(365)<br>df_WILL5000_5d_vol = df_merged.WILL5000INDFC.pct_change(1).rolling(5).std()<br>df_WILL5000_30d_vol = df_merged.WILL5000INDFC.pct_change(1).rolling(30).std()</pre><pre>df_WILL5000_5d_vol= df_WILL5000_5d_vol.loc[df_merged.DGS30&gt;-10].resample(&quot;1W&quot;).mean()<br>df_WILL5000_30d_vol= df_WILL5000_30d_vol.loc[df_merged.DGS30&gt;-10].resample(&quot;1W&quot;).mean()<br>df_merged = df_merged.loc[df_merged.DGS30&gt;-10].resample(&quot;1W&quot;).mean()</pre><p>変数ごとに、変化比率を使うものと差を取るものを分けて、</p><pre>percent = [&quot;WILL5000INDFC&quot;,<br>           &quot;NIKKEI225&quot;,<br>           &quot;CPIAUCSL&quot;, <br>           &quot;CPIFABSL&quot;,<br>           &quot;CPIHOSSL&quot;,<br>           &quot;IC4WSA&quot;,<br>           &quot;INDPRO&quot;,<br>           &quot;IPMAN&quot;,<br>           &quot;HOUST&quot;,<br>           &quot;HSN1F&quot;,<br>           &quot;RELACBW027SBOG&quot;,<br>           &quot;MSPNHSUS&quot;,<br>           &quot;USSTHPI&quot;,<br>           &quot;AHETPI&quot;,<br>           &quot;PCE&quot;,<br>           &quot;PCEND&quot;,<br>           &quot;DAUTOSAAR&quot;,<br>           &quot;A229RX0&quot;,<br>           &quot;DEXJPUS&quot;,<br>           &quot;DTWEXM&quot;,<br>           &quot;GOLDPMGBD228NLBM&quot;,<br>           &quot;WTISPLC&quot;,<br>           &quot;BAMLCC0A0CMTRIV&quot;,<br>           &quot;CMRMTSPL&quot;,<br>           &quot;NONREVSL&quot;,<br>           &quot;M1SL&quot;,<br>           &quot;MABMM301USM189S&quot;,<br>           &quot;TOTALSA&quot;,<br>           &quot;TOTCI&quot;,<br>           &quot;TOTLL&quot;,<br>           &quot;TOTBKCR&quot;,<br>           &quot;PPIACO&quot;,<br>           &quot;PERMIT&quot;,<br>           &quot;DSPIC96&quot;,<br>           &quot;TLAACBW027SBOG&quot;,<br>           &quot;M12MTVUSM227NFWA&quot;,<br>           &quot;PI&quot;,<br>           &quot;AWHMAN&quot;,<br>           &quot;CCSA&quot;,<br>           &quot;TCD&quot;,<br>           &quot;UEMPMEAN&quot;,<br>           &quot;LNS15000000&quot;,<br>           &quot;USCONS&quot;<br>          ]</pre><pre>actual = [&quot;DGS30&quot;,<br>          &quot;DGS10&quot;,<br>          &quot;DGS2&quot;,<br>          &quot;DGS5&quot;,<br>          &quot;DTB3&quot;,<br>          &quot;MORTGAGE30US&quot;,<br>          &quot;AAA&quot;,<br>          &quot;BAA&quot;,<br>          &quot;FEDFUNDS&quot;,<br>          &quot;TB3SMFFM&quot;,<br>          &quot;UMCSENT&quot;,  <br>          &quot;CIVPART&quot;,<br>          &quot;TCU&quot;,<br>          &quot;UNRATE&quot;,<br>          &quot;LNS14000002&quot;,<br>          &quot;NFCI&quot;,<br>          &quot;2-10&quot;,<br>          &quot;10-30&quot;,<br>          &quot;gap&quot;,<br>          &quot;TERMCBAUTO48NS&quot;,<br>          &quot;TERMCBPER24NS&quot;,<br>          &quot;CEFDFSA066MSFRBPHI&quot;,<br>          &quot;INTDSRUSM193N&quot;,<br>          &quot;PSAVERT&quot;,<br>          &quot;DPRIME&quot;,<br>          &quot;MSACSR&quot;,<br>          &quot;CSCICP03USM665S&quot;<br>         ]</pre><p>変化率、差を求めるfunctionを書いて使ってゆきます。変化率の差、差の差も取ってみます。</p><pre>def change(df, percent, actual, period):<br>    df_actual = df[actual].diff(period).fillna(method=&#39;ffill&#39;)</pre><pre>df_percent = df[percent].pct_change(period).fillna(method=&#39;ffill&#39;)<br>    df_concat = pd.concat([df_actual, df_percent], axis=1)<br>    df_concat.columns = [str(col) + &#39;_{}&#39;.format(period) for col in df_concat.columns]<br>    return df_concat</pre><pre>week = change(df_merged, percent, actual, 1)<br>week_week = week.diff(1).add_suffix(&quot;_1&quot;)<br>month = change(df_merged, percent, actual, 4)<br>month_month = month.diff(4).add_suffix(&quot;_4&quot;)<br>three_m = change(df_merged, percent, actual, 13)<br>three_three = three_m.diff(13).add_suffix(&quot;_13&quot;)<br>six_m = change(df_merged, percent, actual, 26)<br>six_six = six_m.diff(26).add_suffix(&quot;_26&quot;)<br>one_y = change(df_merged, percent, actual, 52)</pre><p>そして全て結合して一つのDataFrameに。最初の1年間はNaNがあるので使いません。</p><pre>X = pd.concat([week, <br>               week_week, <br>               month, <br>               month_month, <br>               three_m, <br>               three_three, <br>               six_m, <br>               six_six, <br>               one_y,<br>               df_merged[actual].fillna(method=&quot;ffill&quot;),<br>               df_merged[actual].fillna(method=&quot;ffill&quot;).shift(1),<br>               df_merged[actual].fillna(method=&quot;ffill&quot;).shift(4),<br>               df_merged[actual].fillna(method=&quot;ffill&quot;).shift(13),<br>               df_merged[actual].fillna(method=&quot;ffill&quot;).shift(26),<br>               df_merged[actual].fillna(method=&quot;ffill&quot;).shift(52),<br>               df_WILL5000_5d_vol,<br>               df_WILL5000_30d_vol<br>              ], axis=1)[52:]</pre><p>6ヶ月予測、1年予測をするための被説明変数を作ります。</p><pre>y6m = df_merged.positive_gap.shift(-26)[X.index].fillna(method=&quot;ffill&quot;).apply(lambda x: 1 if x&gt;0.5 else 0)<br>y12m = df_merged.positive_gap.shift(-52)[X.index].fillna(method=&quot;ffill&quot;).apply(lambda x: 1 if x&gt;0.5 else 0)</pre><p>説明変数を標準化して、PCAで処理します。</p><pre>r = StandardScaler()<br>X_scaled = pd.DataFrame(scaler.fit_transform(X))</pre><pre>pca = PCA()<br>X_pca = pca.fit_transform(X_scaled)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*5G9SOAiz8mGyve_NuI6Hsg.png" /><figcaption>Source: FRED</figcaption></figure><p>150くらいのcomponentsで9割がたのvarianceが説明できそうです。もう少し減らしてもいいのですが、とりあえず150でやってみました。前半7割を訓練用、後半3割をテスト用データとして切り分けます。</p><pre>n_pc = 150<br>X_train = X_pca[:int(X_pca.shape[0]*0.7), :n_pc]<br>X_test = X_pca[int(X_pca.shape[0]*0.7):, :n_pc]<br>y6m_train = y6m[:int(X_pca.shape[0]*0.7)]<br>y6m_test = y6m[int(X_pca.shape[0]*0.7):]<br>y12m_train = y12m[:int(X_pca.shape[0]*0.7)]<br>y12m_test = y12m[int(X_pca.shape[0]*0.7):]</pre><p>さてRandom Forestでモデルを組んでみます。他にもSupport Vector MachineやらXG Boostやらいろいろ取り組んでみたのですが、Random Forestが最も成績が良かったのと、tuningしやすかったので。</p><pre>clf = RandomForestClassifier(max_features=50, <br>                             n_estimators=10, <br>                             max_depth=10, <br>                             min_samples_leaf=70, <br>                             random_state=0<br>                            )<br>clf.fit(X_train, y6m_train)</pre><pre>pred = pd.DataFrame(clf.predict_proba(X_pca[:, :n_pc])[:, 1])<br>pred.set_index(X.index, inplace=True)<br>pred.columns = [&quot;pred&quot;]<br>fig = plt.figure(figsize=(16,4))<br>ax = plt.plot(pd.merge(df_merged.positive_gap[X_scaled.index], pred, on=&quot;date&quot;))<br>plt.title(&quot;6-month Forecast: US Positive Output Gap Probability&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.legend([&quot;Positive Output Gap&quot;, &quot;Prediction&quot;], loc=4)<br>plt.show()</pre><p>訓練データは2006年2月分までで、それ以降はテストです。6ヶ月先のアウトプット・ギャップの符号の予測、まぁ何となく上手く行っているような気がしませんか？2010年からの回復をちゃんと予測しているし、その後経済成長率が潜在成長率すれすれで下回った3度ほどは予測できなくても仕方ない一方、2016年前半のネガティブ・ギャップは当てています。これによると2019年中にアウトプット・ギャップはネガティブになりそうな…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oMDdyLqbeYJ2Ov84zuvVfw.png" /><figcaption>Source: FRED</figcaption></figure><p>12ヶ月予測も同じくRandom Forestで書いてみます。</p><pre>clf = RandomForestClassifier(max_features=120, <br>                             n_estimators=60, <br>                             max_depth=10, <br>                             min_samples_leaf=100,<br>                             random_state=0<br>                            )<br>clf.fit(X_train, y12m_train)<br>print(confusion_matrix(clf.predict(X_test), y12m_test))<br>print(&quot;train:&quot;, clf.score(X_train, y12m_train))<br>print(&quot;test:&quot;, clf.score(X_test, y12m_test))</pre><pre>pred = pd.DataFrame(clf.predict_proba(X_pca[:, :n_pc])[:, 1])<br>pred.set_index(X.index, inplace=True)<br>pred.columns = [&quot;pred&quot;]<br>fig = plt.figure(figsize=(16,4))<br>ax = plt.plot(pd.merge(df_merged.positive_gap[X_scaled.index], pred, on=&quot;date&quot;))<br>plt.title(&quot;12-month Forecast: US Positive Output Gap Probability&quot;)<br>plt.ylabel(&quot;Probability&quot;)<br>plt.legend([&quot;Positive Output Gap&quot;, &quot;Prediction&quot;], loc=4)<br>plt.show()</pre><p>12ヶ月の予測は6ヶ月に比べて格段に難しいです。accuracyは8割未満ですが、まぁこれも何とか見られるモデルになったのではないかと思います。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3leghXYX9NGw3EcqgXtraQ.png" /><figcaption>Source: FRED</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a18ba2adda7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/keita-starts-data-science/data-science%E7%B1%B3%E5%9B%BDoutput-gap%E3%82%92%E6%B8%AC%E3%81%A3%E3%81%A6%E3%81%BF%E3%81%BE%E3%81%97%E3%81%9F-2a18ba2adda7">Data Science米国Output Gapを測ってみました</a> was originally published in <a href="https://medium.com/keita-starts-data-science">Keita Starts Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>