<?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[Stories by Zaki Nurkholis on Medium]]></title>
        <description><![CDATA[Stories by Zaki Nurkholis on Medium]]></description>
        <link>https://medium.com/@mouse3mic3?source=rss-c81b53ecc773------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sGjozlz3Uv3zJtq-AAGgsQ.png</url>
            <title>Stories by Zaki Nurkholis on Medium</title>
            <link>https://medium.com/@mouse3mic3?source=rss-c81b53ecc773------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:59:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mouse3mic3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Panduan Praktis Pemrograman R — Analisis Regresi Linear]]></title>
            <link>https://medium.com/@mouse3mic3/panduan-praktis-pemrograman-r-analisis-regresi-linear-accc96344501?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/accc96344501</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Fri, 17 May 2024 02:24:43 GMT</pubDate>
            <atom:updated>2024-05-17T02:24:43.552Z</atom:updated>
            <content:encoded><![CDATA[<h3>Panduan Praktis Pemrograman R — Analisis Regresi Linear</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FazKWYS08CTgNg0V" /><figcaption>Photo by <a href="https://unsplash.com/@wezlar11?utm_source=medium&amp;utm_medium=referral">Dean Pugh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Artikel ini adalah bagian dari seri panduan praktis pemrograman R. Beberapa topik akan dibahas pada artikel di masa mendatang, termasuk inferensi populasi dan analisis regresi, semua dalam Bahasa Indonesia.</p><p>Tanda koma menyatakan ribuan, tanda titik menyatakan desimal.</p><p>Data yang digunakan dapat diakses <a href="https://docs.google.com/spreadsheets/d/1Dz-9ScpeFeoDR2WqG75Zd0A02v1Fa_Su/edit?usp=sharing&amp;ouid=117358761750579055609&amp;rtpof=true&amp;sd=true">di sini</a>.</p><h3>Variabel Dependen dan Independen</h3><p>Variabel independen (bebas, prediktor, X) adalah variabel yang dianggap tidak dipengaruhi oleh variabel lainnya.</p><p>Variabel dependen (terikat, respon, Y) adalah variabel yang dianggap dipengaruhi variabel lainnya.</p><p>Sebagai contoh, dalam penelitian hubungan merokok dan penyakit jantung, status merokok merupakan variabel independen yang diduga menyebabkan sakit jantung (dependen).</p><h3>Analisis Korelasi</h3><p>Korelasi adalah ukuran keeratan hubungan antara dua variabel berskala interval atau rasio (numerik). Koefisien korelasi populasi dilambangkan dengan ρ (<em>rho</em>), sedangkan korelasi sampel <em>r</em>.</p><p>Koefisien korelasi memiliki rentang -1 hingga 1. Semakin jauh nilainya dari 0, semakin erat hubungan kedua variabel. Nilai korelasi 0 menunjukkan tidak ada hubungan linear antara kedua variabel (berubahnya nilai salah satu variabel tidak memengaruhi variabel lainnya).</p><ul><li><strong>Nilai korelasi positif </strong>menunjukkan hubungan searah antara dua variabel. Jika nilai salah satu variabel meningkat, maka variabel lainnya juga meningkat.</li><li><strong>Nilai korelasi negatif</strong> menunjukkan hubungan terbalik antara dua variabel. Jika nilai salah satu variabel meningkat, maka variabel lainnya menurun, dan sebaliknya.</li></ul><p>Nilai korelasi dapat dikelompokkan sebagai berikut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*DQkZgTBIBMNlDkSFwVeehw.png" /></figure><p>Nilai kuadrat korelasi disebut koefisien determinasi r². Nilai ini dapat diartikan sebagai besarnya varians pada variabel Y (dependen) yang dapat dijelaskan oleh variabel X (independen).</p><p><strong>Cara Analisis</strong></p><p>Terdapat banyak jenis koefisien korelasi yang dapat digunakan. Korelasi Pearson paling umum digunakan dalam analisis regresi, Spearman adalah korelasi nonparametrik, Kendall-tau digunakan dalam model linear lain.</p><p>Anda juga dapat melakukan uji hipotesis untuk mengetahui apakah koefisien korelasi antara dua variabel signifikan berbeda dari nol. Hipotesis yang digunakan adalah</p><ul><li>H0: ρ = 0 (tidak ada korelasi antara kedua variabel)</li><li>Ha: ρ ≠ 0 (ada korelasi antara kedua variabel)</li></ul><p>Gunakan fungsi<em> cor.test(…)</em> untuk menghitung korelasi antara dua objek. Fungsi cor(…) menerima argumen <em>method</em> yang dapat Anda gunakan untuk menentukan jenis korelasi yang diinginkan.</p><blockquote><strong><em>Koefisien Korelasi — Contoh 1</em></strong></blockquote><pre>x = c(50, 54, 58)<br>y = c(70, 76, 81)<br>cor.test(x, y, method = &#39;pearson&#39;)<br>cor.test(x, y, method = &#39;spearman&#39;)<br>cor.test(x, y, method = &#39;kendall&#39;)<br>##         Pearson&#39;s product-moment correlation<br>## <br>## data:  x and y<br>## t = 19.053, df = 1, p-value = 0.03338<br>## alternative hypothesis: true correlation is not equal to 0<br>## sample estimates:<br>##       cor <br>## 0.9986254<br>## dst...</pre><blockquote><em>Nilai korelasi Pearson yang diestimasi adalah 0.9986 (korelasi sangat kuat). Nilai p-value &lt; α = 5% mengindikasikan penolakan H0. Artinya, terdapat korelasi signifikan antara variabel x dan y.</em></blockquote><blockquote><strong><em>Koefisien Korelasi — Contoh 2 (Data: TaiwanEstate)</em></strong></blockquote><blockquote><em>Peneliti menduga bahwa semakin jauh jarak stasiun MRT, harga sebuah properti akan semakin murah, dan sebaliknya. Hal ini karena moda transportasi umum menjadi perhatian khusus bagi penduduk Taiwan.</em></blockquote><pre>cor.test(estate$JarakStasiunMRT, estate$Harga) <br>##         Pearson&#39;s product-moment correlation<br>##<br>## data:  estate$JarakStasiunMRT and estate$Harga<br>## t = -18.998, df = 412, p-value &lt; 2.2e-16<br>## alternative hypothesis: true correlation is not equal to 0<br>## 95 percent confidence interval:<br>##  -0.7315510 -0.6283591<br>## sample estimates:<br>##        cor <br>## -0.6833532</pre><p>Nilai korelasi Pearson yang diestimasi adalah -0.683 (korelasi kuat). Tanda negatif menunjukkan bahwa semakin tinggi jarak stasiun MRT, semakin rendah harga properti (sesuai dugaan peneliti). Nilai p-value &lt; α = 5% mengindikasikan korelasi signifikan antara jarak stasiun MRT dan harga properti.</p><h3>Tentang Analisis Regresi Linear</h3><p>Analisis regresi adalah analisis terhadap dua jenis variabel, yakni variabel independen dan variabel dependen, dengan asumsi bahwa variabel independen (X) mempengaruhi variabel dependen (Y). Pengaruh yang diberikan bersifat linear, artinya pasangan data X dan Y membentuk garis lurus pada sebuah <em>scatterplot</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*VfkKD0eqTZGmepOTu9M7mw.png" /></figure><p>Tujuan utama dari analisis regresi adalah mengetahui pola keeratan hubungan antar variabel independen dan dependen, mengestimasi (menduga) pengaruh variabel independen terhadap dependen, dan memprediksi nilai variabel dependen berdasarkan nilai variabel independen.</p><p>Sebagai contoh, analisis regresi dapat digunakan untuk melihat adanya hubungan antara lama pendidikan (X) dan penghasilan (Y) seseorang. Model regresi yang dibentuk dapat digunakan untuk menduga penghasilan seseorang berdasarkan lama pendidikan yang diketahui.</p><p>Dalam analisis regresi, variabel independen mendahului (terjadi sebelum) variabel respon. Dimungkinkan pula dua atau lebih variabel independen untuk memengaruhi variabel dependen. Analisis regresi dengan dua atau lebih variabel independen disebut analisis regresi linear berganda.</p><blockquote><strong><em>Analisis Regresi Linear — Data: TaiwanEstate</em></strong></blockquote><blockquote><em>Peneliti tertarik untuk membentuk sebuah model regresi yang dapat menjelaskan perilaku harga properti di Taiwan berdasarkan beberapa prediktor yang dinilai relevan, seperti Periode Transaksi, Usia Bangunan, Humiditas Tahunan, dan sebagainya. Misalnya pemerintah setempat dapat menyesuaikan kebijakan real estate dengan memberikan subsidi pada periode tertentu, atau membantu penjual properti untuk mengetahui harga yang layak dan diminati oleh sebagian pembeli.</em></blockquote><p>Terdapat beberapa asumsi klasik dari analisis regresi linear, yakni Normalitas, Linearitas, dan Independensi.</p><h3><strong>Asumsi Normalitas</strong></h3><p>Asumsi penting dari regresi linear adalah normalitas, yakni variabel respon mengikuti distribusi Normal. Ini juga berarti variabel respon adalah variabel kontinu (bukan kategorik). Anda dapat menguji normalitas variabel dependen melalui histogram, boxplot, atau secara inferensi.</p><blockquote><strong><em>Uji Normalitas Var. Dependen — Data: TaiwanEstate</em></strong></blockquote><blockquote><em>Peneliti melakukan uji normalitas terhadap variabel harga properti dengan metode shapiro-wilk. Harga properti adalah variabel dependen yang diharapkan.</em></blockquote><blockquote><em>Hipotesis yang digunakan adalah:</em></blockquote><blockquote><em>- H0: Harga properti berasal dari populasi Normal</em></blockquote><blockquote><em>- Ha: Harga properti tidak berasal dari populasi Normal</em></blockquote><blockquote><em>dengan taraf signifikansi α = 5%.</em></blockquote><pre>shapiro.test(estate$Harga)<br>##         Shapiro-Wilk normality test<br>## <br>## data:  estate$Harga<br>## W = 0.99489, p-value = 0.1874</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*kILIpciqmwbruw17ab-m7A.png" /></figure><blockquote><em>Nilai p-value &gt; 5% menunjukkan bahwa harga properti berasal dari populasi yang Normal. Asumsi ini dipenuhi. Histogram di bawah juga mendukung pernyataan ini.</em></blockquote><h3>Asumsi Linearitas</h3><p>Linearitas menunjukkan hubungan antar dua variabel yang linear (lurus). Artinya, apabila X berubah, Y juga berubah. Anda dapat membentuk sebuah <em>scatterplot</em> X vs Y untuk melihat adanya linearitas antara keduanya.</p><blockquote><strong><em>Linearitas Prediktor dan Respon — Data: TaiwanEstate</em></strong></blockquote><blockquote><em>Misal dalam analisis regresi ini, peneliti ingin melihat hubungan beberapa prediktor dengan respon. Untuk memudahkan, Anda dapat menggunakan fungsi ggpairs(…) dalam pustaka GGally.</em></blockquote><pre>library(GGally)<br><br># Variabel yang digunakan<br>reg_estate &lt;- estate[c(&#39;Harga&#39;, &#39;UsiaBangunan&#39; , &#39;Kebisingan&#39;, &#39;JarakStasiunMRT&#39;, &#39;NumMinimarket&#39;, &#39;Humiditas&#39;)]<br><br># Sajikan plot berpasangan<br>ggpairs(reg_estate, lower = list(continuous = &quot;smooth&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*B2UWf5VeiqdhhqT7NAsdCg.png" /></figure><blockquote><em>Hasil di atas menunjukkan hubungan setiap pasang variabel (perhatikan baris dan kolom). Pada bagian segitiga bawah, terlihat scatterplot antar setiap pasang variabel beserta garis regresi terbaik. Pada bagian diagonal, terlihat distribusi dari masing-masing variabel. Pada bagian segitiga atas, tersajikan koefisien korelasi Pearson dengan tanda * yang menunjukkan hasil signifikan atau tidak dari uji Korelasi.</em></blockquote><blockquote><em>Linearitas umumnya ditunjukkan dengan garis regresi yang tidak datar dan titik-titik data menyebar di sekitar garis. Hasil ini mungkin sulit untuk dilihat ketika terdapat banyak sekali data yang menyebar.</em></blockquote><blockquote><em>Pada contoh di atas, peneliti tertarik pada kolom pertama, yakni scatterplot antara variabel Harga dengan variabel lainnya. Hubungan linear positif jelas ditunjukkan antara Harga dan NumMinimarket, mengindikasikan bahwa semakin banyak minimarket disekitar properti, semakin tinggi pula harganya. DI sisi lain, hubungan linear negatif ditunjukkan oleh variable Harga dan Usia Bangunan, serta Harga dan Jarak Stasiun MRT. Keduanya memiliki hubungan terbalik dengan Harga bangunan.</em></blockquote><blockquote><em>Dua variabel lainnya, yakni Kebisingan dan Humiditas, terlihat membentuk garis yang relatif datar dengan koefisien korelasi yang tidak signifikan. Keduanya mungkin memiliki hubungan linear yang lemah terhadap Harga Bangunan.</em></blockquote><p>Apabila hubungan X dan Y tidak linear, Anda mungkin dapat melakukan transformasi data atau menggunakan model regresi nonlinear. Anda juga dapat membuang variabel X tersebut dari model regresi.</p><h3>Asumsi Independensi</h3><p>Independensi yang dimaksud adalah independensi antara setiap observasi. Asumsi ini sulit untuk dibuktikan, namun secara umum, apabila pengambilan data dilakukan dengan sampel acak, asumsi ini dapat dianggap dipenuhi.</p><h3>Model Regresi Linear Sederhana</h3><p>Regresi linear ini disebut sederhana karena hanya memodelkan satu variabel independen (X) dan satu variabel dependen (Y). Model regresi linear sederhana dapat dituliskan sebagai</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*okGQDRC-YMWBB9H1xSDpPw.png" /></figure><p>Peneliti berusaha untuk mencari (mengestimasi) nilai parameter populasi β₀ dan β₁ berdasarkan data yang ada. Statistik untuk keduanya dinotasikan dengan b₀ dan b₁.</p><p>Untuk mencari nilai b₀ dan b₁ yang terbaik, metode kuadrat terkecil (<em>least square</em>) sering digunakan. Dalam metode ini, peneliti berusaha untuk meminimumkan nilai kesalahan Σε² sedemikian hingga variabel X dapat menjelaskan Y sebaik mungkin dengan kesalahan yang minimum.</p><h3>Model Regresi Linear Berganda</h3><p>Regresi ini disebut berganda karena memiliki satu variabel dependen yang dijelaskan oleh lebih dari satu variabel independen. Variabel-variabel independen dapat menjelaskan respon secara individu atau secara bersamaan (simultan). Mirip dengan model regresi sederhana, model regresi berganda dituliskan sebagai berikut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*-Tiv7LxFotksEAsARuS_xQ.png" /></figure><p>Koefisien korelasi <em>R</em> umumnya digunakan untuk mengukur keeratan hubungan linear antara semua variabel independen dan dependen secara bersama-sama. Kuadratnya, <em>R2</em>, disebut koefisien determinasi yang diartikan sebagai besarnya variasi dalam respon yang dapat dijelaskan oleh prediktor.</p><h3>Tahapan Analisis Regresi</h3><p>Tahapan dari analisis regresi linear adalah sebagai berikut. Setelah uji asumsi, Anda cukup menggunakan fungsi lm(…) dan summary(…) untuk mendapatkan hasil analisis regresi keseluruhan.</p><p><strong>1.</strong> <strong>Uji Asumsi Klasik</strong></p><p>Lakukan uji asumsi Normalitas dan Linearitas.</p><p><strong>2.</strong> <strong>Pemodelan Regresi</strong></p><p>Estimasi parameter model, yakni konstanta b₀ dan koefisien b₁, b₂, …, bₚ. Gunakan fungsi lm(…) dalam R dengan argumen sebagai berikut.</p><ul><li><strong>Formula<br></strong>Formula menyatakan variabel yang bertindak sebagai respon dan prediktor. Bentuk formula secara umum adalah</li></ul><pre>respon ~ prediktor1 + prediktor2 + ... + prediktorP</pre><ul><li>Apabila Anda ingin menjalankan regresi linear tanpa konstanta, tambahkan -1 di akhir formula.</li><li><strong>Data<br></strong>Data adalah sebuah matriks atau dataframe yang menyimpang semua variabel dalam formula.</li></ul><p>Simpan objek lm(…) dan gunakan fungsi summary(…) untuk menyajikan ringkasan model regresi.</p><pre># Contoh<br>mod1 &lt;- lm(y ~ x) # Fitting model regresi<br>summary(mod1) # Tampilkan hasil analisis regresi</pre><p><strong>3.</strong> <strong>Uji Overall (ANOVA, Simultan, Keseluruhan)</strong></p><p>Uji ANOVA ini digunakan untuk melihat kelayakan model regresi. Model dikatakan layak untuk digunakan apabila terdapat sekurang-kurangnya satu prediktor yang signifikan mempengaruhi respon. Dengan kata lain, terdapat minimal satu koefisien bⱼ yang signifikan berbeda dari 0.</p><p>Hipotesis yang digunakan adalah:</p><ul><li>H0: b₁ = b₂ = … = bₚ = 0<br> (model regresi tidak layak digunakan, tidak ada hubungan linear antara prediktor dan respon)</li><li>Ha: Ada minimal satu bⱼ ≠ 0<br> (model regresi layak digunakan, ada hubungan linear antara prediktor dan respon).</li></ul><p>Apabila uji ini tidak dipenuhi, Anda dapat mencoba untuk menggunakan variabel prediktor lain atau melakukan transformasi variabel.</p><p>4. <strong>Uji Parsial</strong> <strong>Konstanta dan Koefisien</strong></p><p>Uji parsial digunakan untuk mengetahui apakah konstanta dan koefisien masing-masing memberikan kontribusi signifikan terhadap model.</p><p>Uji ini dilakukan dengan hipotesis sebagai berikut.</p><ul><li><strong>Untuk Konstanta β₀<br></strong>H0: β₀ = 0 vs Ha: β₀ ≠ 0<br> (Konstanta tidak signifikan terhadap model regresi)</li><li><strong>Untuk Koefisien<br></strong>H0: βⱼ = 0 vs Ha: βⱼ ≠ 0, untuk setiap j = 1, 2, …, p<br> (Koefisien ke-j tidak signifikan terhadap model regresi)</li></ul><p>Apabila koefisien tidak signifikan, Anda memiliki opsi untuk mengeluarkannya dari model regresi secara bertahap (satu per satu) dari koefisien paling tidak signifikan (nilai p-value terbesar), kemudian menjalankan tahap 2–4 kembali. Metode ini dinamakan <em>backward-elimination</em>.</p><p>Apabila konstanta tidak signifikan, disarankan untuk tetap digunakan.</p><p><strong>5.</strong> <strong>Analisis Residual</strong></p><p>Analisis residual digunakan untuk melihat lebih lanjut apakah model regresi yang diperoleh melanggar asumsi-asumsi diluar asumsi klasik. Residual adalah selisih antara nilai observasi dan nilai prediksi model. Model yang baik umumnya akan memiliki pola residual tertentu, seperti Normalitas dan Homoskedastik.</p><p>Model regresi linear yang diperoleh mungkin baik untuk data yang ada, namun belum tentu memberikan hasil yang baik untuk data di masa mendatang (tidak konsisten).</p><blockquote><strong><em>Model Regresi Berganda — Data: TaiwanEstate</em></strong></blockquote><blockquote><em>Setelah melakukan uji asumsi Normalitas dan Linearitas, peneliti memutuskan untuk memodelkan respon Harga Bangunan (Y) berdasarkan beberapa prediktor, yakni Usia Bangunan (X1), Tingkat Kebisingan (X2), Jarak Stasiun MRT (X3), Banyaknya Minimarket (X4), dan Humiditas/Kelembaban (X5).</em></blockquote><pre>model_1 &lt;- lm(Harga ~ UsiaBangunan + Kebisingan + JarakStasiunMRT + NumMinimarket + Humiditas, data = estate)<br>summary(model_1)</pre><blockquote><strong><em>Koefisien Determinasi (R2)</em></strong></blockquote><blockquote><em>Nilai koefisien determinasi dapat ditemukan pada bagian</em></blockquote><blockquote>## Multiple R-squared: 0.5698, Adjusted R-squared: 0.5645</blockquote><blockquote><em>yang menunjukkan bahwa sebesar 56.98% variasi harga bangunan dapat dijelaskan oleh prediktor yang digunakan, sisanya dijelaskan faktor lain diluar model. Korelasi merupakan akar kuadrat dari R2, yakni sebesar 0.75 (korelasi kuat).</em></blockquote><blockquote><em>Nilai adjusted R2 merupakan modifikasi terhadap R2 dan umumnya memberikan ukuran yang lebih baik karena ia mempertimbangkan baik tidaknya suatu prediktor apabila dimasukkan ke dalam model. Nilai R2 akan selalu meningkat setiap ditambahkannya sebuah prediktor, terlepas apakah prediktor tersebut signifikan atau tidak.</em></blockquote><blockquote><strong><em>Uji Overall</em></strong></blockquote><blockquote><em>Hipotesis yang digunakan adalah</em></blockquote><blockquote><em>- H0: β_UsiaBangunan = β_Kebisingan = … = β_Humiditas = 0<br> (model regresi tidak layak digunakan, tidak ada hubungan linear antara prediktor dan respon)</em></blockquote><blockquote><em>- Ha: Ada βⱼ ≠ 0, j = UsiaBangunan, Kebisingan, …, Humiditas<br> (model regresi layak digunakan, ada hubungan linear antara prediktor dan respon).</em></blockquote><blockquote><em>Hasil uji overall dapat ditemukan pada baris terakhir, yakni</em></blockquote><blockquote>## F-statistic: 108.1 on 5 and 408 DF, p-value: &lt; 2.2e-16</blockquote><blockquote><em>Statistik uji yang digunakan adalah F sebesar 108.1 dengan derajat bebas 5 dan 408. Untuk kemudahan, Anda dapat melihat nilai p-value yang sangat kecil. Artinya data mendukung penolakan H0. Model regresi ini layak untuk digunakan pada taraf signifikansi α = 5%.</em></blockquote><blockquote><strong><em>Uji Parsial</em></strong></blockquote><blockquote><strong><em>- Untuk Konstanta<br></em></strong><em>H0: β₀ = 0 vs Ha: β₀ ≠ 0<br>(Konstanta tidak signifikan terhadap model regresi)</em></blockquote><blockquote><strong><em>- Untuk Koefisien<br></em></strong><em>H0: βⱼ = 0 vs Ha: βⱼ ≠ = 0,<br>untuk setiap j = UsiaBangunan, Kebisingan, …, Humiditas<br>(Koefisien ke-j tidak signifikan terhadap model regresi)</em></blockquote><blockquote><em>Hasil uji parsial dapat ditemukan pada bagian</em></blockquote><pre>## Coefficients:<br>##                   Estimate Std. Error t value Pr(&gt;|t|)    <br>## (Intercept)     376.517675  12.750842  29.529  &lt; 2e-16 ***<br>## UsiaBangunan     -0.873041   0.122323  -7.137 4.39e-12 ***<br>## Kebisingan       -0.691327   0.428108  -1.615    0.107    <br>## JarakStasiunMRT  -0.016858   0.001381 -12.209  &lt; 2e-16 ***<br>## NumMinimarket     4.226701   0.593776   7.118 4.95e-12 ***<br>## Humiditas         0.070553   0.133764   0.527    0.598    <br>## ---<br>## Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1</pre><blockquote><em>Statistik yang digunakan adalah t. Kolom Estimate menunjukkan estimasi konstanta dan koefisien bⱼ, Std. Error dapat diartikan sebagai invers akurasi bⱼ (semakin rendah semakin akurat), dan kolom Pr(&gt;|t|) adalah P-value untuk masing-masing konstanta dan koefisien. Tanda * menunjukkan signifikansi pada taraf α = 5%.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*cN-HEi573_Kyp6YUou22Xw.png" /></figure><blockquote><em>Terdapat dua variabel prediktor yang tidak signifikan masuk model. Pada Bab selanjutnya, akan dibahas lebih lanjut mengenai pemodelan regresi bertahap.</em></blockquote><blockquote><strong><em>Persamaan Regresi</em></strong></blockquote><blockquote><em>Hasil di atas dapat dirangkum dalam sebuah persamaan regresi sebagai berikut.</em></blockquote><blockquote>Harga = 376.52 — (0.873 * Usia) — (0.691 * Kebisingan) — (0.017 * Jarak MRT) + (4.227 * Minimarket) + (0.071 * Humiditas)</blockquote><blockquote>- Ingat bahwa harga bangunan memiliki satuan ribu TWD/ping.</blockquote><blockquote>- Setiap kenaikan 1 tahun usia bangunan, harga bangunan akan menurun sebesar 873 TWD/ping</blockquote><blockquote>- Setiap kenaikan satu dB kebisingan di sekitar bangunan akan mengakibatkan penurunan harga sebesar 691 TWD/ping</blockquote><blockquote>- Setiap kenaikan 1 meter jarak ke stasiun MRT akan mengakibatkan penurunan harga bangunan sebesar 17 TWD/ping.</blockquote><blockquote>- Setiap bertambahnya minimarket di sekitar bangunan akan meningkatkan harga bangunan sebesar 4.2k TWD/ping.</blockquote><blockquote>- Setiap meningkatnya persentase humiditas akan menaikkan harga bangunan sebesar 71 TWD/ping.</blockquote><blockquote><em>Misal peneliti ingin mengetahui harga dasar bangunan, yakni bangunan baru (Usia = 0), tingkat kebisingan kota (Kebisingan = 20dB), jarak yang dekat (JarakMRT = 100m), minimal satu minimarket (NumMinimarket = 1), dan humiditas kota (Humiditas = 20%).</em></blockquote><blockquote><em>Substitusikan ke dalam persamaan regresi di atas dan diperoleh 366.65</em></blockquote><blockquote><em>yang menunjukkan bahwa harga dasar sebuah bangunan di Taiwan adalah 366 650 TWD/ping.</em></blockquote><h3>Regresi Bertahap — Manual</h3><p>Apabila Anda menemui satu atau beberapa variabel prediktor yang tidak signifikan pada Uji Parsial, Anda dapat membentuk model regresi baru dengan mengeluarkan satu prediktor yang “paling tidak signifikan”. Artinya, prediktor dengan statistik uji F terkecil (atau P-value terbesar) dikeluarkan.</p><p>Metode ini diulangi secara terus menerus hingga diperoleh model dengan koefisien yang signifikan sepenuhnya. Pada bab selanjutnya, akan dibahas metode untuk memilih model regresi terbaik.</p><blockquote><strong><em>Model Regresi Berganda — Data: TaiwanEstate (Tanpa Humiditas)</em></strong></blockquote><blockquote><em>Hasil sebelumnya menunjukkan bahwa variabel Humiditas (X5) memiliki P-value terbesar dan tidak signifikan. Oleh karenanya, variabel ini dikeluarkan dari model.</em></blockquote><pre>model_2 &lt;- lm(Harga ~ UsiaBangunan + Kebisingan + JarakStasiunMRT + NumMinimarket, data = estate)<br>summary(model_2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*z1DeFtYrbDhMfaEGYk4cpw.png" /></figure><blockquote><strong><em>Koefisien Determinasi (R2)</em></strong></blockquote><blockquote><em>Nilai koefisien determinasi yang baru adalah sebesar 0.5695, artinya sebanyak 56.95% variasi pada Harga bangunan dijelaskan oleh prediktor yang ada, yakni Usia, Kebisingan, Jarak MRT, dan Minimarket, sisanya dijelaskan faktor diluar model.</em></blockquote><blockquote><strong><em>Uji Overall</em></strong></blockquote><blockquote><em>Nilai P-value pada bagian F-statistics sangat kecil, artinya data mendukung kuat penolakan H0. Model regresi tanpa melibatkan Humiditas layak untuk digunakan.</em></blockquote><blockquote><strong><em>Uji Parsial</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*D3NLaPknl7j73ZxhlPu8Fw.png" /></figure><blockquote><strong><em>Model Regresi Berganda — Data: TaiwanEstate (Tanpa Humiditas dan Kebisingan)</em></strong></blockquote><blockquote><em>Hasil sebelumnya menunjukkan bahwa variabel kebisingan tidak signifikan pada uji parsial. Oleh karenanya, variabel ini akan dikeluarkan dari model selanjutnya.</em></blockquote><pre>model_3 &lt;- lm(Harga ~ UsiaBangunan + JarakStasiunMRT + NumMinimarket, data = estate)<br>summary(model_3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*Nou4UuD5v9ybKZ1l4zL-OA.png" /></figure><blockquote><strong><em>Koefisien Determinasi (R2)</em></strong></blockquote><blockquote><em>Nilai koefisien determinasi yang baru adalah sebesar 0.5668, artinya sebanyak 56.68% variasi pada Harga bangunan dijelaskan oleh prediktor yang ada, yakni Usia, Jarak MRT, dan Minimarket, sisanya dijelaskan faktor diluar model. Nilai ini sedikit menurun dari sebelumnya.</em></blockquote><blockquote><strong><em>Uji Overall</em></strong></blockquote><blockquote><em>Nilai P-value pada bagian F-statistics sangat kecil, artinya data mendukung kuat penolakan H0. Model regresi tanpa melibatkan Humiditas dan Kebisingan layak untuk digunakan.</em></blockquote><blockquote><strong><em>Uji Parsial</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*RFg_OTWBusLCiKgQ9i2bKA.png" /></figure><blockquote><em>Seluruh prediktor sudah signifikan pada uji parsial. Diperoleh sebanyak tiga model regresi berbeda. Model terakhir melibatkan prediktor Usia Bangunan, Jarak Stasiun MRT, dan Banyaknya Minimarket.</em></blockquote><h3>Pemilihan Model</h3><p>Setelah menjalankan regresi bertahap hingga seluruh prediktor signifikan, tahap selanjutnya adalah menentukan model regresi yang terbaik untuk digunakan. Apabila diinginkan, Anda dapat langsung memilih model terakhir (model dengan seluruh prediktor signifikan) sebagai model terbaik dengan asumsi bahwa model tersebut paling sederhana dan hanya melibatkan prediktor yang diperlukan saja.</p><p>Namun, perlu diperhatikan bahwa model regresi dengan prediktor paling sedikit belum tentu terbaik. Hal ini dikarenakan beberapa prediktor yang tak signifikan mungkin memainkan peran penting dan sebaiknya tidak dihapus (misal: nilai Adjusted R2 lebih tinggi).</p><p>Beberapa kriteria pemilihan model yang dapat Anda gunakan adalah sebagai berikut.</p><ol><li><strong>R2 (Koefisien Determinasi)<br></strong>R2 atau koefisien determinasi merupakan ukuran besarnya variasi respon yang dapat dijelaskan oleh sekelompok prediktor. Nilai ini umum digunakan karena secara langsung mengukur kemampuan model dalam memprediksi sebaran respon berdasarkan prediktor.<br>Model yang baik adalah model dengan R2 tinggi. Anda dapat melihatnya langsung dari fungsi summary(…).</li><li><strong>Adjusted R-Squared <br></strong>Nilai Adjusted R2 lebih diutamakan daripada R2 karena ia mempertimbangkan kualitas setiap prediktor. Nilai Adjusted R2 akan turun apabila peneliti menambahkan prediktor yang buruk, dan akan naik apabila peneliti menambahkan prediktor yang baik. <br>Model yang baik adalah model dengan Adjusted R2 tinggi. Anda dapat melihatnya langsung dari fungsi summary(model).</li><li><strong>AIC (Akaike Information Criterion) <br></strong>AIC merupakan ukuran kebaikan model yang mempertimbangkan <em>goodness-of-fit</em> dengan kompleksitas model. <br>Model yang baik adalah model dengan AIC rendah. Anda dapat menggunakan fungsi AIC(model).</li><li><strong>BIC (Bayesian Information Criterion) <br></strong>BIC (atau juga disebut SBC) berbeda sedikit pada perhitungannya dibandingkan AIC. <br>Model yang baik adalah model dengan BIC rendah. Anda dapat menggunakan fungsi BIC(model).</li><li><strong>Jumlahan Kuadrat Residual (Residual Sum-of-Squares) <br></strong>Residual merupakan selisih antara respon observasi dan respon prediksi model. Model yang baik seharusnya memiliki residual yang kecil, menunjukkan kesalahan prediksi yang kecil. Ukuran yang dapat digunakan adalah jumlahan kuadrat residual.<br>Model yang baik adalah model dengan JKResidual rendah. Anda dapat menggunakan <em>sum(residuals(model)²)</em> untuk mencari JKResidual.</li></ol><h3>Regresi Bertahap — Otomatis</h3><p>Apabila Anda menggunakan AIC sebagai kriteria model terbaik, Anda dapat menggunakan fungsi step(…) dalam R.</p><blockquote><strong><em>Stepwise Regression Otomatis</em></strong><em> — </em><strong><em>Data: TaiwanEstate</em></strong></blockquote><pre># Model awal dengan semua prediktor<br>model_1 &lt;- lm(Harga ~ UsiaBangunan + Kebisingan + JarakStasiunMRT + NumMinimarket + Humiditas, data = estate)<br><br># Jalakan stepwise regression<br>model_terbaik &lt;- step(model_1)</pre><blockquote><em>Fungsi step(…) akan menampilkan proses seleksi di setiap langkahnya. Bagian berikut merupakan model awal.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*uWG-jrsqaI2dlAU4VAI07w.png" /></figure><blockquote><em>Nilai AIC model dengan semua prediktor adalah 2770.67. Kemudian, akan dicoba untuk menghapus satu variabel dari model. Setiap baris pada tabel di atas menunjukkan nilai AIC yang akan diperoleh apabila prediktor tersebut dikeluarkan. Sebagai contoh, apabila Humiditas dikeluarkan, maka AIC akan turun ke 2768.9. Pembuangan prediktor Humiditas menyebabkan penurunan AIC paling besar. Akibatnya, Humiditas dikeluarkan dari model.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*3CAhhrjt8TR3Y1O3NyCqPA.png" /></figure><blockquote><em>Proses yang sama diulangi kembali. Kali ini, apabila prediktor manapun dikeluarkan, nilai AIC justru akan meningkat. Sebagai contoh, mengeluarkan Kebisingan akan menaikkan AIC dari 2768.95 ke 2768.9. Oleh karenanya, algoritma ini berhenti. Model terbaik adalah model regresi tanpa variabel Humiditas.</em></blockquote><blockquote><em>Untuk menampilkan ringkasan model terbaik, gunakan fungsi summary(…)</em></blockquote><pre>summary(model_terbaik)</pre><blockquote><em>Model ini dapat menjelaskan 56.95% variasi harga bangunan berdasarkan usia bangunan, kebisingan, jarak stasiun MRT, dan banyaknya minimarket. Persamaan modelnya adalah</em></blockquote><blockquote>Harga = 379.06 — (0.872 * Usia) — (0.680 * Kebisingan) — (0.017 * JarakMRT) + (4.247 * Minimarket)</blockquote><blockquote>- Ingat bahwa harga bangunan memiliki satuan ribu TWD/ping.</blockquote><blockquote>- Setiap kenaikan 1 tahun usia bangunan, harga bangunan akan menurun sebesar 872 TWD/ping</blockquote><blockquote>- Setiap kenaikan satu dB kebisingan di sekitar bangunan akan mengakibatkan penurunan harga sebesar 681 TWD/ping</blockquote><blockquote>- Setiap kenaikan 1 meter jarak ke stasiun MRT akan mengakibatkan penurunan harga bangunan sebesar 17 TWD/ping.</blockquote><blockquote>- Setiap bertambahnya minimarket di sekitar bangunan akan meningkatkan harga bangunan sebesar 4.25k TWD/ping.</blockquote><h3>Penanganan Data: Pencilan (Outlier)</h3><p>Apabila Anda menemukan data pencilan (baik pada variabel dependen maupun independen), Anda memiliki opsi untuk membuang observasi tersebut. Cara lain yang populer adalah dengan melakukan transformasi.</p><p>Pencilan pada prediktor maupun respon dapat mempengaruhi koefisien regresi, dan oleh sebab itu, Anda disarankan untuk mengambil tindakan terhadap <em>outlier</em>.</p><p>Untuk melihat ada tidaknya pencilan, Anda dapat menyajikan sebuah Boxplot. Apabila terdapat titik data yang jauh dari ujung <em>whiskers</em>, data tersebut dapat dianggap sebagai pencilan.</p><blockquote><strong><em>Pencilan — Data: TaiwanEstate</em></strong></blockquote><blockquote><em>Peneliti menduga bahwa variabel Jarak Stasiun MRT memiliki banyak pencilan karena persebaran stasiun MRT yang tidak merata. Disajikan sebuah boxplot sebagai berikut.</em></blockquote><pre># Boxplot dengan dan tanpa pencilan<br>boxplot(estate$JarakStasiunMRT)<br>boxplot(estate[estate$JarakStasiunMRT &lt; 5000, &quot;JarakStasiunMRT&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*uNnHDxd9ERHtq60vMIyiZQ.png" /></figure><blockquote><em>Pada panel kiri, beberapa titik berada jauh di atas box dan whisker. Median dari data ini berada di bawah 1000, akan tetapi beberapa titik mencapai angka 6000. Peneliti memutuskan untuk membuang semua data dengan jarak stasiun MRT di atas 5000 meter (dianggap pencilan).</em></blockquote><blockquote><em>Pada panel kanan, kini data sudah lebih baik dengan mengeluarkan pencilan. Peneliti memutuskan untuk menggunakan data ini meskipun terlihat masih terdapat beberapa data yang ekstrim. Hal ini dikarenakan beberapa wilayah memang tidak memiliki stasiun MRT.</em></blockquote><blockquote><em>Untuk ilustrasi, akan dibentuk sebuah model regresi dengan dan tanpa penghapusan pencilan. Perhatikan perbedaan besar pada kolom “Estimate”.</em></blockquote><pre># Dengan Pencilan<br>summary(lm(JarakStasiunMRT~Harga, data = estate))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*qdz0R-MXFurFzkeYAJNsQQ.png" /></figure><pre># Tanpa Pencilan<br>tanpa_pencilan &lt;- estate[estate$JarakStasiunMRT &lt; 5000,]<br>summary(lm(JarakStasiunMRT~Harga, data = tanpa_pencilan))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*c-wdqF_SeXEbtBVjb0Y75A.png" /></figure><h3>Penanganan Data — Nilai Hilang (Missing)</h3><p>Umumnya, observasi dengan nilai hilang tidak diikutkan dalam model regresi, terlebih ketika observasi yang Anda miliki cukup banyak (dan sudah secara otomatis dilakukan oleh R).</p><h3>Penanganan Data — Data Kategorik dan Variabel Dummy</h3><p>Variabel kategorik (atau variabel kualitatif) dapat digunakan sebagai prediktor dalam regresi linear. Contohnya adalah jenis kelamin (laki-laki, perempuan) dan tingkat pendidikan (SD, SMP, SMA). Namun, terdapat beberapa hal yang perlu Anda ketahui karena interpretasi mengenai koefisien variabel kategorik berbeda dari variabel numerik.</p><p>Variabel kategorik dapat dikuantifikasi dalam bentuk <em>dummy</em>. Banyaknya variable <em>dummy</em> adalah banyaknya kategori dikurangi satu. Dalam variable <em>dummy</em>, terdapat satu kategori yang dijadikan sebagai kategori <em>reference</em>. Kategori <em>reference</em> bertindak sebagai pembanding untuk kategori lainnya. Nilai kategori <em>reference</em> selalu nol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*rrQ9Ek3ypBDCmniIF-Is1Q.png" /></figure><p>R secara otomatis mengartikan kolom dengan tipe data karakter dan faktor sebagai variabel kategorik. R juga secara otomatis membentuk variabel <em>dummy</em> dengan kategori <em>reference</em> berdasarkan urutan huruf pada kategori.</p><p>Misal: EARLY dan LATE, karena huruf E lebih dahulu daripada L, maka kategori E menjadi <em>reference</em>.</p><p>Untuk mengaturnya, Anda dapat menggunakan fungsi factor(…) atau relevel(…).</p><p><strong>Catatan penting:</strong></p><p>Misal dari variabel Tingkat Pendidikan (SD, SMP, SMA), diperoleh dua variabel dummy. Apabila salah satunya tidak signifikan, maka keduanya dikeluarkan sekaligus dari model.</p><blockquote><strong><em>Konsep Variabel Dummy — Data: TaiwanEstate</em></strong></blockquote><blockquote><em>Misal Anda tertarik untuk memodelkan harga bangunan berdasarkan usia bangunan dan periode transaksi. Periode transaksi adalah variabel kategorik. Oleh karenanya, Anda disarankan untuk merubah tipe datanya ke dalam faktor serta menentukan kategori reference dengan fungsi relevel(…).</em></blockquote><pre>estate$PeriodeTransaksi &lt;- factor(estate$PeriodeTransaksi)<br>estate$PeriodeTransaksi &lt;- relevel(estate$PeriodeTransaksi, ref = &quot;LATE&quot;)<br><br># Analisis regresi<br>summary(lm(Harga ~ UsiaBangunan + PeriodeTransaksi, data = estate))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*40yZdxsfG5fJXdMmLdr_Iw.png" /></figure><blockquote><em>Persamaan regresi yang diperoleh adalah</em></blockquote><blockquote>Harga = 356.86 — (0.8603 * Usia) + (5.980 * EARLY)</blockquote><blockquote>- Ingat bahwa harga bangunan memiliki satuan ribu TWD/ping.</blockquote><blockquote>- Setiap kenaikan 1 tahun usia bangunan, harga bangunan akan menurun sebesar 860 TWD/ping</blockquote><blockquote>- Periode transaksi “EARLY” (awal tahun) akan memberikan harga bangunan 5980 TWD/ping lebih tinggi daripada periode <em>reference</em>, yakni “LATE”.</blockquote><blockquote>Perhatikan pula bahwa variabel <em>dummy</em> di atas tidak signifikan dan dapat dikeluarkan dari model.</blockquote><h3>Penanganan Data — Nonlinearitas, Non-Normal, dan Transformasi Data</h3><p>Ketika data yang Anda gunakan tidak memenuhi asumsi linearitas maupun normalitas, Anda dapat mencoba melakukan transformasi data dengan Box-Cox, akar kuadrat, logaritma, dan sebagainya.</p><h3>Penanganan Data — Variabel Dependen Biner dan Cacah</h3><p>Regresi linear yang telah dibahas mengharuskan variabel dependen yang kontinu. Apabila Anda memiliki variabel dependen biner (misal: Ya-Tidak, Sakit-Tidak Sakit), Anda dapat mencoba melakukan analisis regresi logistik. Apabila variabel dependen Anda berbentuk cacah, Anda dapat mencoba regresi Poisson. Kedua regresi ini adalah bentuk generalisasi dari model linear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=accc96344501" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Panduan Praktis Pemrograman R — Analisis Mean dan Proporsi Dua Sampel]]></title>
            <link>https://medium.com/@mouse3mic3/panduan-praktis-pemrograman-r-analisis-mean-dan-proporsi-dua-sampel-6ab89f18ee40?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ab89f18ee40</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[r-programming]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Thu, 16 May 2024 09:04:45 GMT</pubDate>
            <atom:updated>2024-05-16T09:04:45.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Panduan Praktis Pemrograman R — Analisis Mean dan Proporsi Dua Sampel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RNwZkQcvIPb9ikcr" /><figcaption>Photo by <a href="https://unsplash.com/@wezlar11?utm_source=medium&amp;utm_medium=referral">Dean Pugh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Artikel ini adalah bagian dari seri panduan praktis pemrograman R. Beberapa topik akan dibahas pada artikel di masa mendatang, termasuk inferensi populasi dan analisis regresi, semua dalam Bahasa Indonesia.</p><p>Tanda koma menyatakan ribuan, tanda titik menyatakan desimal.</p><p>Data yang digunakan dapat diakses <a href="https://docs.google.com/spreadsheets/d/1Dz-9ScpeFeoDR2WqG75Zd0A02v1Fa_Su/edit?usp=sharing&amp;ouid=117358761750579055609&amp;rtpof=true&amp;sd=true">di sini</a>.</p><h3>Uji Dua Sampel</h3><p>Uji dua sampel membandingkan karakteristik dari dua populasi berdasarkan data sampel. Ketika membandingan dua populasi, peneliti harus memerhatikan apakah keduanya bergantung satu sama lainnya (dependen/berpasangan) atau tidak (independen).</p><p>Independen yang dimaksud adalah kedua populasi tidak saling berhubungan dan memengaruhi sampel satu sama lainnya. Artinya, sampel dari populasi A tidak memengaruhi sampel populasi B dan sebaliknya.</p><p><strong>Contoh Sampel Berpasangan dan Tidak Berpasangan</strong></p><ul><li>Pengukuran efektivitas lensa antiradiasi. Dalam penelitian ini, setiap orang mengenakan lensa biasa dan lensa antiradiasi dan dicatat lama waktu hingga mata memerah.<br>- Data biasa dan antiradiasi diperoleh dari individu yang sama sehingga ia disebut sampel <strong>berpasangan</strong>.<br>- Apabila setiap individu hanya diminta untuk mengenakan satu jenis lensa saja, ia disebut sampel <strong>independen</strong>.</li><li>Nilai pre-test (sebelum) dan post-test (sesudah) dicatat dari individu yang sama. Nilai post-test akan dipengaruhi oleh nilai pre-test. Data tersebut <strong>berpasangan</strong>.</li><li>Penghasilan seseorang 5 tahun dan 10 tahun setelah kelulusan adalah data <strong>berpasangan</strong>.</li><li>Kadar oksigen yang dihasilkan tanaman Anggrek di dua humiditas berbeda (tinggi dan rendah). Masing-masing Anggrek hanya dikenakan satu jenis humiditas dan tidak memengaruhi Anggrek di lokasi lain. Data ini <strong>independen</strong>.</li><li>Nilai siswa pada kurikulum pembelajaran lama dan baru. Terdapat dua kelas berbeda, kelas A menerima kurikulum lama dan kelas B menerima kurikulum baru.<br>- Data ini <strong>independen</strong>.<br>- Apabila kedua kelas berada dalam sekolah yang sama dan guru yang sama, terdapat kemungkinan hasil kelas A memengaruhi hasil kelas B (<strong>dependen</strong>).</li><li>Rata-rata lama tidur kakak beradik. Sekilas data ini independen karena rata-rata lama tidur diukur dari dua individu berbeda (kakak dan adik). Akan tetapi, dimungkinkan pula bahwa keduanya saling <strong>dependen</strong>, baik dari genetis atau karena interaksi keduanya di rumah. Dalam konteks ini, sebuah kelompok atau “individu” dapat diartikan sebagai “sepasang kakak beradik”.</li></ul><h3>Uji Proporsi Dua Sampel Independen</h3><p>Uji ini digunakan untuk membandingkan proporsi sebuah kelompok pada dua populasi berbeda. Sebagai contoh, ingin diketahui apakah proporsi mobil sedan di Kota Semarang dan Kota Surabaya berbeda. Sama halnya seperti pada kasus satu sampel, digunakan statistik Z dengan asumsi bahwa ukuran sampel besar.</p><p><strong>Asumsi: </strong>kedua populasi independen dan sampel cukup besar.</p><p><strong>Cara Analisis:</strong></p><p>Gunakan fungsi <em>prop.test(…)</em>.</p><p>Argumen yang Anda berikan adalah banyaknya kejadian sukses pada masing-masing sampel (x₁, x₂), ukuran sampel (n₁, n₂), hipotesis alternatif, dan tingkat konfidensi (dalam desimal).</p><p>Misal dan menunjukkan proporsi masing-masing populasi. Terdapat 3 jenis hipotesis alternatif:</p><p>- “two.sided” digunakan ketika menguji Ha: p₁ ≠ p₂ atau p₁ — p₂ ≠ 0</p><p>- “greater” digunakan ketika menguji Ha: p₁ &gt; p₂ atau p₁ — p₂ &gt; 0</p><p>- “less” digunakan ketika menguji Ha: p₁ &lt; p₂ atau p₁ — p₂ &lt; 0</p><p>Anda juga dapat menguji perbedaan selisih proporsi (tidak harus 0).</p><p><strong>Alternatif: </strong>Gunakan uji Wilcoxon apabila sampel terbatas dan pendekatan Normal tidak memungkinkan.</p><blockquote><strong><em>Uji Proporsi Dua Sampel Independen — Contoh 1 (Data: Karyawan)</em></strong></blockquote><blockquote><em>Data Karyawan merupakan data keterlambatan karyawan di dua cabang berbeda. Seorang manajer tertarik untuk melihat apakah terdapat perbedaan proporsi pria yang terlambat di dua cabang tersebut.</em></blockquote><pre>table(karyawan[c(&#39;Kode Cabang&#39;, &#39;Jenis Kelamin&#39;)])<br>##            Jenis Kelamin<br>## Kode Cabang Pria Wanita<br>##           A   11     13<br>##           B   12     14</pre><blockquote><em>Misal p_A menunjukkan proporsi karyawan pria terlambat di cabang A dan p_B di cabang B. Dari tabel tersebut, diperoleh</em></blockquote><blockquote><em>x_A = 11</em></blockquote><blockquote><em>x_B = 12</em></blockquote><blockquote><em>n_A = 11 + 13 = 24</em></blockquote><blockquote><em>n_B = 12 + 14 = 26</em></blockquote><blockquote><em>Hipotesis yang digunakan adalah</em></blockquote><blockquote><em>H0: p_A = p_B<br> Proporsi karyawan pria terlambat di kedua cabang sama</em></blockquote><blockquote><em>Ha: p_A ≠ p_B<br>Proporsi karyawan pria terlambat di kedua cabang berbeda</em></blockquote><blockquote><em>dengan tingkat signifikansi α = 5%.</em></blockquote><pre>prop.test(x = c(11, 12), n = c(24, 26), <br>alternative = &quot;two.side&quot;, conf.level = 0.95)<br>##         2-sample test for equality of proportions<br>## <br>## data:  c(11, 12) out of c(24, 26)<br>## X-squared = 3.4088e-31, df = 1, p-value = 1<br>## alternative hypothesis: two.sided<br>## 95 percent confidence interval:<br>##  -0.2829168  0.2765065<br>## sample estimates:<br>##    prop 1    prop 2 <br>## 0.4583333 0.4615385</pre><blockquote><em>Diperoleh p-value = 1, artinya tidak cukup data untuk menolak H0. Proporsi karyawan pria yang terlambat identik di kedua cabang pada taraf 5%. Dari sample estimates, proporsi karyawan pria cabang A yang terlambat adalah 45.8%, tidak jauh berbeda dari cabang B sebesar 46.2%.</em></blockquote><blockquote><em>Anda juga memeroleh nilai interval konfidensi 95%. Nilai ini menunjukkan bahwa selisih proporsi antara kedua cabang, p_A — p_B, berada di rentang -28% hingga 27%.</em></blockquote><blockquote><strong><em>Uji Proporsi Dua Sampel Independen — Contoh 2 (Data: Pembelajaran Daring)</em></strong></blockquote><blockquote><em>Seorang peneliti ingin membandingkan efektivitas pembelajaran daring dan luring. Peneliti tersebut memilih 125 siswa dari sebuah kelas berisi 300 siswa untuk belajar secara daring, sisanya dengan tatap muka. Di akhir pembelajaran, seluruh siswa diminta mengisi sebuah kuis dengan hasil yang dirangkum di tabel di bawah.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*V0UbjHgLgdedp_ezfWGVSw.png" /></figure><blockquote><em>Untuk mengetahui apakah pembelajaran daring menurunkan proporsi siswa yang lulus daripada pembelajaran tatap muka, peneliti mengasumsikan bahwa kedua kelompok siswa saling independen (antara kelompok daring dan luring). Hipotesis yang digunakan adalah sebagai berikut.</em></blockquote><blockquote><em>Misal </em>p_Daring<em> menunjukkan proporsi siswa lulus di kelompok daring, </em>p_Luring<em> di kelompok luring. Dari tabel tersebut, diperoleh</em></blockquote><blockquote><em>x_Daring = 61</em></blockquote><blockquote><em>x_Luring = 112</em></blockquote><blockquote><em>n_Daring = 125</em></blockquote><blockquote><em>n_Luring = 175</em></blockquote><blockquote><em>Hipotesis yang digunakan adalah</em></blockquote><blockquote><em>- H0: p_Daring ≥ p_Luring<br> Proporsi kelulusan di kelompok daring lebih tinggi</em></blockquote><blockquote><em>- Ha: p_Daring &lt; p_Luring<br> Proporsi kelulusan di kelompok daring lebih rendah</em></blockquote><blockquote><em>dengan tingkat signifikansi α = 5%.</em></blockquote><pre>prop.test(x = c(61, 112), n = c(125, 175), alternative = &quot;less&quot;, conf.level = 0.95)<br>##         2-sample test for equality of proportions with continuity ## correction<br>##<br>## data:  c(61, 112) out of c(125, 175)<br>## X-squared = 6.2923, df = 1, p-value = 0.006063<br>## alternative hypothesis: less<br>## 95 percent confidence interval:<br>##  -1.00000000 -0.05043271<br>## sample estimates:<br>## prop 1 prop 2 <br>##  0.488  0.640</pre><p>Diperoleh nilai pval = 0.006 &lt; α = 5%, artinya data mendukung penolakan H0. Pembelajaran secara daring secara signifikan menurunkan proporsi siswa yang lulus kuis. Peneliti juga perlu menggaris bawahi bahwa hasil ini terbatas pada satu kali pembelajaran dan satu kuis. Pada kenyataannya, untuk membandingkan efektivitas pembelajaran daring dan luring, diperlukan analisis yang lebih menyeluruh.</p><p>Hasil di atas juga menunjukkan estimasi proporsi siswa lulus. Pada kelompok 1 (daring), sebanyak 49% siswa lulus, sedangkan pada kelompok 2 (luring) sebanyak 64% lulus.</p><h3>Uji Proporsi Dua Sampel Berpasangan</h3><p>Anda dapat menggunakan uji McNemar. Uji ini bersifat non-parametrik dan akan dibahas kembali pada artikel-artikel selanjutnya.</p><h3>Uji Mean Dua Sampel Independen</h3><p>Uji ini digunakan untuk membandingkan mean dua populasi yang sifatnya independen.</p><p><strong>Asumsi: </strong>Masing-masing sampel berdistribusi Normal. Sebaiknya Anda melakukan uji homogenitas variansi.</p><p><strong>Cara Analisis:</strong></p><p>Anda dapat kembali menggunakan fungsi <em>t.test(…),</em> namun dengan menambahkan beberapa argumen.</p><ul><li>Apabila data Anda berupa dua vektor dan masing-masing merupakan sampel, gunakan:</li></ul><pre>t.test(x = sampel1, y = sampel2, ..., <br>      paired = FALSE, var.equal = FALSE)</pre><ul><li>Apabila data Anda berbentuk memanjang (seperti pada contoh Uji Homogenitas Variansi), Anda dapat menggunakan formula.</li></ul><pre>t.test(VarNumerik ~ VarKategorik, data = data, ... <br>       paired = FALSE, var.equal = FALSE)</pre><p>Argumen <em>paired = FALSE</em> menyatakan bahwa Anda tidak ingin uji dua sampel berpasangan. Argumen <em>var.equal</em> menyatakan asumsi kesamaan variansi. Gunakan <em>TRUE</em> jika asumsi terpenuhi.</p><p>Misal μ₁ dan μ₂ menunjukkan mean masing-masing populasi. μ_D = μ₁ — μ₂ menunjukkan selisih mean. Terdapat 3 jenis hipotesis alternatif:</p><ul><li>“two.sided” digunakan ketika menguji Ha: μ₁ ≠ μ₂ atau μ₁ — μ₂ ≠ μ_D</li><li>“greater” digunakan ketika menguji Ha: μ₁ &gt; μ₂ atau μ₁ — μ₂ &gt; μ_D atau</li><li>“less” digunakan ketika menguji Ha: μ₁ &lt; μ₂ atau μ₁ — μ₂ &lt; μ_D atau</li></ul><p>Anda juga dapat merubah nilai 0 di ruas kanan dengan argumen <em>mu</em>.</p><blockquote><strong><em>Uji Mean Dua Sampel Independen — Contoh 1 (Data: TaiwanEstate</em></strong><em>)</em></blockquote><blockquote><em>Peneliti ingin mengetahui apakah rata-rata harga bangunan di dua periode transaksi (EARLY dan LATE) berbeda secara signifikan. Dari data historis, peneliti menemukan bahwa harga properti umumnya meningkat di awal tahun karena adanya CNY.</em></blockquote><blockquote>Uji Normalitas</blockquote><blockquote><em>Uji Normalitas dilakukan pada masing-masing sampel.</em></blockquote><pre>shapiro.test(estate[estate$PeriodeTransaksi == &#39;EARLY&#39;, &#39;Harga&#39;])<br>shapiro.test(estate[estate$PeriodeTransaksi == &#39;LATE&#39;, &#39;Harga&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*U8GaW12ZL35PdbgEbMYxeg.png" /></figure><blockquote><em>Hasil di atas (p-value &gt; 5%) menunjukkan bahwa H0 tidak ditolak (kedua populasi berdistribusi Normal).</em></blockquote><blockquote>Uji Homogenitas Variansi (Levene)</blockquote><pre>bartlett.test(Harga ~ PeriodeTransaksi, data = estate)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*lXdlI8GJNZkUiE1jdA3sWw.png" /></figure><blockquote><em>Hasil di atas (p-value &gt; 5%) menunjukkan bahwa H0 tidak ditolak (variansi harga pada kedua periode transaksi homogen).</em></blockquote><blockquote>Uji t Dua Sampel Independen</blockquote><blockquote><em>Misal dimiliki μ_Early, μ_Late sebagai rata-rata masing-masing populasi (karena huruf E lebih dahulu muncul daripada L, maka kategori EARLY menjadi μ₁) . Hipotesis yang diajukan adalah</em></blockquote><blockquote><em>- H0: μ_Early ≤ μ_Late<br> (rata-rata harga properti di awal tahun lebih rendah dari akhir tahun)</em></blockquote><blockquote><em>- Ha: μ_Early &gt; μ_Late<br> (rata-rata harga properti di awal tahun lebih tinggi dari akhir tahun)</em></blockquote><blockquote><em>dengan α = 10%.</em></blockquote><pre>t.test(Harga~PeriodeTransaksi, data = estate, alternative = &quot;greater&quot;,<br>      paired = FALSE, var.equal = TRUE, conf.level = 0.9)<br>##         Two Sample t-test<br>##<br>## data:  Harga by PeriodeTransaksi<br>## t = 1.3143, df = 412, p-value = 0.09474<br>## alternative hypothesis: true difference in means between group EARLY and group LATE is greater than 0<br>##  90 percent confidence interval:<br>##   0.1341699       Inf<br>##  sample estimates:<br>##  mean in group EARLY  mean in group LATE <br>##             347.5121            341.7678</pre><blockquote><em>Nilai pval = 0.09 menunjukkan penolakan terhadap H0 apabila digunakan α = 10%, namun H0 tidak ditolak apabila α = 5%. Pemilihan nilai signifikansi α ini menjadi topik penting karena berhubungan langsung dengan keyakinan model. Semakin tinggi nilai α, semakin mungkin pula untuk menolak H0. Akan tetapi, risiko melakukan kesalahan tipe I semakin tinggi.</em></blockquote><blockquote><em>Pada keyakinan 90%, klaim peneliti benar adanya bahwa harga properti di Taiwan pada periode awal tahun relatif lebih tinggi daripada akhir tahun. Apabila diperhatikan, rata-rata harga di awal tahun sebesar 347.5k TWD, sedangkan di akhir tahun adalah 341.8k TWD, perbedaan sekitar 6k TWD.</em></blockquote><h3>Uji Mean Dua Sampel Dependen</h3><blockquote><strong><em>Uji Mean Dua Sampel Dependen — Contoh 1 (Data: AndrogenRusa)</em></strong></blockquote><blockquote><em>Dalam sebuah penelitian yang dilakukan di Departemen Kehutanan dan Margasatwa di Virginia Tech, J. A. Wesson meneliti pengaruh obat suksinilkolin pada tingkat sirkulasi androgen dalam darah.</em></blockquote><blockquote><em>Sampel darah pertama diambil dari rusa liar yang berkeliaran segera setelah mereka menerima suntikan suksinilkolin intramuskular yang diberikan menggunakan panah dan pistol penangkap. Sampel darah kedua diperoleh dari setiap rusa 30 menit setelah sampel pertama, setelah itu rusa dilepaskan. Kadar androgen pada saat penangkapan dan 30 menit kemudian, diukur dalam nanogram per mililiter (ng/mL), untuk 15 rusa disajikan pada tabel di bawah ini. Peneliti ingin mengetahui apakah konsentrasi androgen berubah setelah 30 menit.</em></blockquote><blockquote><em>Dataset ini tersedia dan terdapat kolom “Treatment” (indikator sampel pertama atau kedua) dan “Androgens” (konsentrasi androgens yang dicatat). Misal diasumsikan bahwa Normalitas sudah dipenuhi untuk kedua sampel. Selanjutnya, digunakan hipotesis</em></blockquote><blockquote><em>H0: μ_Pre = μ_Post (rata-rata konsentrasi androgen tidak berubah setelah 30 menit)</em></blockquote><blockquote><em>Ha: μ_Pre ≠ μ_Post (rata-rata konsentrasi androgen berubah setelah 30 menit)</em></blockquote><blockquote><em>dan tingkat signifikansi \alpha = 5%.</em></blockquote><pre>androgens &lt;- read_excel(path = &quot;C:\\Project\\Dataset.xlsx&quot;,<br>   sheet = &quot;AndrogensRusa&quot;)<br>androgens &lt;- as.data.frame(androgens)<br><br># Ubah urutan agar kategori “Pre” didahulukan...<br>androgens$Treatment &lt;- factor(androgens$Treatment, <br>levels = c(&quot;Pre&quot;, &quot;Post&quot;)) <br><br># ...dengan demikian μ_1 adalah Pre, μ_2 adalah Post<br>t.test(Androgens~Treatment, data = androgens, paired = TRUE, <br> conf.level = 0.95, alternative = &quot;two.sided&quot;)<br><br>##         Paired t-test<br>##<br>## data:  Androgens by Treatment<br>## t = -2.0646, df = 14, p-value = 0.058<br>## alternative hypothesis: true mean difference is not equal to 0<br>## 95 percent confidence interval:<br>##  -20.0783535   0.3823535<br>## sample estimates:<br>## mean difference <br>##          -9.848</pre><blockquote><em>Nilai mean difference dapat diartikan sebagai μ_Pre — μ_Post = -9.848 yang menunjukkan bahwa terdapat kenaikan konsentrasi androgen sebesar 9.848 ng/mL setelah 30 menit rusa disuntik, namun, peningkatan ini tidak signifikan pada taraf 5%. Nilai p-value 0.058 &gt; α = 5% menunjukkan bahwa tidak cukup bukti untuk menolak H0.</em></blockquote><blockquote><em>Dari interval konfidensi, peneliti juga menemukan bahwa konsentrasi androgen 30 menit setelah suntik dapat menurun sebesar 0.382 ng/mL atau meningkat hingga 20.078 ng/mL.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ab89f18ee40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Panduan Praktis Pemrograman R — Analisis Mean dan Proporsi Satu Sampel]]></title>
            <link>https://medium.com/@mouse3mic3/panduan-praktis-pemrograman-r-analisis-mean-dan-proporsi-satu-sampel-2ff414e45283?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ff414e45283</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Thu, 16 May 2024 08:25:38 GMT</pubDate>
            <atom:updated>2024-05-16T08:25:38.136Z</atom:updated>
            <content:encoded><![CDATA[<h3>Panduan Praktis Pemrograman R — Analisis Mean dan Proporsi Satu Sampel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XWbe4JurJCnzKIqA" /><figcaption>Photo by <a href="https://unsplash.com/@wezlar11?utm_source=medium&amp;utm_medium=referral">Dean Pugh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Artikel ini adalah bagian dari seri panduan praktis pemrograman R. Beberapa topik akan dibahas pada artikel di masa mendatang, termasuk inferensi populasi dan analisis regresi, semua dalam Bahasa Indonesia.</p><p>Tanda koma menyatakan ribuan, tanda titik menyatakan desimal.</p><p>Data yang digunakan dapat diakses <a href="https://docs.google.com/spreadsheets/d/1Dz-9ScpeFeoDR2WqG75Zd0A02v1Fa_Su/edit?usp=sharing&amp;ouid=117358761750579055609&amp;rtpof=true&amp;sd=true">di sini</a>.</p><h3>Sampel dan Populasi</h3><p><strong>Sampel dan Populasi</strong></p><p>Populasi mewakili seluruh subjek / target utama penelitian. Sampel merupakan bagian dari populasi. Sampel yang diambil diharapkan dapat mewakili karakteristik populasi. Dengan kata lain, apabila memadai, Anda dapat menarik kesimpulan tentang populasi hanya dengan data sampel.</p><p>Pengambilan sampel di mana seluruh anggota populasi memiliki kemungkinan sama untuk dipilih disebut sampel acak. Ukuran sebuah populasi disebut parameter, sedangkan ukuran sebuah sampel disebut statistik.</p><p><strong>Inferensi Statistika</strong></p><p>Pada dasarnya, inferensi statistika bertujuan untuk mengungkap informasi parameter berdasarkan sampel yang ada, dengan derajat keyakinan tertentu. Terdapat dua macam estimasi, yakni estimasi titik dan interval.</p><blockquote><em>Sebagai contoh, sebuah penelitian bertujuan untuk mengetahui rata-rata harga tanah di sebuah Kota Semarang. Rata-rata harga tanah sebenarnya (parameter) dinotasikan dengan dan tidak diketahui. Peneliti mengambil sampel sebanyak 1000 rumah secara acak dan mendapatkan rata-rata harga juta/m2 (statistik).</em></blockquote><blockquote><em>Dari sampel yang dimiliki, peneliti ingin menduga nilai dengan keyakinan sebesar 95%. Ia telah memeroleh estimasi titik, yakni juta/m2. Ia kemudian memeroleh estimasi interval 95%, yakni harga tanah berada di antara Rp 2,9 juta/m2 dan Rp 3,3 juta/m2.</em></blockquote><p>Informasi yang terdapat pada sampel bersifat terbatas, artinya akan ada kesalahan pada saat pengambilan keputusan. Konsep ini akan dibahas lebih lanjut pada uji hipotesis.</p><h3>Fungsi Dasar Statistik</h3><p><strong>Mean / Rata-rata</strong></p><p>Mean atau rata-rata merupakan ukuran pusat data. Mean menggambarkan dimana letak data terpusat. Mean sampel dituliskan dengan persamaan</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*n1uDSMqz-DKC_Pyd4nDXfw.png" /></figure><p>dengan menunjukkan data yang dimiliki. Artinya, untuk menghitung mean, jumlahkan semua data lalu bagi dengan banyaknya data.</p><p>Gunakan fungsi <em>mean(…)</em> untuk menghitung mean. Mean mudah dipengaruhi oleh <em>outlier</em> atau pencilan. Ukuran lain seperti median dapat digunakan.</p><p><strong>Median / Nilai Tengah</strong></p><p>Median merupakan nilai tengah data yang sudah diurutkan, atau dikenal sebagai kuantil kedua. Misal dimiliki data sebanyak <em>n</em>.</p><p>· Apabila <em>n</em> bernilai ganjil (banyaknya data ganjil), maka median merupakan data ke (n+1)/2.</p><p>· Apabila <em>n</em> bernilai genap, maka median merupakan rata-rata data ke n/2 dann/2 + 1 .</p><p>Artinya, untuk mencari median, urutkan data terlebih dahulu (baik dari data terkecil maupun terbesar), kemudian cari nilai tengah yang dapat memisahkan data menjadi dua bagian sama banyak.</p><p>Gunakan fungsi median(…) untuk menghitung median.</p><p><strong>Variansi dan Deviasi Standar</strong></p><p>Variansi merupakan ukuran sebaran data. Ia menjelaskan seberapa jauh suatu data dari pusatnya. Variansi untuk sampel sebanyak <em>n </em>dihitung dengan persamaan</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*JbjCO_K8XtnZeGf8QcmnHQ.png" /></figure><p>dengan x1, x2, .., xn menunjukkan data yang dimiliki dan \bar{x} menunjukkan rata-rata data.</p><p>Deviasi standar merupakan akar kuadrat dari variansi. Gunakan fungsi var(…) untuk variansi dan sd(…) untuk deviasi standar.</p><p><strong>Proporsi</strong></p><p>Dalam sebuah eksperimen, proporsi adalah rasio antara kejadian “sukses” dan banyaknya hasil. Misal dalam percobaan vaksin pada tikus, kejadian sukses adalah tikus yang menghasilkan antibodi. Proporsi sebesar 0.43 menunjukkan bahwa 43% tikus menghasilkan antibodi, sedangkan sisanya yakni 1–0.43 = 0.57 (57%) tidak menghasilkan antibodi.</p><h3>Uji Hipotesis</h3><p>Uji hipotesis dilakukan untuk mengetahui apakah dugaan tentang karakteristik populasi didukung kuat oleh data sampel atau tidak. Hipotesis adalah sebuah pernyataan tentang parameter populasi. Terdapat dua jenis hipotesis, yakni hipotesis nol (H0, <em>null hypothesis</em>) dan hipotesis alternatif (Ha, H1, <em>alternative hypothesis</em>).</p><p><strong>Hipotesis Nol dan Hipotesis Alternatif</strong></p><p>H0 adalah hipotesis yang dirumuskan dengan harapan untuk ditolak, umumnya berupa pernyataan tidak adanya perbedaan karakteristik populasi (sifatnya netral). Ha digunakan untuk menunjukkan pernyataan mendapat dukungan kuat dari data sampel. H0 dianggap benar dalam keadaan apapun kecuali apabila data sampel mendukung penolakan H0.</p><p><strong>Kesalahan</strong></p><p>Terdapat dua tipe kesalahan pada pengambilan kesimpulan dari uji hipotesis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*6L61LZcWwPZgv2D_5il8LQ.png" /></figure><p>α adalah peluang melakukan kesalahan tipe I (menolak H0 meskipun kenyataannya H0 benar), sedangkan β peluang melakukan kesalahan tipe II (tidak menolak H0 meskipun kenyataannya H0 salah). Idealnya nilai keduanya diatur serendah mungkin, namun hal ini sulit untuk dilakukan.</p><p>Umumnya kesalahan α (tipe I) lebih penting dibandingkan kesalahan tipe II. Menghukum orang yang tak bersalah dinilai lebih buruk dibandingkan membebaskan orang bersalah.</p><p><strong>Tingkat Signifikansi</strong></p><p>Dalam sebuah uji hipotesis, peneliti membatasi kesalahan tipe I. Nilai α yang sering digunakan adalah 1%, 5%, dan 10%. Tingkat signifikansi berkaitan dengan konsep estimasi interval. Tingkat keyakinan pada estimasi interval diperoleh dari (1-α)100%.</p><p><strong>Statistik Uji, Daerah Kritik/Penolakan, dan P-value</strong></p><p>Statistik uji adalah nilai tertentu yang digunakan untuk menentukan apakah H0 ditolak atau tidak. Apabila nilai statistik uji berada dalam daerah kritik, maka H0 ditolak dan sebaliknya.</p><p>Selain statistik uji, nilai p-value juga dapat digunakan. Nilai ini dapat diartikan sebagai nilai α terendah untuk menolak H0, atau peluang memeroleh hasil serupa atau lebih ekstrim dari data. Apabila p-value &lt; α, data mendukung penolakan H0.</p><p><strong>Kesimpulan</strong></p><p>Peneliti dapat mengambil kesimpulan untuk menolak atau tidak menolak H0 pada tingkat signifikansi tertentu.</p><blockquote><strong><em>Contoh Uji Hipotesis</em></strong></blockquote><blockquote><em>Dari contoh sebelumnya, peneliti ingin mengetahui apakah harga rata-rata tanah melebihi rata-rata nasional, yakni Rp 3 juta/m2. Dibentuk dua pernyataan sebagai hipotesis, yakni:</em></blockquote><blockquote><em>- H0: μ ≤ Rp 3 juta/m2 <br> (harga rata-rata tanah Kota Semarang tidak lebih tinggi dari rata-rata nasional)</em></blockquote><blockquote><em>- Ha: μ &gt; Rp 3 juta/m2 <br> (harga rata-rata tanah Kota Semarang lebih tinggi dari rata-rata nasional)</em></blockquote><blockquote><em>Misal dari hasil sebelumnya, diperoleh p-value sebesar 0.25. Keputusan peneliti adalah tidak menolak H0, artinya harga rata-rata tanah Kota Semarang tidak lebih tinggi dari rata-rata nasional pada taraf signifikansi 5%.</em></blockquote><h3>Uji Satu Sampel</h3><p>Uji satu sampel, sesuai namanya, menguji apakah sebuah populasi memiliki karakteristik tertentu berdasarkan data sampel.</p><h3>Uji Normalitas</h3><p>Uji normalitas menjadi asumsi penting dari berbagai analisis parametrik. Uji ini menilai apakah sebuah variabel / sampel berasal dari populasi yang berdistribusi Normal. Distribusi Normal memiliki bentuk seperti lonceng simetris.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*iJGHaby7KF4FARucg4k0wg.png" /></figure><p>Terdapat beberapa cara untuk melihat apakah sebuah variabel berdistribusi Normal atau tidak. Contoh di bawah ini menunjukkan uji Normalitas pada variabel usia bangunan.</p><h4>Eksploratif — Histogram dan Boxplot</h4><blockquote><strong><em>Uji Normalitas — Histogram</em></strong></blockquote><pre>usia &lt;- estate$UsiaBangunan<br>hist(usia, freq = FALSE, breaks = 30)<br>lines(density(usia))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*9ldnhUPi-d17lK9L3Ke3_g.png" /></figure><blockquote><em>Hasil di atas menunjukkan bahwa histogram usia bangunan tidak membentuk kurva Normal. Dengan demikian, secara visual data usia bangunan tidak berdistribusi Normal.</em></blockquote><blockquote><strong><em>Uji Normalitas — Boxplot</em></strong></blockquote><pre>usia &lt;- estate$UsiaBangunan<br>boxplot(usia)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*zkBJAwx7dUO1Bnb9updalA.png" /></figure><blockquote><em>Data yang Normal umumnya akan menghasilkan boxplot dengan median (garis tengah tebal) tepat di tengah kotak. Dalam contoh ini, terlihat median cenderung lebih dekat ke batas bawah (Q1) mengindikasikan usia bangunan yang tidak Normal.</em></blockquote><h4>Uji Hipotesis</h4><p>Hipotesis yang digunakan adalah</p><p>· H0: Sampel berasal dari populasi yang berdistribusi Normal</p><p>· Ha: Sampel tidak berasal dari populasi yang berdistribusi Normal</p><p>Terdapat beberapa jenis uji normalitas yang dapat Anda gunakan.</p><blockquote><strong><em>Uji Normalitas — Shapiro-Wilk</em></strong></blockquote><pre>shapiro.test(estate$usia)<br>##         Shapiro-Wilk normality test<br>## <br>## data:  usia<br>## W = 0.94674, p-value = 4.798e-11</pre><blockquote><strong><em>Uji Normalitas — Anderson-Darling</em></strong></blockquote><pre>library(nortest)<br>ad.test(estate$usia)<br>##         Anderson-Darling normality test<br>## <br>## data:  usia<br>## A = 7.3279, p-value &lt; 2.2e-16</pre><blockquote><strong><em>Uji Normalitas — Jarque-Bera</em></strong></blockquote><pre>library(fBasics)<br>jarqueberaTest(estate$usia)<br>## Test Results:<br>##  STATISTIC:<br>##    X-squared: 23.4338<br>##  P VALUE:<br>##    Asymptotic p Value: 8.155e-06</pre><blockquote><strong><em>Uji Normalitas — Kolmogorov-Smirnov</em></strong></blockquote><pre>lillie.test(estate$usia)<br>##         Lilliefors (Kolmogorov-Smirnov) normality test<br>## <br>## data:  usia<br>## D = 0.1182, p-value = 3.354e-15</pre><p>P-value yang dihasilkan semua uji di atas sangat rendah (α &lt; 5%). Artinya data mendukung penolakan H0 (usia bangunan tidak berdistribusi Normal).</p><h3>Uji Kesamaan (Homogenitas) Variansi</h3><p>Uji ini digunakan untuk mengetahui apakah dua populasi berbeda memiliki varians yang homogen. Asumsi ini penting dalam uji mean dua sampel karena akan menentukan statistik uji yang digunakan. Karakteristik variansi dua populasi yang homogen akan mempermudah perhitungan.</p><p>Misalkan variansi kedua populasi masing-masing adalah σ₁² dan σ₂².</p><p>Hipotesis yang digunakan adalah</p><p>- H0: σ₁² = σ₂² (variansi populasi 1 dan 2 homogen)</p><p>- Ha: σ₁² ≠ σ₂² (variansi populasi 1 dan 2 tidak homogen)</p><p>Terdapat beberapa uji yang dapat digunakan seperti Bartlett dan Levene. Untuk menggunakan uji Bartlett, Anda dapat memanggil fungsi <em>bartlett.test(…)</em>. Uji Bartlett memberi hasil yang akurat apabila asumsi Normalitas terpenuhi (data berdistribusi Normal). Uji Levene tidak mengharuskan Normalitas dan Anda dapat menggunakan fungsi <em>homog.test(…)</em> dalam pustaka <em>onewaytests</em>.</p><p><strong>Catatan: </strong>Anda harus memerhatikan bentuk data Anda. Kedua fungsi tersebut mengharapkan bentuk data memanjang di mana terdapat satu kolom penanda kelompok populasi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*Wxbe2D1s9t9r8gQ9vd7eQg.png" /></figure><p>Misal Anda memiliki dua vektor, masing-masing mengandung data untuk satu populasi. Anda harus mengubah bentuknya terlebih dahulu ke bentuk di atas.</p><p>Fungsi <em>bartlett.test(…)</em> dan <em>homog.test(…)</em> menerima argumen berupa formula.</p><pre>kolomNumerik ~ kolomKategorik</pre><blockquote><strong><em>Uji Homogenitas Variansi Dua Populasi — Contoh (Data: TaiwanEstate)</em></strong></blockquote><blockquote><em>Misal ingin diketahui apakah variansi usia bangunan antara dua periode transaksi (EARLY dan LATE) homogen atau tidak. Perbedaan dalam variansi dapat menandakan bahwa kedua periode tersebut memiliki sebaran usia yang berbeda.</em></blockquote><blockquote><em>- H0: σ²Early = σ²Late<br> (variansi usia bangunan kelompok early dan late homogen)</em></blockquote><blockquote><em>- Ha: σ²Early ≠ σ²Late<br> (variansi usia bangunan kelompok early dan late tidak homogen)</em></blockquote><pre>bartlett.test(UsiaBangunan ~ PeriodeTransaksi, data = estate)<br>##         Bartlett test of homogeneity of variances<br>## <br>## data:  UsiaBangunan by PeriodeTransaksi<br>## Bartlett&#39;s K-squared = 0.46606, df = 1, p-value = 0.4948</pre><blockquote><em>Uji Bartlett menghasilkan nilai statistik K-kuadrat dan p-value sebesar 0.49. Pada taraf signifikansi α = 5% , peneliti tidak menolak H0. Artinya, variansi usia bangunan kedua periode homogen (sama).</em></blockquote><blockquote><em>Dalam kasus ini, karena usia bangunan berdistribusi Normal bagi kedua periode, uji Bartlett dapat digunakan. Apabila Anda ingin menggunakan uji Levene:</em></blockquote><pre>homog.test(UsiaBangunan ~ PeriodeTransaksi, data = estate)<br>##   Levene&#39;s Homogeneity Test (alpha = 0.05) <br>## ----------------------------------------------- <br>##   data : UsiaBangunan and PeriodeTransaksi <br><br>##   statistic  : 1.652116 <br>##   num df     : 1 <br>##   denum df   : 412 <br>##   p.value    : 0.1993932 <br><br>##   Result     : Variances are homogeneous. <br>## -----------------------------------------------</pre><blockquote><em>Uji Levene memberikan kesimpulan yang serupa, yakni variansi usia bangunan di kedua periode homogen.</em></blockquote><h3>Uji Proporsi Satu Sampel</h3><p>Uji proporsi satu sampel bertujuan untuk menguji proporsi kelompok tertentu dalam populasi terhadap nilai tertentu.</p><p>Uji ini juga disebut Uji Binomial karena distribusinya yang Binomial. Namun, apabila ukuran sampel besar, Binomial dapat didekati dengan distribusi Normal sehingga uji ini dinamakan Uji Z.</p><p><strong>Asumsi dan Cara Analisis</strong></p><ul><li><strong>Kasus Sampel Besar (Uji Z)</strong><br> Apabila np₀ ≥ 10 dan n(1 — p₀) ≥ 10, gunakan fungsi <em>prop.test(…)</em>.</li><li><strong>Kasus Sampel Kecil (Uji Eksak Binomial)<br></strong>Gunakan fungsi <em>binom.test(…)</em> sebagai alternatif apabila Anda tidak yakin.</li></ul><p>Argumen yang Anda berikan adalah banyaknya kejadian sukses (<em>x</em>), banyaknya percobaan atau sampel (<em>n</em>), proporsi pembanding yang diuji p₀, hipotesis alternatif, dan tingkat konfidensi (dalam desimal).</p><p>Misal p menunjukkan proporsi populasi dan p₀ adalah proporsi pembanding yang diuji. Terdapat 3 jenis hipotesis alternatif:</p><ul><li>“two.sided” digunakan ketika menguji Ha: p ≠ p₀</li><li>“greater” digunakan ketika menguji Ha: p &gt; p₀</li><li>“less” digunakan ketika menguji Ha: p &lt; p₀</li></ul><pre># Contoh<br>prop.test(x = 30, n = 100, p = 0.25, <br>    alternative = &quot;greater&quot;, conf.level = 0.95)</pre><blockquote><strong><em>Uji Proporsi Satu Sampel — Contoh 1 (Data: TaiwanEstate)</em></strong></blockquote><blockquote><em>Dari data harga bangunan di Taiwan, ingin diketahui apakah jual-beli terjadi secara merata di pertengahan awal dan akhir tahun. Kolom PeriodeTransaksi mencatat periode transaksi (Januari-Juni atau Juli-Desember). Fungsi table(…) menyajikan frekuensi masing-masing kategori.</em></blockquote><pre>table(estate$PeriodeTransaksi)<br>## EARLY  LATE <br>##   265   149</pre><blockquote><em>Apabila diperhatikan, transaksi properti lebih banyak dilakukan di pertengahan pertama tahunan (EARLY). Uji proporsi didesain untuk melihat apakah perbedaan ini hanya “kebetulan” saja atau tidak. Hipotesis yang digunakan adalah</em></blockquote><blockquote><em>- H0: p_Early = 0.5</em></blockquote><blockquote><em>- Ha: p_Early ≠ 0.5</em></blockquote><blockquote><em>Penggunaan hipotesis di atas dengan alasan sebagai berikut. Peneliti ingin menguji apakah proporsi transaksi EARLY dan LATE sama, atau dengan kata lain, <br> H0: p_Early = p_Late = 0.5</em></blockquote><blockquote><em>Anda dapat menyatakan x sebagai “banyaknya EARLY” atau “banyaknya LATE” dan memeroleh hasil yang identik.</em></blockquote><pre>prop.test(x = 265, n = 265+149, p = 0.5, alternative = &quot;two.sided&quot;, conf.level = 0.95)<br>##         1-sample proportions test with continuity correction<br>## <br>## data:  265 out of 265 + 149, null probability 0.5<br>## X-squared = 31.944, df = 1, p-value = 1.586e-08<br>## alternative hypothesis: true p is not equal to 0.5<br>## 95 percent confidence interval:<br>##  0.5915395 0.6860109<br>## sample estimates:<br>##         p <br>## 0.6400966</pre><blockquote><em>Hasil di atas menunjukkan p-value yang sangat kecil, artinya data mendukung penolakan H0. Proporsi transaksi pada EARLY berbeda signifikan dari 0.5, atau transaksi properti tidak merata sepanjang tahun.</em></blockquote><blockquote><em>*Catatan: Statistik uji dari R adalah X-squared (Chi-square) dengan df = 1 yang ekivalen dengan Z².</em></blockquote><blockquote><strong><em>Uji Proporsi Satu Sampel — Contoh 2 (Data: Jaksa)</em></strong></blockquote><blockquote><em>Seorang jaksa daerah ingin mencalonkan diri untuk jabatan jaksa kota. Dia memutuskan akan melepas jabatan lamanya jika lebih dari 90% pemilih partai mendukungnya. Untuk maksud tersebut, manajer kampanye dari partai tersebut melakukan survey terhadap 70 orang anggota partainya diambil secara random, untuk ditanyai setuju atau tidak terkait pencalonan jaksa tersebut. Didapat 54 orang menjawab setuju. Apa keputusan terbaik yang diambil jaksa tersebut?</em></blockquote><blockquote><em>Dalam kasus ini, n=70, p₀ = 0.9, dan x = 54. Perhatikan bahwa</em></blockquote><p>np₀ = 70 * 0.9 = 56 dan n(1-p₀) = 70 * 0.1 = 7</p><blockquote><em>yang menunjukkan bahwa asumsi sampel besar tak dipenuhi. Oleh karenanya, Anda menggunakan fungsi binom.test(…) dengan hipotesis sebagai berikut.</em></blockquote><blockquote><em>- H0: p₀ ≤ 0.9</em></blockquote><blockquote><em>- Ha: p₀ &gt; 0.9</em></blockquote><blockquote><em>Tingkat signifikansi yang digunakan adalah α = 5%. Diperoleh hasil sebagai berikut.</em></blockquote><pre>binom.test(x = 54, n = 70, p = 0.9, alternative = &quot;greater&quot;, conf.level = 0.95)<br>##         Exact binomial test<br>## <br>## data:  54 and 70<br>## number of successes = 54, number of trials = 70, p-value = 0.9996<br>## alternative hypothesis: true probability of success is greater than ## 0.9<br>## 95 percent confidence interval:<br>##  0.6737701 1.0000000<br>## sample estimates:<br>## probability of success <br>##              0.7714286</pre><blockquote><em>Nilai p-value yang diperoleh 0.9996 &gt; α = 5% menunjukkan H0 tidak ditolak. Artinya, pendukung jaksa tersebut kurang dari 90% dari partainya. Ia tidak disarankan untuk maju kampanye dan tetap pada jabatan lamanya.</em></blockquote><h3>Uji Mean Satu Sampel</h3><p>Uji mean satu sampel bertujuan untuk membandingkan sampel terhadap sebuah nilai tetap. Dengan kata lain, peneliti ingin menguji apakah mean populasi berbeda dari sebuah nilai.</p><p><strong>Asumsi:</strong></p><p>Uji mean satu sampel dapat dilakukan dengan uji t. Uji t mengasumsikan bahwa data sampel <strong>berdistribusi Normal</strong> dan <strong>observasi bersifat independen</strong>. Uji ini menggunakan statistik uji yang mengikuti distribusi Student’s t.</p><p><strong>Cara Analisis</strong></p><p>Untuk menjalankan analisis, gunakan fungsi t.test(…) pada R. Argumen yang Anda berikan adalah vektor data, hipotesis alternatif, mean pembanding yang diuji (μ₀), dan tingkat konfidensi (dalam desimal).</p><p>Misal μ menunjukkan mean populasi dan μ₀ adalah mean pembanding yang diuji. Terdapat 3 jenis hipotesis alternatif:</p><p>- “two.sided” digunakan ketika menguji Ha: μ ≠ μ₀</p><p>- “greater” digunakan ketika menguji Ha: μ &gt; μ₀</p><p>- “less” digunakan ketika menguji Ha: μ &lt; μ₀</p><p><strong>Alternatif</strong></p><p>Apabila asumsi Normalitas tidak dipenuhi, Anda dapat menggunakan uji Wilcoxon Sign Test.</p><pre># Contoh:<br>t.test(data, alternative = “greater”, mu = 100, conf.level = 0.95)</pre><blockquote><strong><em>Uji Mean Satu Sampel — Contoh 1 (Data: TaiwanEstate)</em></strong></blockquote><blockquote><em>Misal ingin diketahui apakah harga rata-rata bangunan di Taiwan lebih tinggi dari nilai yang diproyeksikan, yakni sekitar TWD 340.000/ping.</em></blockquote><blockquote>Normalitas</blockquote><blockquote><em>Lakukan uji Normalitas Shapiro-Wilk dengan hipotesis</em></blockquote><blockquote><em>· H0: Harga rata-rata bangunan per ping di Taiwan berasal dari populasi yang berdistribusi Normal</em></blockquote><blockquote><em>· Ha: Harga rata-rata bangunan per ping di Taiwan tidak berasal dari populasi yang berdistribusi Normal</em></blockquote><blockquote><em>tingkat signifikansi α = 5% dan diperoleh hasil berikut.</em></blockquote><pre>shapiro.test(estate$Harga)<br>##         Shapiro-Wilk normality test<br>## <br>## data:  df$Harga<br>## W = 0.99489, p-value = 0.1874</pre><blockquote><em>Diperoleh hasil p-value &gt; 5%, H0 tidak ditolak (harga bangunan berdistribusi Normal).</em></blockquote><blockquote>Uji t Mean Satu Sampel</blockquote><blockquote><em>Misal μ menunjukkan rata-rata harga bangunan per ping di Taiwan (dalam ribuan TWD) dan μ₀ adalah harga proyeksi. Hipotesis yang diajukan adalah</em></blockquote><blockquote><em>- H0: μ ≤ μ₀ = 340<br> Rata-rata harga bangunan per ping di Taiwan tidak lebih tinggi dari proyeksi</em></blockquote><blockquote><em>- Ha: μ &gt; μ₀ = 340<br> Rata-rata harga bangunan per ping di Taiwan lebih tinggi dari proyeksi</em></blockquote><blockquote><em>dengan tingkat signifikansi α = 5%.</em></blockquote><pre>t.test(estate$Harga, alternative = &quot;greater&quot;, mu = 340)<br>##         One Sample t-test<br>## <br>## data:  df$Harga<br>## t = 2.5932, df = 413, p-value = 0.004923<br>## alternative hypothesis: true mean is greater than 340<br>## 95 percent confidence interval:<br>##  341.9834      Inf<br>## sample estimates:<br>## mean of x <br>##  345.4447</pre><blockquote><em>Hasil di atas menunjukkan statistik uji t = 2.59 dan pval = 0.0049. Nilai pval &lt; α = 5% menunjukkan data mendukung penolakan H0. Dengan demikian, rata-rata harga bangunan di Taiwan lebih tinggi dari proyeksi secara signifikan pada taraf 5%.</em></blockquote><blockquote><strong><em>Uji Mean Satu Sampel — Contoh 2 (Data: Karyawan)</em></strong></blockquote><blockquote><em>Sebuah perusahaan sedang melakukan evaluasi kinerja karyawannya. Disinyalir bahwa keterlambatan karyawan merupakan faktor penting yang memengaruhi perusahaan. Jika rata — rata keterlambatan seluruh karyawan lebih dari 7 menit, akan diberlakukan kebijakan baru. Diambil sampel 50 karyawan dan diperoleh data keterlambatan. Apakah perusahaan perlu menetapkan kebijakan baru?</em></blockquote><blockquote>Uji Normalitas</blockquote><blockquote><em>Lakukan uji Normalitas Shapiro-Wilk dengan hipotesis</em></blockquote><blockquote><em>· H0: Rata-rata keterlambatan berasal dari populasi yang berdistribusi Normal</em></blockquote><blockquote><em>· Ha: Rata-rata keterlambatan tidak berasal dari populasi yang berdistribusi Normal</em></blockquote><blockquote><em>tingkat signifikansi α = 5% dan diperoleh hasil berikut.</em></blockquote><pre># Buka Data<br>karyawan &lt;- read_excel(path = &quot;C:\\Project\\Dataset.xlsx&quot;,<br>   sheet = &quot;Karyawan&quot;)<br>karyawan &lt;- as.data.frame(karyawan)<br><br># Uji Normalitas<br>shapiro.test(karyawan[,&#39;Menit Terlambat&#39;])<br>##         Shapiro-Wilk normality test<br>## <br>## data:  karyawan[, &quot;Menit Terlambat&quot;]<br>## W = 0.98022, p-value = 0.5614</pre><blockquote><em>Hasil tersebut menunjukkan p-value &gt; α = 5%, artinya data tidak mendukung penolakan H0. Data berdistribusi Normal.</em></blockquote><blockquote>Uji t Mean Satu Sampel</blockquote><blockquote><em>Selanjutnya, lakukan uji satu sampel t dengan hipotesis sebagai berikut.</em></blockquote><blockquote><em>- H0: μ ≤ μ₀ = 7<br> Rata-rata keterlambatan karyawan tidak lebih dari 7 menit</em></blockquote><blockquote><em>- Ha: μ &gt; μ₀ = 7<br> Rata-rata keterlambatan karyawan lebih dari 7 menit</em></blockquote><pre>t.test(karyawan[,&#39;Menit Terlambat&#39;], alternative = &quot;greater&quot;, mu = 7)<br>##         One Sample t-test<br>## <br>## data:  karyawan[, &quot;Menit Terlambat&quot;]<br>## t = 1.3555, df = 49, p-value = 0.09074<br>## alternative hypothesis: true mean is greater than 7<br>## 95 percent confidence interval:<br>##  6.833261      Inf<br>## sample estimates:<br>## mean of x <br>##    7.704</pre><blockquote><em>Diperoleh p-value = 0.09 &gt; α = 5%, artinya tidak cukup bukti bahwa rata-rata keterlambatan karyawan lebih dari 7 menit (H0 tidak ditolak). Akan tetapi, perusahaan dapat mengevaluasi kebijakan lebih lanjut karena nilai estimasi berada di ambang batas.</em></blockquote><blockquote><em>Peneliti juga dapat mengartikan hasil di atas dengan interval konfidensi. Dengan keyakinan 95%, peneliti meyakini bahwa rata-rata keterlambatan karyawan sekurang-kurangnya 6.8 menit.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ff414e45283" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Panduan Praktis Pemrograman R — Visualisasi Data]]></title>
            <link>https://medium.com/@mouse3mic3/panduan-praktis-pemrograman-r-visualisasi-data-424269dd8419?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/424269dd8419</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Thu, 16 May 2024 04:14:02 GMT</pubDate>
            <atom:updated>2024-05-16T04:14:02.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Panduan Praktis Pemrograman R — Visualisasi Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RkSCHJF2Y0LGM4al" /><figcaption>Photo by <a href="https://unsplash.com/@wezlar11?utm_source=medium&amp;utm_medium=referral">Dean Pugh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Artikel ini adalah bagian dari seri panduan praktis pemrograman R. Beberapa topik akan dibahas pada artikel di masa mendatang, termasuk inferensi populasi dan analisis regresi, semua dalam Bahasa Indonesia.</p><p>Tanda koma menyatakan ribuan, tanda titik menyatakan desimal.</p><h3>Visualisasi Data di R</h3><p>Data dalam bentuk visual lebih mudah untuk dipahami. Penentuan teknik visualisasi data menjadi penting dan perlu memerhatikan target <em>audience</em> Anda.</p><p>R menyediakan beberapa fungsi untuk menghasilkan <em>diagram</em> sederhana dan akan dibahas pada bab selanjutnya. Fungsionalitas ini sering disebut <em>Base R </em>Graphics dengan penggunaan yang relatif mudah.</p><p>Setiap fungsi dalam Base R Graphics memiliki beberapa argumen yang dapat Anda gunakan. Anda dapat melihat seluruh argumen penting di sini.</p><h3>Pustaka ggplot2</h3><p><em>ggplot2</em> adalah salah satu pustaka R populer untuk menghasilkan visualisasi data. <em>ggplot2</em> memiliki banyak fitur yang memungkinkan pengguna untuk mengatur visual sesuai keinginan.</p><p>Berbeda dari metode visualisasi pada umumnya, <em>ggplot</em>2 memecah tahapan visualisasi ke dalam beberapa bagian yang memungkinkan pengguna untuk mengatur bagaimana diagram tersebut bekerja. <em>ggplot2</em> mungkin terlihat lebih kompleks, akan tetapi, modul ini akan menunjukkan beberapa contoh sederhana yang selanjutnya dapat dikembangkan.</p><p>Gunakan perintah</p><pre># install ggplot2<br>install.packages(“ggplot2”)<br>library(ggplot2)</pre><h3>Dataset di R</h3><p>R menyediakan beberapa dataset standar yang dapat langsung Anda gunakan. Untuk melihat daftar dataset yang ada di R, gunakan fungsi <em>data()</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rxCKLWuof-TE6qmEIMAV4w.png" /><figcaption>Dataset di R</figcaption></figure><p>Untuk melihat atau menggunakan dataset, Anda dapat langsung menuliskan nama dataset tersebut.</p><pre>head(AirPassengers) # lihat 6 observasi pertama dari AirPassengers<br>##      Jan Feb Mar Apr May Jun<br>## 1949 112 118 132 129 121 135</pre><h3>Histogram</h3><p>Histogram adalah diagram yang tepat untuk melihat bagaimana data memusat dan menyebar, atau disebut distribusi data. Histogram cocok untuk data numerik, di mana ketinggian batang vertikal menunjukkan frekuensi munculnya data. Semakin tinggi batang vertikal, semakin banyak pula data pada rentang tersebut.</p><p>Untuk menyajikan sebuah histogram, Anda dapat menggunakan fungsi <em>hist(…)</em>. Fungsi ini menerima argumen berupa vektor numerik dan argumen lainnya yang akan dibahas.</p><p><strong>Histogram Sepal.Length pada data Iris</strong></p><pre># Gunakan kolom Sepal.Length dari dataset iris<br>sepal_length &lt;- iris$Sepal.Length <br><br># Tampilkan histogram<br>hist(sepal_length)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*Np6k9fOP0CfI5XMODSJyLw.png" /></figure><p><strong>Histogram — Mengatur Label Sumbu</strong></p><p>Anda dapat merubah label X dan Y, serta judul histogram.</p><pre>sepal_length &lt;- iris$Sepal.Length<br><br>hist(sepal_length,        # vektor data <br>  xlab = &quot;Sepal Length&quot;,  # Label sumbu X<br>  ylab = &quot;Frekuensi&quot;,     # Label sumbu Y<br>  main = &quot;Histogram Sepal Length, Iris&quot;) # Judul Histogram</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*quyqCsA-fUGFFya8TPfcfQ.png" /></figure><p><strong>Histogram — Menambah Kurva Padatan (Densitas)</strong></p><p>Apabila Histogram menyajikan frekuensi pada sumbu vertikal, Anda dapat menyajikan proposi (atau densitas/padatan) dengan kurva densitas.</p><p>Argumen freq mengatur apakah histogram menyajikan frekuensi (<em>TRUE</em>) atau bukan frekuensi (<em>FALSE</em>).</p><p>Anda dapat menghitung densitas dengan fungsi <em>density(…)</em>, menghasilkan sebuah vektor numerik. Untuk menambahkan garis pada sebuah diagram, Anda dapat menggunakan fungsi <em>lines(…)</em>.</p><pre>sepal_length &lt;- iris$Sepal.Length<br><br>hist(sepal_length,    # vektor data <br>  xlab = &quot;Sepal Length&quot;,  # Label sumbu X<br>  ylab = &quot;Frekuensi&quot;,  # Label sumbu Y<br>  main = &quot;Histogram Sepal Length, Iris&quot;, # Judul Histogram<br>  freq = FALSE)   # atur freq ke FALSE<br><br>den &lt;- density(sepal_length) # hitung densitas, berupa vektor<br>lines(den)    # tampilkan densitas</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*f65SIJsJ7SRSeqNonYgRBA.png" /></figure><p><strong>Histogram — Mengatur Binning dan Batas Sumbu</strong></p><p>Fungsi Histogram secara langsung menentukan <em>binning</em> (lebar / interval batang vertikal). Anda dapat menyesuaikan interval batang apabila dinilai kurang sesuai melalui argumen breaks. Nilai yang Anda berikan dapat berupa banyaknya batang yang diinginkan atau vektor berisi titik pemisah batang.</p><p>Anda juga dapat memberi batas untuk sumbu X dan Y dengan fungsi <em>xlim(…)</em> dan <em>ylim(…)</em>. Nilai yang diberikan berupa vektor dua angka untuk batas bawah dan atas.</p><pre>sepal_length &lt;- iris$Sepal.Length<br><br>hist(sepal_length,        # vektor data <br>  xlab = &quot;Sepal Length&quot;,  # Label sumbu X<br>  ylab = &quot;Frekuensi&quot;,     # Label sumbu Y<br>  main = &quot;Histogram Sepal Length, Iris&quot;, # Judul Histogram<br>  breaks = 30,            # Atur breaks lebih besar<br>  xlim = c(3, 9),         # Beri batas sumbu X dari 3 - 9<br>  ylim = c(0, 12)         # Beri batas sumbu Y dari 0 - 12<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*TiQOG35MOieFZIfGqule4Q.png" /></figure><p><strong>Histogram — Mengatur Warna Histogram</strong></p><p>Anda bisa menggunakan argumen col pada fungsi hist(…). Argumen ini mengatur warna batang histogram. Anda dapat memberikan string nama warna, kode hexadesimal RGB, dan sebuah vektor warna.</p><p>Di bawah ini adalah contoh menggunakan nama warna dan kode RGB heksadesimal. Anda dapat melihat daftar nama warna di laman <a href="https://www.datanovia.com/en/blog/awesome-list-of-657-r-color-names/">ini</a>.</p><pre>sepal_length &lt;- iris$Sepal.Length<br><br>hist(sepal_length,  <br>  col = &quot;lightsalmon2&quot;<br>)<br><br>hist(sepal_length, <br>  col = &quot;#533685&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*NgudIfxSaEbUdad77NmSeQ.png" /></figure><h3>Boxplot</h3><p>Boxplot merupakan cara lain untuk menyajikan distribusi variabel numerik. Boxplot memberikan informasi mengenai kuartil pertama, kedua, dan ketiga, serta jangkauan (<em>range</em>) data.</p><p><strong>Boxplot</strong></p><pre>petal_length &lt;- iris[&quot;Petal.Length&quot;]<br>boxplot(petal_length,   # data<br> ylab = &quot;Length (cm)&quot;,  # label sumbu Y<br> main = &quot;Iris: Petal Length&quot;, # judul<br> col = &quot;maroon&quot;,        # warna boxplot<br> lwd = 2                # ketebalan garis<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*3sRkO9PzhfEaS64NB4xHOg.png" /></figure><p><strong>Boxplot — Data Frame</strong></p><pre>sepal_petal &lt;- iris[c(&quot;Sepal.Length&quot;, &quot;Sepal.Width&quot;, &quot;Petal.Length&quot;, &quot;Petal.Width&quot;)]<br><br>boxplot(sepal_petal,<br> col = rainbow(4),      # Ambil 4 warna dari rainbow<br> xlab = &quot;Kolom Data&quot;,   # Label sumbu X<br> ylab = &quot;Length (cm)&quot;,  # Label sumbu Y<br> main = &quot;Iris Dataset&quot;) # Judul Plot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*LmWNeHno9dWcLa4XpCOexg.png" /></figure><p><strong>Boxplot — Data Memanjang (<em>Long Data</em>)</strong></p><p>Apabila Anda ingin menyajikan Boxplot dengan data berbentuk memanjang (<em>long data</em>) seperti dataset <em>InsectSprays</em>, Anda dapat menggunakan formula.</p><p>Dataset <em>InsectSprays</em> memiliki dua kolom. Kolom spray adalah kolom kategorik. Misal diinginkan sebuah boxplot untuk masing-masing kategori spray.</p><pre>head(InsectSprays) # Tampilkan 6 baris pertama dataset<br>##   count spray<br>## 1    10     A<br>## 2     7     A<br>## 3    20     A<br>## 4    14     A<br>## 5    14     A<br>## 6    12     A<br><br>boxplot(count ~ spray,   # Kolom dataframe yang digunakan<br>  data = InsectSprays,   # Dataframe yang digunakan<br>  col = rainbow(6),      # Warna boxplot<br>  main = &quot;Insect Sprays&quot;, # Judul plot<br>  #boxwex = 0.5,         # Skala ukuran boxplot<br>  border = &quot;red&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*mnwhAkjn07vPpQ3yZEL53g.png" /></figure><h3>Barplot / Diagram Batang</h3><p>Barplot atau diagram batang mirip seperti histogram, yakni menunjukkan perbandingan frekuensi suatu variabel. Hanya saja, barplot ditujukan untuk variabel kategorik. Batang vertikal menunjukkan frekuensi sebuah kategori.</p><p>Untuk dapat menggunakan barplot, Anda memerlukan sebuah vektor nama kategori dan vektor lain yang menunjukkan frekuensi kategori.</p><p><strong>Barplot</strong></p><p>Berikut adalah contoh barplot untuk data kategori sederhana.</p><p>month.abb menyediakan 12 nama bulan. Contoh dibawah mengambil 7 bulan pertama. Pengguna baru adalah frekuensi di setiap bulan.</p><p>Nama kategori diberikan pada argumen names.arg. Anda dapat menggunakan pengaturan tambahan seperti xlab dan ylab yang telah ditunjukkan di histogram sebelumnya.</p><pre>bulan &lt;- month.abb[1:7]<br>pengguna_baru &lt;- c(132, 144, 165, 123, 134, 98, 113)<br><br>barplot(pengguna_baru,     # Vektor frekuensi<br>  names.arg = bulan,       # Nama kategori<br>   xlab = &quot;Bulan&quot;,         # label sumbu X dan Y<br>   ylab = &quot;# Pengguna Baru&quot;,<br>   main = &quot;Pengguna Baru Per Bulan&quot; # Judul Plot<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*vtTVzWVNZPHtYZmLUXmLMw.png" /></figure><p><strong>Barplot — Mengatur Warna</strong></p><p>Warna barplot dapat disesuaikan dengan memberikan vektor warna untuk masing-masing kategori. Anda juga dapat menggunakan palet warna yang sudah tersedia di R atau membuat palet warna Anda sendiri.</p><p>Palet warna yang sudah tersedia adalah <em>rainbow(n)</em>, <em>heat.colors(n)</em>, <em>terrain.colors(n)</em>, <em>topo.colors(n)</em>, dan <em>cm.colors(n)</em>. Argumen n dapat Anda ganti dengan banyaknya kategori.</p><pre>bulan &lt;- month.abb[1:7]<br>pengguna_baru &lt;- c(132, 144, 165, 123, 134, 98, 113)<br>warna &lt;- c(&quot;skyblue&quot;, &quot;skyblue1&quot;, &quot;skyblue2&quot;, &quot;skyblue3&quot;, &quot;skyblue4&quot;,<br>  &quot;slateblue&quot;, &quot;slateblue1&quot;)<br><br>barplot(pengguna_baru, <br>   names.arg = bulan,<br>   col = warna   # vektor warna untuk setiap batang<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*1T1893dSs2gHUbxFax3SRA.png" /></figure><p><strong>Barplot — Kolom Data Frame Kategorik</strong></p><p>Apabila dimiliki sebuah kolom (atau vektor) kategorik, Anda dapat menggunakan fungsi <em>table(…)</em> yang secara otomatis menghitung frekuensi untuk setiap kategori.</p><p>Di bawah ini merupakan contoh menggunakan data infert yang menunjukkan infertilitas setelah aborsi. Kolom education merupakan kolom kategorik, menunjukkan lama pendidikan yang telah ditempuh.</p><p>Perhatikan fungsi <em>table(…)</em> menghasilkan tabel. Baris pertama menunjukkan kategori, baris kedua menunjukkan frekuensi.</p><pre>edukasi &lt;- table(infert$education)<br>edukasi<br>## 0-5yrs 6-11yrs 12+ yrs  # kategori<br>##     12     120     116 # frekuensi<br><br># Barplot dengan R color palette<br>barplot(edukasi,<br>   col = heat.colors(n = 3), # Gunakan n = 3 kategori<br>   horiz = TRUE,             # Barplot Horizontal<br>   space = 0.0,              # Atur jarak antar batang<br>   density = 50,             # Ketebalan warna barplot<br>   border = &quot;white&quot;,         # Warna border<br>  <br>   main = &quot;Tingkat Edukasi&quot;,  # Judul plot<br>   sub = &quot;Infertility Dataset, R&quot;, # Subjudul plot<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*jRUjZEN8779uCWFQ2e0CdA.png" /></figure><p><strong>Barplot — <em>Stacked Barplot</em></strong></p><p><em>Stacked </em>barplot berguna untuk menyajikan frekuensi dari beberapa kolom kategorik sekaligus. Misalnya dalam data infert, Anda ingin menyajikan frekuensi edukasi dan case.</p><pre>educase &lt;- infert[c(&quot;education&quot;, &quot;case&quot;)] # ambil dua kolom kategorik<br>tab_educase &lt;- table(educase)   # gunakan fungsi table<br>tab_educase      <br>##          case<br>## education  0  1<br>##   0-5yrs   8  4<br>##   6-11yrs 80 40<br>##   12+ yrs 77 39<br><br>b &lt;- barplot(tab_educase,<br>  beside = TRUE,               # Untuk stacked barplot<br>  col = terrain.colors(n = 3), # Tiga warna untuk 3 case<br>  xlab = &quot;Case&quot;,               # label sumbu X<br>  main = &quot;Frekuensi Edukasi per Case&quot;, # Judul plot<br>  # Atur Legenda<br>  legend.text = TRUE,<br>  args.legend = list(title = &quot;Edukasi&quot;),<br>  # Atur range sumbu Y agar tidak ada yang terpotong<br>  ylim = c(0, 85) <br>)<br># Tampilkan label frekuensi<br>ypos &lt;- tab_educase + 2  <br>text(b, ypos, tab_educase)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*GEiHEtHaHEBMan3nFpBPuw.png" /></figure><h3>Pieplot / Diagram Lingkaran</h3><p>Sama halnya dengan barplot, pieplot digunakan untuk menyajikan frekuensi data kategorik.</p><p><strong>Pieplot</strong></p><pre>edukasi &lt;- table(infert$education)<br><br># Hitung persentase masing-masing kategori<br>persen &lt;- round(100 * edukasi / sum(edukasi), 1)<br>persen_label &lt;- paste(names(edukasi), &quot;(&quot;, persen, &quot;%)&quot;, sep = &quot;&quot;)<br><br>pie(edukasi, <br> labels = persen_label,    # Label dengan persentase<br> col = c(&quot;seagreen4&quot;, &quot;slateblue4&quot;, &quot;red4&quot;),<br> border = &quot;white&quot;,         # Warna border<br> main = &quot;Lama Pendidikan&quot;, # Judul<br> radius = 1                # Ukuran pieplot<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*pRM7nLUU9J1JvUylYu1UwA.png" /></figure><p><strong>Pieplot — 3D</strong></p><p>Anda dapat menggunakan pustaka plotrix untuk menampilkan pieplot 3D.</p><pre>install.packages(“plotrix”)<br>library(plotrix)<br><br>pie3D(edukasi,<br> labels = persen_label,<br> col = c(&quot;seagreen4&quot;, &quot;slateblue4&quot;, &quot;red4&quot;),<br> main = &quot;Lama Pendidikan&quot;,<br> explode = 0.1<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*vsWg5pTp1Yo9Nlg3K-xzBw.png" /></figure><h3>Scatterplot</h3><p>Scatterplot menggambarkan hubungan antara dua variabel melalui sumbu X dan Y. Scatterplot sering digunakan dalam analisis regresi untuk melihat ada tidaknya hubungan linear antara prediktor dan respon.</p><p>Untuk menampilkan scatterplot, gunakan fungsi <em>plot(…)</em>.</p><p><strong>Scatterplot</strong></p><pre>hp &lt;- mtcars$hp<br>mpg &lt;- mtcars$mpg<br><br>par(bg = &quot;seashell2&quot;) # atur warna latar plot<br>plot(x = hp,          # vektor yang akan di plot<br>  y = mpg, <br>  type = &quot;p&quot;,         # gunakan p untuk &quot;points&quot; atau titik<br>  pch = 19,           # jenis titik<br>  cex = 0.85,         # ukuran titik<br>  col = &quot;orangered4&quot;, # warna titik<br> <br> # atur font<br>  family = &quot;serif&quot;,<br>  font = 2,<br>  main = &quot;Horsepower vs Miles-per-gallon&quot;,<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*hrTaXDkEAmPK8FOpt4iXfA.png" /></figure><p><strong>Scatterplot — Garis Regresi</strong></p><p>Anda dapat menambahkan garis regresi antara mpg dan hp dengan menggunakan fungsi abline. Anda juga dapat mengatur jenis garis yang ditampilkan.</p><pre>hp &lt;- mtcars$hp<br>mpg &lt;- mtcars$mpg<br><br>par(bg = &quot;seashell2&quot;) # atur warna latar plot<br>plot(x = hp,          # vektor yang akan di plot<br>  y = mpg, <br>  type = &quot;p&quot;,         # gunakan p untuk &quot;points&quot; atau titik<br>  pch = 19,           # jenis titik<br>  cex = 0.85,         # ukuran titik<br>  col = &quot;orangered4&quot;, # warna titik<br> <br> # atur font<br>  family = &quot;serif&quot;,<br>  font = 2,<br>  main = &quot;Horsepower vs Miles-per-gallon&quot;,<br>)<br><br># Tambahkan garis regresi<br>abline(lm(mpg~hp),  # y ~ x<br>     lwd = 1.5,  # ketebalan garis<br>    lty = 2,  # tipe garis terputus<br>  col = &quot;red4&quot; # warna garis<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*b3xzcdEkOzGM7SfchQRjZA.png" /></figure><p><strong>Scatterplot — Skala Log</strong></p><p>Anda dapat menggunakan skala logaritmik untuk sumbu X maupun Y dengan argumen log.</p><pre>hp &lt;- mtcars$hp<br>mpg &lt;- mtcars$mpg<br><br>par(bg = &quot;seashell2&quot;) # atur warna latar plot)<br><br>plot(x = hp,   # vektor yang akan di plot<br> y = mpg, <br> type = &quot;p&quot;,  # gunakan p untuk &quot;points&quot; atau titik<br> pch = 19,    # jenis titik<br> cex = 0.85,  # ukuran titik<br> col = &quot;orangered4&quot;, # warna titik<br><br> ylab = &quot;Log(mpg)&quot;,# Label sumbu Y<br> las = 1,  # Atur agar anotasi sumbu selalu horizontal<br><br> # atur font<br> family = &quot;serif&quot;,<br> font = 2,<br> main = &quot;Horsepower vs Miles-per-gallon&quot;,<br><br> log = &quot;y&quot;  # log dapat bernilai x, y, atau xy<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*L4SPo-oyHIUV1Ol8lIqsww.png" /></figure><h3>Lineplot / Diagram Garis</h3><p>Lineplot cocok untuk digunakan pada data deret waktu / data yang berevolusi. Umumnya, sumbu X menunjukkan indeks waktu dan sumbu Y menunjukkan nilai pada waktu tersebut.</p><p>Pembentukan lineplot serupa dengan scatterplot, yakni dengan fungsi <em>plot(…)</em>, akan tetapi dengan argumen <em>type = “l”</em>.</p><p><strong>Lineplot</strong></p><p>Untuk menggunakan lineplot, Anda harus memiliki vektor tanggal/indeks dan vektor nilai.</p><pre># Vektor tanggal bulanan dari Jan 2023 - Des 2023<br>tanggal &lt;- seq(from = as.Date(&quot;2023-01-01&quot;), <br>to = as.Date(&quot;2023-12-01&quot;), <br>by = &quot;month&quot;)<br><br>sales &lt;- c(123, 42, 323, 233, 295, 317, 328, 409, 398, 417, 425, 456)<br><br>g &lt;- plot(x = tanggal,<br> y = sales,<br> type = &quot;l&quot;, # Atur type menjadi l<br> lwd = 3,  # tebal garis<br> main = &quot;Monthly Sales&quot;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*4HJV65r5345UvbzxHZQQzA.png" /></figure><p><strong>Lineplot — Anotasi Tertinggi</strong></p><p>Anda dapat menambahkan sebuah titik atau teks pada sebuah plot.</p><pre># Vektor tanggal bulanan dari Jan 2023 - Des 2023<br>tanggal &lt;- seq(from = as.Date(&quot;2023-01-01&quot;), to = as.Date(&quot;2023-12-01&quot;), by = &quot;month&quot;)<br>sales &lt;- c(123, 42, 323, 233, 295, 317, 328, 409, 398, 417, 425, 456)<br>plot(x = tanggal,<br> y = sales,<br> type = &quot;l&quot;,   # Atur type menjadi l<br> lwd = 3,      # tebal garis<br> main = &quot;Monthly Sales&quot;<br>)<br><br># Tambahkan sales tertinggi<br>id &lt;- which.max(sales)   # Ambil indeks dengan sales tertinggi<br>points(x = tanggal[id],  # Titik sales tertinggi<br> y = sales[id],<br> col = &quot;red&quot;,<br> pch = 16<br>)<br>text(x = tanggal[id] - 50, # Teks sales tertinggi<br> y = sales[id],<br> paste(&quot;max sales:&quot;, sales[id])<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*IAPPlLrX92pYK-j2BONuqg.png" /></figure><p><strong>Lineplot — Objek TS</strong></p><p>Apabila Anda sudah memiliki objek dengan tipe timeseries, Anda dapat langsung menggunakan fungsi <em>plot(…)</em> tanpa argumen type. Untuk membuat objek timeseries, Anda dapat menggunakan fungsi <em>ts(…)</em>.</p><p>Contoh di bawah ini memperlihatkan dataset AirPassengers yang sudah berbentuk timeseries serta pengambilan subset dari AirPassengers.</p><pre>plot(AirPassengers,<br> main = &quot;Air Passengers&quot;)<br><br># Tampilkan AirPassengers dari 1955<br>air_1955 &lt;- window(AirPassengers, start = 1955, end = 1960)<br>plot(air_1955, main = &quot;Air Passengers since 1955&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*PgN8V4gMWO3YFO04Sulb8g.png" /></figure><p><strong>Lineplot — Multivariat / Multipel Lineplot</strong></p><p>Apabila Anda memiliki beberapa data timeseries dengan interval waktu yang sama, Anda dapat langsung menampilkan seluruh data dengan fungsi <em>matplot(…)</em>.</p><p>Dataset EuStockMarkets memiliki empat saham.</p><pre># Siapkan empat warna untuk empat data<br>colors &lt;- c(&quot;tomato&quot;, &quot;springgreen&quot;, &quot;steelblue&quot;, &quot;wheat&quot;)<br><br># Gunakan fungsi matplot<br>matplot(EuStockMarkets, type = &quot;l&quot;, col = colors)<br><br># Tambah legenda<br>legend(&quot;topleft&quot;, legend = colnames(EuStockMarkets), col = colors, lty = 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*ilBUb0p2u9Nt62n04ETM_w.png" /></figure><h3>Multipel Plot</h3><p>Anda dapat menyajikan beberapa plot sekaligus dengan mengatur argumen mfrow pada fungsi <em>par(…)</em>. Fungsi <em>par(…)</em> digunakan untuk mengatur tampilan plot secara umum, seperti font, ukuran garis, dan sebagainya.</p><p><strong>Multipel Plot — 2x2</strong></p><p>Perhatikan beberapa argumen dituliskan di par(…) dan bukan di plot(…). Daftar argumen untuk par(…) dicantumkan di bagian akhir.</p><pre>par(bg = &quot;seashell2&quot;,<br> family = &quot;serif&quot;, font = 2,<br> mfrow = c(2,2), pch = 19, cex = 0.85,<br> oma = c(0, 0, 2, 0)<br>)<br><br># Plot 1 - Scatterplot HP vs MPG<br>plot(x = mtcars$hp,<br> y = mtcars$mpg,<br> col = &quot;orangered4&quot;,<br> main = &quot;Hp vs MpG&quot;)<br><br># Plot 2 - Barplot Silinder Mesin<br>cy = table(mtcars$cyl)<br>barplot(cy,<br> col = heat.colors(3),<br> main = &quot;Silinder Mesin&quot;)<br><br># Plot 3 - Histogram Berat Mobil<br>hist(mtcars$wt, col = &quot;orangered2&quot;, freq = FALSE,<br> main = &quot;Bobot Mobil&quot;)<br>lines(density(mtcars$wt))<br><br># Plot 4 - Pieplot 3D Gear<br>gear &lt;- table(mtcars$gear)<br>persen &lt;- round(100 * gear / sum(gear), 1)<br>persen_label &lt;- paste(names(gear), &quot; Gear (&quot;, persen, &quot;%)&quot;, sep = &quot;&quot;)<br>pie3D(gear, labels = persen_label, labelcex = 0.8,<br> main = &quot;N Gear&quot;)<br><br># Judul<br>title(&quot;Data: mtcars&quot;, outer = TRUE, cex.main = 2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*_1Sy_SUAKNZy75JFftMjsw.png" /></figure><h3>Referensi Argumen par(…)</h3><p>Seluruh argumen ini dapat Anda gunakan di fungsi par(…).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*zWbdebGERlwZilKUpoiJNg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*It0HKJi9VNn5PJ09gN25DA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=424269dd8419" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Panduan Praktis Pemrograman R — Pengenalan]]></title>
            <link>https://medium.com/@mouse3mic3/panduan-praktis-pemrograman-r-pengenalan-775a01eaf7a3?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/775a01eaf7a3</guid>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Thu, 16 May 2024 03:17:41 GMT</pubDate>
            <atom:updated>2024-05-16T08:24:26.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Panduan Praktis Pemrograman R — Pengenalan</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qyjceYjZzZOwt9PJ" /><figcaption>Photo by <a href="https://unsplash.com/@wezlar11?utm_source=medium&amp;utm_medium=referral">Dean Pugh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Artikel ini adalah bagian dari seri panduan praktis pemrograman R. Beberapa topik akan dibahas pada artikel di masa mendatang, termasuk inferensi populasi dan analisis regresi, semua dalam Bahasa Indonesia.</p><p>Tanda koma menyatakan ribuan, tanda titik menyatakan desimal.</p><h3>Tentang R</h3><p>R merupakan bahasa pemrograman yang ditujukan untuk analisis, komputasi, dan visualisasi data. R menyediakan berbagai jenis analisis data, seperti model linear dan non-linear, analisis runtun waktu, analisis Bayesian, hingga pembelajaran mesin (<em>machine learning</em>). R bertipe gratis dan open-source.</p><h3>Instalasi</h3><p>Modul ini akan menggunakan R versi 4.3.2 pada sistem operasi Windows. Untuk mengunduh R, Anda dapat mengunjungi laman <a href="https://cloud.r-project.org/">R-Project</a> dan memilih versi sesuai dengan sistem operasi Anda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*blIaAmotvUix81-GDsgXfQ.png" /><figcaption>CRAN</figcaption></figure><p>Setelah instalasi selesai, Anda dapat memulai R dengan menjalankan R-GUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*3HwZjlvitncAaa_kf67eFQ.png" /><figcaption>Tampilan R-GUI</figcaption></figure><p>Dalam jendela R Console, Anda dapat menjalankan analisis yang diharapkan. RGUI menyediakan tiga jenis jendela utama, yakni R Console, R Script, dan Graphics.</p><h3>R Console</h3><p>R Console adalah jendela utama R. Seluruh perintah dan hasil analisis akan dijalankan di R Console. Anda hanya dapat membuka satu R Console.</p><p>Silakan ketik potongan kode berikut pada jendela R Console dan tekan ENTER. Anda akan mendapatkan luaran <em>[1] 183.3333</em> yang merupakan mean (rata-rata) dari data tersebut sebesar 183.3333. Anda tidak perlu menghiraukan <em>[1]</em>.</p><pre>mean(c(100,200,250))</pre><h3>R Script Editor</h3><p>R Script memungkinkan Anda untuk menulis kode yang terdiri dari beberapa baris, menjalankannya berulang-ulang, dan menyimpannya untuk digunakan di lain waktu.</p><p><strong>Membuat R Script</strong></p><p>Untuk membuka jendela R Script, Anda dapat memilih menu <em>File &gt; New Scripts</em>. Dalam jendela R Script, silakan ketik potongan kode berikut.</p><pre>x &lt;- c(10, 20, 30)<br>y &lt;- c(1, 2, 3)<br>summary(lm(y ~ x))</pre><p>Potongan kode dalam R Script tidak akan dijalankan secara otomatis oleh R. Untuk menjalankannya, <em>highlight </em>baris kode yang ingin Anda jalankan, kemudian tekan <em>Ctrl + R</em>.</p><p>Setiap baris yang Anda jalankan akan dikirim ke R Console. Anda dapat melihat luaran analisis pada R Console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*y8J9kbelMJXbnNM6ZaL7pQ.png" /><figcaption>Contoh Luaran (Output) Kode</figcaption></figure><p>Anda tidak harus menjalankan seluruh baris dalam R Script. Anda juga dapat membuka beberapa jendela R Script dalam satu waktu.</p><p><strong>Menyimpan dan Membuka R Script</strong></p><p>Anda dapat memilih jendela R Script, kemudian menuju menu <em>File &gt; Sav</em>e. Untuk membuka file R Script, Anda dapat memilih menu <em>File &gt; Open Script</em>.</p><p><strong>Menambahkan Komentar</strong></p><p>Anda dapat memberikan komentar / penjelasan dalam kode Anda dengan menambahkan tanda <em>#</em> di awal kalimat.</p><pre>data &lt;- read.delim(&#39;...&#39;)<br># Baris setelah tanda # tidak akan dijalankan oleh R.<br>lm(y~x, data)</pre><h3>R Graphics</h3><p>Jendela R Graphics akan muncul secara otomatis apabila Anda ingin menyajikan sebuah diagram atau <em>plot</em>.</p><p>Misal ingin ditampilkan sebuah histogram bilangan acak berdistribusi Normal. Jalankan kode berikut di R Console atau R Script.</p><pre>hist(rnorm(1000))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*fXIN7EOUAHIZYRFnG3TirA.png" /><figcaption>Histogram Normal</figcaption></figure><p>Anda akan mendapatkan jendela baru yang menampilkan histogram.</p><h3>R-Studio</h3><p>R-Studio merupakan GUI (<em>Graphical User Interface</em>) populer yang memberikan tampilan modern untuk R. R-Studio bersifat opsional dan Anda dapat mengunduhnya melalui laman <a href="https://posit.co/download/rstudio-desktop/">posit</a>.</p><h3>Mendefinisikan dan Menghapus Objek di R</h3><p><strong>Mendefinisikan Objek</strong></p><p>Angka, data, hasil analisis, dan lainnya lainnya dapat disimpan dalam sebuah variabel (atau disebut objek). Gunakan operator penugasan (<em>assignment operator</em>) yaitu &lt;- atau =. Operator &lt;- lebih umum digunakan.</p><p>Anda dapat memberikan nama apapun untuk objek Anda, asalkan memenuhi ketentuan berikut.</p><p>· Diawali dengan huruf atau titik.</p><p>· Setelahnya dapat menggunakan huruf, angka, <em>underscore</em>, dan titik.</p><p>· Nama objek bersifat <em>case-sensitive</em>. Data dan data adalah dua objek berbeda.</p><p>· Hindari kata-kata tertentu, seperti <em>if, for, function, else</em>.</p><p><strong>Menampilkan Objek</strong></p><p>Untuk menampilkan nilai suatu objek, ketikkan nama objek tersebut.</p><p><strong>Menghapus Objek</strong></p><p>Untuk menghapus objek, gunakan fungsi <em>rm(nama.objek)</em>. Tindakan ini opsional, namun berguna untuk mengurangi penggunaan memori.</p><pre># Penamaan yang benar<br>dataku &lt;- c(12, 32, 33)<br>analisis_17 &lt;- dataku + 2<br>Model_A &lt;- lm(c(17, 18) ~ c(1, 2))<br><br># Penamaan yang salah<br>2023_temperatur &lt;- 20<br>_kuadrat &lt;- 4^2<br><br># Tampilkan objek dataku<br>dataku<br><br># Hapus objek dataku<br>rm(dataku)</pre><h3>Tipe Data Dasar</h3><h4>Tipe Data Numerik</h4><p>Tipe data numerik dapat menggambarkan bilangan bulat (<em>integer</em>) maupun desimal. Setiap bilangan Real akan otomatis memiliki tipe numerik. Apabila Anda ingin menggunakan tipe integer, Anda dapat membubuhi huruf <em>L</em> di akhir angka.</p><pre>alpha &lt;- 18.5     # numerik<br>beta &lt;- 17L       # integer<br>gamma &lt;- 18.6L    # ?</pre><h4>Tipe Data Karakter</h4><p>Data berupa teks (<em>string</em>) memiliki tipe karakter. Karakter tidak terbatas pada huruf saja. Data numerik dan lainnya dapat disimpan dalam tipe karakter. Gunakan tanda petik (atau petik dua) di awal dan akhir teks.</p><pre>delta &lt;- &quot;Rp 13.000,00&quot;<br>epsilon &lt;- &#39;Felis catus&#39;</pre><h4>Tipe Data Boolean</h4><p>Boolean terdiri dari dua nilai, yaitu TRUE dan FALSE. Umumnya Boolean digunakan dalam operasi perbandingan untuk mengetahui apakah kondisi tertentu sudah dipenuhi.</p><pre>zeta &lt;- FALSE<br>eta &lt;- T  # anda dapat menyingkat TRUE dan FALSE</pre><h4>Tipe Data Faktor</h4><p>Faktor umumnya digunakan untuk data kategorik, seperti jenis kelamin atau jenis perlakuan. Faktor mengandung <em>Levels</em> yang menunjukkan kategori dalam data.</p><pre>lambda &lt;- factor(c(&quot;PRIA&quot;, &quot;PRIA&quot;, &quot;WANITA&quot;, &quot;PRIA&quot;, &quot;WANITA&quot;, &quot;WANITA&quot;))<br>lambda  # tampilkan objek lambda<br>## [1] PRIA   PRIA   WANITA PRIA   WANITA WANITA<br>## Levels: PRIA WANITA</pre><h3>Vektor</h3><h4>Mendefinisikan Vektor</h4><p>Vektor adalah sekumpulan objek dengan tipe yang sama. Untuk mendefinisikan vektor, gunakan fungsi <em>c(..)</em>. Fungsi ini disebut fungsi <em>concatenate</em>.</p><pre>vektorku &lt;- c(12, 24, 36, 48) <br>vektorku  # tampilkan objek vektorku<br>## [1] 12 24 36 48</pre><h4>Mengambil Elemen Vektor dengan Indeks Posisi</h4><p>Objek vektorku di atas mengandung empat elemen numerik. Untuk mengakses elemen tertentu, Anda dapat menggunakan notasi kurung persegi <em>[…]</em> dan memasukkan indeks elemen.</p><pre>vektorku[1]        # ambil elemen pertama <br><br>v4 &lt;- vektorku[4]  # ambil elemen keempat, simpan di objek lain<br><br>vektorku[-1]       # ambil semua kecuali elemen pertama<br><br>vektorku[c(2,3)]   # ambil elemen kedua dan ketiga <br><br>vektorku[1:3]      # ambil elemen pertama hingga ketiga</pre><h4>Mengambil Elemen Vektor dengan Indeks Logis</h4><p>Cara lain untuk mengambil elemen adalah dengan memberikan sebuah ekspresi logis. Tabel di bawah ini menunjukkan operator logika yang dapat digunakan untuk membandingan dua objek.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*uLj6rp6mbXyBLK7zCpmAeQ.png" /><figcaption>Tabel Operator Perbandingan R</figcaption></figure><pre>vektorku[vektorku &gt; 20]  # Ambil elemen lebih besar dari 20<br>## [1] 24 36 48<br><br>vektorku[vektorku &gt; 20 &amp; vektorku &lt; 40] # Elemen diantara 20 dan 40<br>## [1] 24 36</pre><p>Dalam contoh di atas, ekspresi <em>vektorku &gt; 20</em> memberikan nilai berupa:</p><pre>vektorku &gt; 20<br>## [1] FALSE TRUE TRUE TRUE</pre><p>menunjukkan bahwa elemen pertama (FALSE) tidak memenuhi kondisi, sedangkan elemen kedua hingga keempat (TRUE) memenuhi kondisi.</p><p>Semua elemen yang berkorespondensi dengan TRUE akan diambil.</p><h4>Merubah Elemen</h4><p>Untuk merubah elemen, gunakan notasi kurung persegi <em>[…]</em> dan operator penugasan <em>&lt;-</em>.</p><pre>vektorku[2] &lt;- 100  # ubah elemen kedua menjadi 100<br>vektorku     <br>## [1]  12 100  36  48<br><br>vektorku[c(3,4)] &lt;- c(27, 28) # ubah elemen ketiga dan keempat<br>vektorku<br>## [1]  12 100  27  28</pre><h3>Pengecekan dan Konversi Tipe Data</h3><p>Anda dapat mengecek tipe data sebuah variabel serta mengubah ke tipe data lainnya dengan fungsi berikut.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*G8t7uynxmI2thK1ACuv30Q.png" /><figcaption>Cek dan Konversi Tipe Data secara coercing</figcaption></figure><p>Anda juga dapat melihat tipe data sebuah objek dengan fungsi <em>class(objek)</em>.</p><pre>obj_num &lt;- 689.19<br><br># cek apakah numerik<br>is.numeric(obj_num)<br>## [1] TRUE<br><br># Konversi ke integer sama seperti pembulatan<br>as.integer(obj_num)<br>## [1] 689<br><br># Konversi ke Boolean/Logis<br># Semua bilangan selain 0 dianggap TRUE<br>as.logical(obj_num)<br>## [1] TRUE<br><br>as.logical(0)<br>## [1] FALSE<br><br>as.logical(&quot;ABC&quot;)<br>## [1] NA<br><br># Umumnya string / karakter tidak bisa dikonversi langsung<br>obj_char &lt;- &quot;Sampel 1970&quot;<br>as.numeric(obj_char)<br>## [1] NA<br>## Warning message:<br>## NAs introduced by coercion</pre><h3>Operasi Aritmatika</h3><p>R mendukung operasi artimatika dasar, seperti penjumlahan, pengurangan, perkalian, pembagian, dan kuadrat. Operasi ini berlaku pula bagi vektor.</p><pre>13 + 8                      # penjumlahan<br>## [1] 21<br><br>vektorku &lt;- c(5, 7, 9)<br>vektorku_lagi &lt;- c(1, 2, 3)<br>vektorku + vektorku_lagi    # penjumlahan antar vektor<br>[1]  6  9 12<br><br>7 – 9                       # pengurangan<br>## [1] -2<br><br>vektorku * 2                # perkalian<br>[1] 10 14 18<br><br>12/5                        # pembagian<br>## [1] 2.4  <br><br>4 ** 3                      # perpangkatan<br>## [1] 64<br><br>4 ^ 0.5                     # perpangkatan<br>## [1] 2<br><br>theta &lt;- 4<br>theta + 8   <br>## [1] 12  <br><br>theta                        # perhatikan bahwa nilai theta tetap 4<br>## [1] 4<br><br>theta &lt;- theta + 8           # untuk mengubah nilai theta<br>theta<br>## [1] 12</pre><p>Untuk mencari akar kuadrat, logaritma, dan antilog, Anda dapat menggunakan fungsi yang tersedia di R.</p><pre>sqrt(16)       # akar kuadrat<br><br>log(8)         # logaritma natural<br><br>log10(100)     # logaritma basis 10<br><br>exp(1)         # antilog natural / eksponensial</pre><p>R mengerjakan operasi aritmatika dengan urutan umum (misal: perkalian mendahului penjumlahan).</p><pre>(50 + 7*2) / exp(3.14)<br>## [1] 2.770099</pre><h3>Fungsi</h3><p>Fungsi adalah objek yang dapat menerima sebuah masukan (argumen atau parameter) dan mengeluarkan sebuah luaran (<em>output</em>). Fungsi sangat berguna untuk meringkas kode yang digunakan berulang kali.</p><p>R memiliki banyak fungsi yang tersedia, seperti fungsi <em>c(…)</em>, <em>sqrt(…)</em>, dan <em>mean(…)</em> yang telah ditunjukkan sebelumnya. Fungsi <em>sqrt(…)</em> menerima argumen berupa angka yang ingin diakar-kuadratkan. Fungsi <em>c(…)</em> menerima argumen berupa objek-objek yang ingin di-vektorkan.</p><p>Untuk mengetahui arti / penggunaan sebuah fungsi di R, Anda dapat menambahkan tanda tanya <em>?</em> di depan nama fungsi.</p><pre>?mean  # menampilkan halaman bantuan mengenai fungsi mean</pre><h3>Pustaka (Library)</h3><p>Tidak semua analisis tersedia di R secara <em>default</em>. Sebagai contoh, tidak tersedia fungsi untuk model ARFIMA. Untuk itu, komunitas R bersama-sama menyediakan berbagai macam pustaka yang berisi fungsi-fungsi untuk menjalankan analisis tertentu. Ribuan pustaka tersedia melalui repositori resmi <a href="https://cran.r-project.org/web/packages/available_packages_by_name.html">CRAN</a>.</p><p>Komunitas R menyediakan ringkasan mengenai pustaka berdasarkan jenis analisis. Anda dapat mengunjungi <a href="https://cran.r-project.org/web/views/">CRAN Task Views</a>.</p><h3>Instalasi dan Penggunaan Pustaka</h3><p>Untuk melakukan pemodelan ARFIMA (<em>Autoregressive Fractionally-Integrated Moving Average</em>), Anda dapat memasang pustaka <a href="https://cran.r-project.org/web/packages/forecast/index.html">forecast</a> dengan fungsi install.packages(“forecast”). Instalasi hanya perlu dilakukan satu kali saja (kecuali apabila Anda ingin memperbarui).</p><p>Untuk menggunakan pustaka tersebut dalam sebuah R Script, gunakan fungsi <em>library(forecast)</em>. Anda dapat menggunakan beberapa pustaka sekaligus.</p><pre>install.packages(“forecast”) # cukup jalankan sekali saja<br>library(forecast) <br><br>?arfima  # tampilkan laman bantuan untuk fungsi arfima</pre><h3>Matriks dan Array</h3><p>Matriks adalah sebuah struktur data dua dimensi yang memiliki baris dan kolom, serupa dengan sebuah lembar Excel. Matriks umum digunakan dalam R karena komputasinya jauh lebih mudah dibandingkan dengan skalar.</p><p>Array serupa dengan matriks, tetapi tidak terbatas pada dua dimensi. Baik matriks maupun array harus memiliki elemen dengan tipe data yang sama.</p><p>Akses elemen dalam matriks mirip seperti vektor. Gunakan notasi kurung persegi <em>[baris, kolom]</em>.</p><p><strong>Mendefinisikan Matriks</strong></p><p>Untuk mendefinisikan matriks dan array, gunakan fungsi <em>matrix(…)</em> dan <em>array(…)</em>.</p><pre># Matriks dengan dua baris<br># Jumlah kolom secara otomatis disesuaikan<br>matku &lt;- matrix(c(1,2,3,4,5,6), nrow = 2)<br>matku<br>##      [,1] [,2] [,3]<br>## [1,]    1    3    5<br>## [2,]    2    4    6</pre><p>Perhatikan R mengisi kolom terlebih dahulu. Untuk mengisi baris terlebih dahulu, tambahkan argumen <em>byrow = TRUE</em>.</p><pre># Perhatikan bahwa penulisan di bawah diperbolehkan<br>matku &lt;- matrix(c(1,2,3,<br>                  4,5,6), nrow = 2, byrow = TRUE)<br>matku<br>##      [,1] [,2] [,3]<br>## [1,]    1    2    3<br>## [2,]    4    5    6<br><br>matku[1, ]         # Akses baris ke-2<br>## [1] 1 2 3<br><br>matku[, c(2,3)]    # Akses kolom ke-2 dan ke-3<br>##      [,1] [,2]<br>## [1,]    2    3<br>## [2,]    5    6<br><br>matku[2, 3]        # Akses elemen baris ke-2 kolom ke-3<br>## [1] 6</pre><p><strong>Menamai Matriks</strong></p><p>Kolom dan baris pada matriks di atas secara <em>default</em> diberi angka indeks. Anda dapat memberi nama baris dan kolom matriks untuk memudahkan interpretasi.</p><pre>matku &lt;- matrix(c(1,2,3,<br>                  4,5,6), nrow = 2, byrow = TRUE)<br><br># Beri nama baris dengan operator penugasan<br>rownames(matku) &lt;- c(“Baris A”, “Baris B”)<br><br># Beri nama kolom dengan operator penugasan<br>colnames(matku) &lt;- c(“Kolom A”, “Kolom B”, “Kolom C”)<br>matku<br>##         Kolom A Kolom B Kolom C<br>## Baris A       1       2       3<br>## Baris B       4       5       6</pre><h3>Data Frame</h3><p>Struktur data frame mirip dengan matriks, yakni memiliki baris dan kolom. Akan tetapi, setiap kolom data frame diperbolehkan untuk memiliki tipe data berbeda. Umumnya baris menunjukkan observasi, sedangkan kolom menunjukkan variabel. Data frame adalah struktur data yang umum digunakan dalam analisis.</p><p><strong>Mendefinisikan Data Frame</strong></p><p>Data frame dapat dibentuk dengan menggunakan fungsi <em>data.frame(…)</em> dan mengirimkan beberapa vektor dengan jumlah elemen yang sama. Anda langsung dapat memberi nama kolom data frame pada saat pembuatan.</p><p>Anda juga dapat mengubah matriks menjadi data frame dengan fungsi <em>as.data.frame(…)</em>.</p><pre># Siapkan beberapa vektor untuk data frame<br>max_torque &lt;- c(201, 211, 234)<br>max_speed &lt;- c(181, 234, 210)<br>fuel_per_100 &lt;- c(5.4, 7.8, 6.1)<br>car_type &lt;- c(“Hatchback”, “MPV”, “SUV”)<br><br># Bentuk sebuah data frame<br>car_df &lt;- data.frame( torque = max_torque, <br>    speed = max_speed, <br>    fuel_efficiency = fuel_per_100, <br>    type = car_type)<br>car_df # Tampilkan dataframe<br><br>##   torque speed fuel_efficiency      type<br>## 1    201   181             5.4 Hatchback<br>## 2    211   234             7.8       MPV<br>## 3    234   210             6.1       SUV</pre><p>Terlihat bahwa data frame secara otomatis memberikan nama baris berupa angka berurutan. Untuk mengubah nama baris atau kolom, Anda dapat menggunakan cara serupa dengan matriks.</p><p><strong>Mengakses Elemen Data Frame</strong></p><p>Anda dapat menggunakan cara serupa dengan matriks, baik dengan menggunakan indeks maupun nama baris/kolom. Anda dapat secara langsung mengambil sebuah kolom dengan menggunakan tanda <em>$</em>.</p><pre># Gunakan car_df dari contoh sebelumnya<br>car_df[1, ]   # Ambil baris pertama dengan indeks<br>##   torque speed fuel_efficiency      type<br>## 1    201   181             5.4 Hatchback<br><br>car_df[, c(2,3)]  # Ambil kolom kedua dan ketiga dengan indeks<br>##   speed fuel_efficiency<br>## 1   181             5.4<br>## 2   234             7.8<br>## 3   210             6.1<br><br>car_df[&quot;speed&quot;]  # Ambil kolom speed dengan nama kolom<br>##   speed<br>## 1   181<br>## 2   234<br>## 3   210<br><br># Ambil kolom speed, perhatikan luaran berupa VEKTOR<br>car_df[,&quot;speed&quot;]  <br>car_df$speed<br>## [1] 181 234 210<br><br>car_df[,c(&quot;speed&quot;, &quot;type&quot;)] # Ambil dua kolom dengan nama kolom<br>##   speed      type<br>## 1   181 Hatchback<br>## 2   234       MPV<br>## 3   210       SUV</pre><p>R memiliki banyak dataset yang dapat langsung digunakan dalam analisis. Sebagai contoh, berikut adalah dataset Iris (Fisher, 1936 dan Anderson, 1935).</p><pre># Gunakan data iris<br>dataku &lt;- iris<br>head(dataku) # Tampilkan 6 baris pertama<br>##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species<br>## 1          5.1         3.5          1.4         0.2  setosa<br>## 2          4.9         3.0          1.4         0.2  setosa<br>## 3          4.7         3.2          1.3         0.2  setosa<br>## 4          4.6         3.1          1.5         0.2  setosa<br>## 5          5.0         3.6          1.4         0.2  setosa<br>## 6          5.4         3.9          1.7         0.4  setosa<br><br># Tampilkan data dengan kriteria Sepal.Length &gt;= 5<br># Perhatikan ekspresi kriteria diberikan pada baris, bukan kolom<br>dataku[dataku[&quot;Sepal.Length&quot;] &gt;= 5, ]<br><br># Tampilkan data dengan kriteria diatas dan Species setosa.<br>dataku[dataku[&quot;Sepal.Length&quot;] &gt;= 5<br>  &amp; dataku[&quot;Species&quot;] == &quot;setosa&quot;, ]</pre><h3>Membuka dan Menyimpan Data CSV, Excel, SPSS</h3><p>R mendukung banyak format data, seperti CSV (<em>Comma Separated Values</em>), TSV (<em>Tab Separated Values</em>), XLSX (Excel 2003+), dan sebagainya. Tabel berikut menyajikan ringkasan fungsi untuk membuka dan menyimpan data dengan format populer.</p><p>Anda hanya perlu mengubah teks <em>string</em> yang ada dengan lokasi/direktori file Anda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*mtkhkZvhq6y1ptoJNvQIEA.png" /><figcaption>Buka dan Simpan Data Eksternal</figcaption></figure><p><strong>Contoh File Excel</strong></p><p>Data yang digunakan dapat diakses <a href="https://docs.google.com/spreadsheets/d/1Dz-9ScpeFeoDR2WqG75Zd0A02v1Fa_Su/edit?usp=sharing&amp;ouid=117358761750579055609&amp;rtpof=true&amp;sd=true">di sini</a>.</p><p>Untuk menggunakan dataset dalam file “Dataset.xlsx” dan sheet “TaiwanEstate”, gunakan pustaka readxl dan fungsi <em>read_excel(…)</em>. Untuk kemudahan, ubah format menjadi data frame.</p><pre>library(readxl)<br>estate &lt;- read_excel(path = &quot;C:\\Project\\Dataset.xlsx&quot;,<br>   sheet = &quot;TaiwanEstate&quot;)<br>estate &lt;- as.data.frame(estate) # Ubah ke dataframe<br>head(estate)    # Sajikan 6 baris pertama data</pre><p><strong>Contoh File CSV</strong></p><p>Anda dapat langsung membuka file CSV yang tersedia <em>online</em> tanpa perlu mengunduhnya terlebih dahulu.</p><pre>library(readxl)<br>addresses &lt;- read_excel(<br>path=&quot;https://people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv&quot;)<br><br>addresses &lt;- as.data.frame(addresses) # Ubah ke dataframe<br>head(addresses)     # Sajikan 6 baris pertama </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775a01eaf7a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to Automated Machine Learning in Python using FLAML]]></title>
            <link>https://medium.com/@mouse3mic3/a-practical-guide-to-automated-machine-learning-in-python-using-flaml-c73a714887a4?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/c73a714887a4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Thu, 09 May 2024 03:27:16 GMT</pubDate>
            <atom:updated>2024-05-09T03:27:16.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e7AgU_QX67_Qf-rn" /><figcaption>Photo by <a href="https://unsplash.com/@headwayio?utm_source=medium&amp;utm_medium=referral">Headway</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Machine learning modelling doesn’t have to be complicated! In fact, you don’t need much experience in order to create a perfectly usable model. You don’t even need to run any data preprocessing! Sounds too good to be true, right?</p><p>In this guide, we will be taking a look at an Auto ML framework, <a href="https://microsoft.github.io/FLAML/docs/Getting-Started">FLAML</a>. Developed by Microsoft, it allows user to skip the repetitive task of preprocessing and model tuning. It automatically select the best model for the given data under constraints that are determined by the user. FLAML is one of many AutoML frameworks available and it is widely used for many classification and regression tasks. In its recent version, it also supports AutoGen, an LLM framework by Microsoft.</p><p>We will be taking a look at its usage in classification problems, which are considered “task-oriented”. In this sense, we have a label representing the target that must be predicted based on the given input.</p><p>The code used can be accessed through this <a href="https://colab.research.google.com/drive/1AgYcHqxRDNy96fRQHKkINCyvROG3NQxn?usp=sharing">Google Colab Notebook</a>.</p><h3>Preparations</h3><p>We’ll start by loading a dataset. We’ll be using <a href="https://www.kaggle.com/datasets/mnassrib/telecom-churn-datasets?select=churn-bigml-80.csv">customer churn dataset from Kaggle</a>. We can load the dataset using pandas library.</p><pre>import pandas as pd<br>df = pd.read_csv(&#39;/content/churn-bigml-80.csv&#39;)<br>df.head()</pre><p>Churn is a term used when a customer of a particular company stops being a customer and/or moves to another. This type of analysis is quite common and proves to be challenging due to data imbalancy.</p><pre># Compute the frequency using value_counts() then displaying the result in a horizontal barplot<br>df[&#39;Churn&#39;].value_counts().plot(kind = &#39;barh&#39;, figsize = (4, 1), title = &#39;Churn Frequency&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*6cnjxixz-zKCv8pdwD_3MA.png" /></figure><p>A dataset is considered to be imbalance when the label frequency is not equal. The figure above shows that there are far more non-churning customer, which somewhat reflects the real-life case. Knowing the characteristic of a churning customer is therefore much more important than non-churning, as it may help us prevent potential churner in the future.</p><h3>Train-Test Split</h3><p>For most cases, we can immediately run the automated ML without doing any form of preprocessing. When fitting (i.e creating) a machine learning model, we should be aware of over and underfitting. In short, our model(s) may perform admirably on well-known customer pattern, but fall miserably when implemented on new customer data. We don’t want this.</p><p>A simple way to circumvent this is by reserving some data for later, these are “unseen” by our ML model. We train the model using the majority, but not all, of existing data. We then test its performance on the unseen data. Good model will have roughly equal accuracy (or other metrics) on both “training” and “testing” set.</p><p>For demonstration purposes, we will still split our data into 80% training and 20% testing sets. The test set will act as a “new customer data” than we’ve never seen before. The stratified split ensures that we have equal distribution of churn and non-churn customer in both training and testing sets. That is, if 10% of customer are churning, it should also be 10% in each of the train and test sets.</p><pre># Separate X and y into two objects<br>X = df.drop(&#39;Churn&#39;, axis = 1)<br>y = df[&#39;Churn&#39;]<br><br># Split train test using stratify <br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, stratify = y)</pre><h3>A Baseline Tree</h3><p>We begin by creating a baseline, a simple decision tree classifier. Our FLAML model should then be better than this baseline.</p><p>The result is produced below for both training and testing set (the code is provided in the Colab).</p><pre># Evaluation on Training Set<br>               precision    recall  f1-score   support<br><br>       False       0.85      0.85      0.85      1822<br>        True       0.14      0.14      0.14       310<br><br>    accuracy                           0.75      2132<br>   macro avg       0.50      0.50      0.50      2132<br>                                                  ...<br><br># Evaluation on Testing Set<br>               precision    recall  f1-score   support<br><br>       False       0.85      0.85      0.85       456<br>        True       0.15      0.15      0.15        78<br><br>    accuracy                           0.75       534<br>   macro avg       0.51      0.51      0.51       534<br>                                                  ...</pre><p>The accuracy is 75% for both training and testing sets, there are definitely room for improvement! Even worse, while our model performs well on predicting non-churning customer (the “False” row suggest a very high precision and recall), it can’t say the same with the churning customer.</p><p>A high disparity between the the two classes indicates that the model focuses “too-much” on learning the majority non-churning customers. There are several ways we can deal with data imbalancy. We’ll discuss this in further detail later.</p><p>This also highlights the importance of selecting an apropriate metric. <a href="https://datascience.stackexchange.com/questions/110124/what-are-the-disadvantages-of-accuracy">Accuracy may not be the best when the label is imbalanced</a>, and instead, we should rely on other metric that truly reflects the model performance overall. For example, the F1-score is a harmonic mean between precision and recall. A higher value of F1-score suggests a better model.</p><h3>Simple FLAML AutoML Classifier</h3><p>To construct a simple FLAML AutoML classifier, we only need 3 things.</p><ul><li><strong>Data.</strong> Separated into features (X) and label (y).</li><li><strong>Time budget</strong>. It is the maximum time the model is allowed to be trained. FLAML will not always use up all the available time budget, so you don’t have to worry if you accidentally set this value too high.</li><li><strong>Metric.</strong> As a general guide, in classification we want to maximize accuracy, precision, recall, or F1-score. In regression we want to minimize MSE, MAE, and MAPE. All available metrics are listed <a href="https://microsoft.github.io/FLAML/docs/Use-Cases/Task-Oriented-AutoML/#customize-automlfit">here</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*oeFXCl54sC-B34VU02tSzA.png" /><figcaption>Available metrics</figcaption></figure><pre>from flaml import AutoML<br>model_config = {<br>    &#39;task&#39; : &#39;classification&#39;,  # classification or regression<br>    &#39;time_budget&#39; : 60,    # time budget in seconds<br>    &#39;metric&#39; : &#39;macro_f1&#39;  # main metric to be optimized<br>}<br><br>model = AutoML()<br>model.fit(X_train, y_train, **model_config)</pre><p>In the background, FLAML is <strong>trying several ML model and finding which one performs best on our cross-validated data</strong>. Some of the model may include Light GBM (LGBM), Random Forest (rf), XGBoost (xgb), and lrl1 (Logistic Regression).</p><p>You may also notice that some model may be used more than once. This is because FLAML <strong>also attempts to tune the hyperparameters</strong>, essentially customizing the model to better fit our data. We’ll talk about hyperparameter a bit later.</p><h3>Model Summary</h3><p>Once done, we can display the best model and the best hyperparameters. We see that Light GBM with the given hyperparameters is the best model for our data (for the given time constraints).</p><pre>model.model.estimator<br><br># LGBMClassifier(colsample_bytree=0.5576123916641383,<br>               learning_rate=0.32245352992309906, max_bin=127,<br>               min_child_samples=2, n_estimators=1, n_jobs=-1, num_leaves=20,<br>               reg_alpha=0.0009765625, reg_lambda=0.01156359270003933,<br>               verbose=-1)</pre><p>FLAML by default uses more than Light GBM. To display the best configuration for each model/estimator, use <em>best_config_per_estimator</em>.</p><pre>model.best_config_per_estimator</pre><p>We can also display which iteration resulted in the best model and how long it takes to find it.</p><pre>print(&#39;The &#39;, model.best_iteration,&#39;-th iteration is the best, completed in &#39;, round(model.time_to_find_best_model, 1),&#39; seconds.&#39;, sep = &#39;&#39;)<br># The 57-th iteration is the best, completed in 47.1 seconds.</pre><p>The model object itself can be directly used to predict new data.</p><pre># Predict test data<br>y_test_pred = model.predict(X_test)<br><br># Display metrics<br>print(classification_report(y_test, y_test_pred))<br><br># Output<br>              precision    recall  f1-score   support<br><br>       False       0.96      0.99      0.97       456<br>        True       0.92      0.76      0.83        78<br><br>    accuracy                           0.96       534<br>   macro avg       0.94      0.87      0.90       534<br>weighted avg       0.95      0.96      0.95       534</pre><p>A very simple FLAML classifier is able to <strong>outperform our baseline,</strong> the decision tree, in a minute! The improvement is very noticeable on the True class, where the precision and recall increases substantially!</p><p><strong>This could be much better if we give it more time or if we tinker with the classifier a bit.</strong></p><h3>Cross-Validation</h3><p>Cross-validation is a slightly more sophisticated way to verify the goodness of a model. <strong>Instead of only making one train-test split, we make k-split, splitting the data into k-fold.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/0*ccKmuC0eNbJ7vaHh.png" /><figcaption>5-fold cross-validation (from scikit-learn.org)</figcaption></figure><p>The figure above shows a simple example of 5-fold cross-validation. We’ve further split the training data into into 5 folds. From the folds, we essentially have 5 different kind of train-test split, covering the entire data. In split 1, the training set is fold 2-fold 5, whereas the test set is the fold 1.</p><p>We then train our model on each splits (using identical parameters), measure the performance metrics, then aggregating the result using average or median value. <strong>This method ensures that the “unseen” test-set covers all possible data.</strong></p><p><strong>A big concern is that training time will increase substantially. </strong>In the case of 5-fold CV, we need to train our ML model 5 times instead of 1. Cross-validation is absolutely worth the downside since <strong>it is almost guaranteed to yield better and more reliable model.</strong> Most (if not all) top performing models on Kaggle ML competitions use a form of CV.</p><p><strong>FLAML will automatically use 5-fold stratified CV if possible</strong>, which is great! We can adjust it to our liking. Several kinds of cross-validation is supported in scikit-learn <a href="https://scikit-learn.org/stable/modules/cross_validation.html#cross-validation-iterators">here</a>.</p><p>We can pass the method as <em>split_type</em>. Ensure that <em>eval_method</em> is also set to “cv”. In this example, we use <em>RepeatedStratifiedKFold</em>.</p><pre>model_config = {<br>    ...<br>    &#39;eval_method&#39; : &#39;cv&#39;,<br>    &#39;split_type&#39;  : RepeatedStratifiedKFold(n_splits = 5, n_repeats = 5),<br>}</pre><p>It is also possible to customize the CV simply by adjusting the <em>split_type</em> and <em>n_splits</em>. The following is roughly identical to using non-stratified <em>KFold(5)</em>.</p><pre>model_config = {<br>    ...<br>    &#39;eval_method&#39; : &#39;cv&#39;,<br>    &#39;split_type&#39;  : &#39;uniform&#39;, # can be uniform or stratified<br>    &#39;n_splits&#39;    : 5          # num of splits<br>}</pre><h3>Alternative to Cross Validation</h3><p>If we wish to not use cross-validation (or we already have FLAML within CV), we can instead pass <strong>validation</strong> data, or provide <strong>a ratio of data to be used as validation</strong>. The validation set will not be used during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*vd5yGWuPlXXUx9UIlTJwCQ.png" /><figcaption>Holdout data</figcaption></figure><pre># Provide percentage of training data to be used as validation set.<br>model_config = {<br>    ...<br>    &#39;eval_method&#39; : &#39;holdout&#39;,<br>    &#39;split_ratio&#39; : 0.2<br>}</pre><pre># Provide validation data<br>model_config = {<br>    ...<br>    &#39;eval_method&#39; : &#39;holdout&#39;,<br>    &#39;X_val&#39;       : X_val,<br>    &#39;y_val&#39;       : y_val<br>}</pre><h3>Iteration Budget</h3><p>If we don’t have a time limit, but instead have <strong>iteration limit</strong> (i.e number of fitting), we can pass the <em>max_iter</em> argument (or use both!). This may be useful when we have computer memory constraints.</p><pre>model_config = {<br>    ...<br>    &#39;time_budget&#39; : 60,  # in seconds<br>    &#39;max_iter&#39;    : 60,  # num of model fitting allowed<br>}</pre><h3>Custom Metrics</h3><p>Let’s say that we want to use sensitivity as our main metric. This is not available by default, so we would need to <strong>create a custom function to compute the metric</strong>.</p><p>The function <strong>must accepts all the default arguments</strong> and <strong>return the metric to be minimized</strong>. Since we want to maximize sensitivity instead, we need to flip its sign (as suggested by the <em>-1 * final_metric</em>)!</p><pre>from sklearn.metrics import confusion_matrix<br><br># Define a function that accepts all of these arguments<br>def sensitivity_metric(X_val, y_val, estimator, labels, <br>                       X_train, y_train, weight_val = None, <br>                       weight_train = None, *args):<br><br>  # tp: true positive, fp: false positive<br>  # tn: true negative, fn: false negative<br>  # in our case, the Churn is assigned as &quot;positive&quot; class.<br>  <br>  # Predict the train data and compute sensitivity<br>  y_train_predicted = estimator.predict(X_train)<br>  tp, fp, fn, tn = confusion_matrix(y_train, y_train_predicted).ravel()<br>  train_sensitivity = tp/(tp+fn)<br><br>  # Predict the validation data and compute sensitivity<br>  y_val_predicted = estimator.predict(X_val)<br>  tp, fp, fn, tn = confusion_matrix(y_val, y_val_predicted).ravel()<br>  val_sensitivity = tp/(tp+fn)<br><br>  # Compute the average sensitivity between training and val<br>  final_metric = (train_sensitivity + val_sensitivity)/2<br><br>  # Return the metric and a dictionary containing some logging information<br>  # Since FLAML only minimizes the metric, we flip the sign of our metric<br>  return -1 * final_metric, {<br>      &#39;train_sensitivity&#39; : train_sensitivity,<br>      &#39;val_sensitivity&#39; : val_sensitivity<br>  }</pre><pre># Adjust the metric argument<br>model_config = {<br>    ...<br>    &#39;metric&#39;      : sensitivity_metric,<br>    ...<br>}</pre><h3>Selecting Estimator / Model</h3><p>We can <strong>select certain estimator/model to be tried.</strong> Many popular algorithms are natively supported on FLAML, listed <a href="https://microsoft.github.io/FLAML/docs/Use-Cases/Task-Oriented-AutoML/#estimator-and-search-space">here</a>. Limiting FLAML to only certain estimators may be beneficial, such that <strong>we only focus on models that we know will perform best.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*HBAfTGNBWgBC9zeLaCjvWA.png" /><figcaption>Available estimators in FLAML (for non-time series data)</figcaption></figure><p>LightGBM (lgbm), XGBoost (xgboost), Catboost (catboost), and Hist Gradient Boost (histgb) are some of the best for classification or regression.</p><pre>model_config = {<br>    ...<br>    &#39;estimator_list&#39; : [&#39;lgbm&#39;, &#39;histgb&#39;]<br>}</pre><h3>Custom Estimator / Model</h3><p>Our favorite estimator, say Support Vector Machine (<a href="https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html">SVM</a>), is not available in FLAML. Just like the custom metrics, we can define a <strong>custom estimator</strong>. The estimator <strong>is not limited to what’s available in scikit-learn</strong>, but it may get a bit more complicated. More details can be found <a href="https://microsoft.github.io/FLAML/docs/Use-Cases/Task-Oriented-AutoML/#guidelines-on-tuning-a-custom-estimator">here</a>.</p><p>We can specify <strong>which estimator to be used for classification and/or regression.</strong> In our case, SVC is for classification, while SVR is for regression.</p><p>Additionally, <strong>we must also include a search_space function.</strong> This is the possible values for any of the hyperparameter of SVM, for example, the kernel type could be linear or polynomial. More explanation is described in the code.</p><pre>from sklearn.svm import SVC, SVR<br>from flaml.automl.model import SKLearnEstimator<br>from flaml import tune<br>from flaml.automl.task.task import CLASSIFICATION<br><br># Derrive from the base class SKLearnEstimator<br># SKLearnEstimator only works for scikit-learn compatible object (i.e those that has .fit and .predict methods)<br># For more general estimator, derive from BaseEstimator instead<br>class SVM(SKLearnEstimator):<br><br>  # The task argument here is necessary as an initialization<br>  # By default FLAML sets n_jobs parameter. This is used in SVM<br>  # ... thus we explicitly set it to None<br>  def __init__(self, n_jobs = None, task = &#39;classification&#39;, **config):<br>    super().__init__(task, **config)<br><br>    # We only need to modify the estimator_class according to the task<br>    # SVC is for classification, SVR is for regression<br>    if task in CLASSIFICATION:<br>      self.estimator_class = SVC<br>    else:<br>      self.estimator_class = SVR<br><br>  # Any estimator must also include hyperparameter space<br>  # These are the model (i.e SVM) parameters that will be tuned by FLAML<br>  @classmethod<br>  def search_space(cls, data_size, task):<br>    # We will optimize C, kernel type, and maximum solver iteration<br><br>    # uniform and loguniform is used for float<br>    # randint and lograndint is used for integers<br>    # choice is used for categories<br>  <br>    space = {<br>        # C values between 0.5 and 4 (float)<br>        &quot;C&quot;:{<br>            &quot;domain&quot;: tune.uniform(lower = 0.5, upper = 4.0),<br>        },<br>        # Kernel could be linear, radial basis, or polynomial<br>        # Additionally, we can specify the &quot;fastest&quot; (low time-cost) configuration<br>        &quot;kernel&quot;:{<br>            &quot;domain&quot;: tune.choice([&#39;linear&#39;, &#39;rbf&#39;, &#39;poly&#39;]),<br>            &quot;low_cost_init_value&quot;: &#39;linear&#39;<br>        },<br>        # Max solver iteration (integer), it is usually necessary to put hard limit on SVM<br>        &quot;max_iter&quot;:{<br>            &quot;domain&quot;: tune.randint(lower = 100, upper = 1000),<br>            &quot;low_cost_init_value&quot;: 100<br>        }<br>    }<br><br>    return space</pre><p>And we call the <em>add_learner </em>method before fitting. We’ll give it a name ‘<em>svm</em>’.</p><pre>...<br>model = AutoML()<br><br># Add svm to the list of estimator<br>model.add_learner(&#39;svm&#39;, SVM)<br>model_config = {<br>  ...<br>  &#39;estimator_list&#39; : [&#39;lgbm&#39;, &#39;histgb&#39;, &#39;svm&#39;]<br>  ...<br>}<br><br>model.fit(X_train, y_train, **model_config)</pre><h3>Hyperparameter Tuning Existing Estimator</h3><p>All built-in estimators (such as Light GBM, XGBoost, Histogram GB) have assigned hyperparameter space to search. For some specific cases, we might wish to modify some of the space to our liking. This is possible through the <em>custom_hp</em> argument.</p><p>The following is an example to customize some hyperparameter space of Light GBM and Histogram Gradient Boost, then passing it into fitting.</p><pre>custom_params = {<br><br>    # LightGBM<br>    &quot;lgbm&quot;:{<br>        # Limit Max Depth to 1 - 10<br>        &quot;max_depth&quot;:{<br>            &quot;domain&quot;: tune.randint(lower = 1, upper = 10)<br>        },<br>        # More boosting<br>        &quot;n_estimators&quot;:{<br>            &quot;domain&quot;: tune.lograndint(lower = 20, upper = 500),<br>            &quot;low_cost_init_value&quot;: 20<br>        }<br>    },<br>    <br>    # Histogram GB<br>    &quot;histgb&quot;:{<br>        # Put limit to minimum samples per leaf node<br>        &quot;min_samples_leaf&quot;:{<br>            &quot;domain&quot;: tune.randint(lower = 5, upper = 75),<br>        },<br>        # Disable learning_rate optimization<br>        &quot;learning_rate&quot;:{<br>            &quot;domain&quot;: None<br>        }<br>    }<br>}</pre><pre># pass the custom param space<br>model_config = {<br>    ...<br>    &#39;custom_hp&#39;   : custom_params,<br>}<br><br>model.fit(X_train, y_train, **model_config)</pre><p>Note that other untouched hyperparameter, such as <em>l2_regularization</em>, will still be searched using FLAML default space.</p><h3>Ensembling the Best Estimators</h3><p>In practice, a model can never be perfect. Having two models can be useful, where one model is struggling to predict a certain user segment, whereas other model excels.</p><p>You may have heard an ensemble. A Random Forest estimator is an ensemble since it is a collection of hundreds or thousands of individual decision tree. Each tree is trained and asked to make prediction. The final prediction is determined through voting. Class with more votes will be chosen as the final prediction.</p><p>In practice, <strong>we can combine the two (or more) best performing estimators into one, effectively making an ensemble of classifiers. </strong>This can be done by setting the argument <em>ensemble</em> to <em>True</em>.</p><pre>model_config = {<br>    ...<br>    &#39;ensemble&#39;    : True<br>}</pre><p><strong>It is important to note that ensemble will require each model/estimators to have predict_proba(…) method. </strong>Most scikit-learn estimators have these, but some (e.g SVM) does not have it by default. For our case (SVM), we need to add <em>probability = True</em> to the search space.</p><pre># modify the SVM class<br>class SVM(SKLearnEstimator):<br>  ...<br>  <br>  def search_space(cls, data_size, task):<br>    ...<br>    space = {<br>        ...<br>        # Probability<br>        &quot;probability&quot;:{<br>            &quot;domain&quot;: tune.choice([True]),<br>        }<br>    }</pre><h3>Verbose Control</h3><p>If you don’t need FLAML to display the progress in each iteration, you can adjust the verbose argument between 0–3.</p><ul><li>Value of 0 and 1 will suppress all messages (except warnings from estimators)</li><li>Value of 2 will only display warning</li><li>Value of 3 (default) will display every iteration</li></ul><pre>model_config = {<br>    ...<br>    &#39;verbose&#39;     : 1<br>}</pre><h3>Logging</h3><p>Logging (i.e storing the iteration history) can be useful for diagnostic purposes. We can also see which parameter space is searched and for how long. This is done by specifying a <em>log_file_name</em>.</p><p>By default, only iteration with improvements are stored. To store (literally) every iteration, you can set <em>log_type</em> to <em>better</em> or <em>all</em>.</p><pre>model_config = {<br>    ...<br>    &#39;log_file_name&#39;: &#39;training_log&#39;,<br>    &#39;log_type&#39;    : &#39;all&#39;<br>}</pre><p>We can re-fit the best model using <em>retrain_from_log(…)</em>. This is useful such that we do not need to run the fitting again.</p><pre>model_old = AutoML()<br>model_old.retrain_from_log(X_train = X_train, y_train = y_train, log_file_name = &#39;training_log&#39;)</pre><h3>Save and Continue</h3><p>We can save and load AutoML model by using pickle.</p><pre>import pickle<br><br># Save Model<br>with open(&quot;my_model.pkl&quot;, &quot;wb&quot;) as f:<br>    pickle.dump(model, f, pickle.HIGHEST_PROTOCOL)<br><br># Open Model<br>with open(&quot;my_model.pkl&quot;, &quot;rb&quot;) as f:<br>    model = pickle.load(f)</pre><p>If we have a completed AutoML run and we wish to continue training (without resetting), send the last model’s <em>best_config_per_estimator</em> as <em>starting_points</em>.</p><pre># Initial run<br>model = AutoML()<br>model.fit(X_train, y_train, time_budget = 30)<br><br># Continue training<br>model_continue = AutoML()<br>model_continue.fit(X_train, y_train, time_budget = 30, starting_points = model.best_config_per_estimator)</pre><p><strong>Note: it seems that there are some issues with </strong><em>custom_hp</em><strong> arguments. If you set a </strong><em>custom_hp</em><strong> for the 1st run, then warm-start the 2nd run, it may not work due to KeyError.</strong></p><pre># THE FOLLOWING CODE WILL YIELD A KEYERROR!<br>model = AutoML()<br>model_config = {<br>    &#39;task&#39;        : &#39;classification&#39;,<br>    &#39;time_budget&#39; : 10, <br>    &#39;estimator_list&#39; : [&#39;lgbm&#39;, &#39;histgb&#39;],<br>    &#39;custom_hp&#39;   : custom_params, # Disabling custom_hp will resolve the error<br>}<br>model.fit(X_train, y_train, **model_config)<br><br># Continue training<br>model_continue_config = {<br>    &#39;task&#39;        : &#39;classification&#39;,<br>    &#39;time_budget&#39; : 10, <br>    &#39;estimator_list&#39; : [&#39;lgbm&#39;, &#39;histgb&#39;], <br>    &#39;custom_hp&#39;   : custom_params,<br>    &#39;starting_points&#39; : model.best_config_per_estimator<br>}<br><br>model_continue = AutoML()<br>model_continue.fit(X_train, y_train, **model_continue_config)</pre><h3>Putting It All Together</h3><p>Here’s a snippet of the final code. Again, for the full code, you can access it from <a href="https://colab.research.google.com/drive/1AgYcHqxRDNy96fRQHKkINCyvROG3NQxn?usp=sharing">here</a>.</p><pre>model_config = {<br>    &#39;task&#39;        : &#39;classification&#39;,<br>    &#39;time_budget&#39; : 300,     # in seconds<br>    &#39;max_iter&#39;    : 1000,    # num of model fitting allowed<br>    &#39;metric&#39;      : sensitivity_metric,   # custom metric function<br>    &#39;estimator_list&#39; : [&#39;lgbm&#39;, &#39;histgb&#39;, &#39;svm&#39;],  # list of estimators used<br>    &#39;eval_method&#39; : &#39;cv&#39;,   # use RepeatedKFold<br>    &#39;split_type&#39;  : RepeatedKFold(n_splits = 3, n_repeats = 10),<br>    &#39;custom_hp&#39;   : custom_params,<br>    &#39;ensemble&#39;    : True,<br>    &#39;verbose&#39;     : 3,<br>    &#39;log_file_name&#39;: &#39;training_log&#39;,<br>    &#39;log_type&#39;    : &#39;all&#39;<br>}<br><br>model = AutoML()<br>model.add_learner(&#39;svm&#39;, SVM)<br>model.fit(X_train, y_train, **model_config)<br><br># Save Model<br>import pickle<br>with open(&quot;my_model.pkl&quot;, &quot;wb&quot;) as f:<br>    pickle.dump(model, f, pickle.HIGHEST_PROTOCOL)</pre><p>When enabling Ensemble, to display the final estimator, we do not need to access the estimator attribute. We should see a StackingClassifier instead, where two of the best estimators, lgbm and histgb, are shown.</p><pre>print(model.model)<br>print(&#39;The &#39;, model.best_iteration,&#39;-th iteration is the best, completed in &#39;, round(model.time_to_find_best_model, 1),&#39; seconds.&#39;, sep = &#39;&#39;)<br><br># StackingClassifier(estimators=[(&#39;lgbm&#39;, ...), (&#39;histgb&#39;, ...)])<br># The 17-th iteration is the best, completed in 38.9 seconds.</pre><pre>y_test_pred = model.predict(X_test)<br>print(classification_report(y_test, y_test_pred))<br><br>              precision    recall  f1-score   support<br><br>       False       0.96      0.99      0.98       456<br>        True       0.92      0.77      0.84        78<br><br>    accuracy                           0.96       534<br>   macro avg       0.94      0.88      0.91       534<br>weighted avg       0.96      0.96      0.96       534</pre><p>The model has only improved slightly… but not unexpected. This is most likely caused by our flawed custom metric (only taking into account the sensitivity, not specificity), or perhaps due to SVM taking much longer to fit and not having sufficient time budget. Try changing it back to <em>macro_f1</em> and see if the result improves!</p><p>That’s it everyone! Thank you for reading this far and I hope you are having a great learning day. If you’re interested in other Auto ML frameworks, check out <a href="https://auto.gluon.ai/">Autogluon</a> and <a href="https://autokeras.com/">Autokeras</a>.</p><h3>Extras: Handling Imbalancy</h3><p>There are several ways we can deal with data imbalancy. We’ll discuss this in further detail next time.</p><ul><li><strong>Use resampling technique (over or undersampling)</strong>. Oversampling means we make “duplicates” of the less-frequent class. Undersampling means we reduce the data of the more-frequent class.</li><li><strong>Assign class weight</strong>. Many state-of-the-art ML algorithms accept class-weight. Essentially we force the model to put more attention to less-frequent (i.e more difficult) cases.</li><li><strong>Adjust Regularization</strong>. L1 or L2 regularization also helps reduce overfitting by purposely giving penalty to the model. These are often called “gamma” or “lambda”, with higher values corresponding to higher penalty.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c73a714887a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tuning Hyperparameter of Machine Learning Model using Meta-Heuristic Algorithm]]></title>
            <link>https://medium.com/@mouse3mic3/tuning-hyperparameter-of-machine-learning-model-using-meta-heuristic-algorithm-92c597ca256e?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/92c597ca256e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[decision-tree]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 04:54:52 GMT</pubDate>
            <atom:updated>2024-03-16T04:54:52.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xUhzDFk4JeFhdvRS" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The concept of hyperparameter tuning is well-known. Hyperparameters are parameters of the model that are not estimated from within. Usually, these parameters have a noticeable impact on our model performance and can be tuned according to how our data is structured.</p><p>This article will discuss how we can implement existing population-based meta-heuristic algorithms to yield a better ML model.</p><h3>An Intuition of the Problem</h3><p>Many tuners have been implemented, ranging from an exhaustive search of the space (i.e., searching all the possible values), random search (i.e., selecting several random values), or a better-informed method such as Bayesian optimization. These are often well-implemented and documented and can achieve an objectively better-performing model within a reasonable time.</p><p>One important note is that it is almost impossible to find the absolute best hyperparameter combination. A deeper decision tree doesn’t always yield better accuracy. Even if it does (up to a certain extent), changing other parameters such as the split criterion may also alter existing hyperparameter behavior. This is why we often do not go for the best solution, but rather we go for a reasonably good solution. In math terms, a local optima, which is easier to accomplish.</p><p>Let’s imagine we have a simple tree classifier (i.e., a Decision Tree model that predicts binary output) with a depth of 2. We trained it on our data with cross-validation, and we get 80% accuracy. Changing the depth to 3 helps our accuracy to reach 84%. However, when we try a depth of 4, the accuracy now goes down slightly to 83%. If we think naively, we may say that a depth of 3 is optimal and we should not check any larger values.</p><p>What if a depth of 5 suddenly gives an incredible accuracy of 87%? We would never know since it is against our assumptions. This illustrates the problem. It is very easy for us to be stuck on a local optima, just like in real life when we think that everything won’t work out the way we wanted. So how do we solve this?</p><p>Many hyperparameter optimization techniques take care of this by simply checking some larger depth values. Not all of them, just enough to reach a certain confidence level that says “Yes, I don’t think any larger values will lead to a better result.” Models such as Bayesian optimization accomplish this by using prior information to better “drive” the direction that we need to check. This also cuts our training time considerably, allowing us to focus more on important things in life (or not).</p><h3>Why Population-Based Meta-Heuristic Algorithm?</h3><p>Meta-algorithms solve this by applying natural patterns or phenomena that arise from biological processes or physics. MH aims to retain diversity in the searching process. Often, it starts by searching a very wide hyperparameter space, then each generation (epoch) focuses more on a smaller space. The official <a href="https://mealpy.readthedocs.io/en/latest/pages/general/introduction.html">Mealpy docs</a> should provide more detail on this topic.</p><p>It should be noted that many meta-algorithms are heavily criticized for not being novel compared to existing algorithms. The firefly algorithm, for example, is a slightly modified particle swarm, which some consider not novel enough to be considered its own algorithm. Of course, we’re not here to judge the novelty. Another thing to note is that many MH algorithms do not guarantee convergence, and often we’re quite a bit away from proving their convergence.</p><p>Anyways, let’s begin!</p><h3>The Action!</h3><p>In Python, the <a href="https://mealpy.readthedocs.io/en/latest/">mealpy package</a> provides a wonderful assortments of meta-heuristic algorithm. It has an easy-to-use implementation, ranging from the popular particle-swarm to the latest sparrow-search. It supports multi-objective optimization (e.g maximizing accuracy and minimizing model fitting time, both at the same time), discrete and/or constrained system, and even an early-stopping system.</p><p>This tutorial uses <em>Python 3.11.</em></p><p>The data we’ll be using is <a href="https://epistasislab.github.io/pmlb/profile/coil2000.html">coil2000</a> dataset, which is provided by Penn Machine Learning Benchmark (Olson, R.S., et al., 2017). Many of the features are correlated and have many zeroes. Pre-processing is of course important (as suggested by the very low F1-score we’ll see later), however we will focus instead on the hyperparameter optimization.</p><p>Let’s load several libraries we’ll be using.</p><pre>import pandas as pd<br>from sklearn.model_selection import *<br>from sklearn.preprocessing import *<br>from sklearn.ensemble import *<br>from pmlb import fetch_data<br>import numpy as np <br>from mealpy import *<br>import seaborn as sns # optional</pre><p>Load the data using the <em>fetch_data</em> function provided in the <em>pmlb</em> library. Ensure that you have an active internet connection.</p><pre>X, y = fetch_data(&#39;coil2000&#39;, return_X_y = True)<br>X.shape<br><br># Output: (9822, 85)</pre><p>coil2000 consists of 9822 observation and 85 features. The label is heavily imbalanced, as shown below.</p><pre>pd.DataFrame({&#39;y&#39; : y}).value_counts().plot(kind = &#39;bar&#39;, title = &#39;Label Distribution&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*XQ9f2WcNCJOidD3oZb24Bw.png" /><figcaption>Imbalanced label of coil2000 dataset</figcaption></figure><p>To use <em>mealpy</em>’s algorithms, it is recommended for us to create a class that inherits from <em>Problem</em> class. To put it simply, we copy-paste the example from the <a href="https://github.com/thieu1995/mealpy">official github page</a> and modify the <em>obj_func</em> to our liking. It may seems scary, but all we really care about is what’s inside the <em>obj_func</em>.</p><p>The <em>obj_func</em> is the function that we’d like to optimize. In our case, let’s say that we want to get the best F1-score. The <em>obj_func</em> will receive one argument which stores the hyperparameter combination that we should use. We pass these into our ML model, which is histogram-based boosted tree.</p><p>The hyperparameters we will try to optimize include <em>learning_rate, max_iter, max_leaf_nodes, max_features, min_samples_leaf, </em>and <em>l2_regularization</em>.</p><p>Inside this <em>obj_func</em>, we also compute the F1-score by taking the average of the cross-validation score. The CV we use here is a stratified K-fold. We then return this F1-score. Additionally, we can also store the best metric and F1-score in a separate variable.</p><pre># Define optimize class which stores our problem methods<br>class optimize(Problem):<br>    def __init__(self, bounds=None, minmax=&quot;max&quot;, name=None, **kwargs):<br>        self.name = name<br>        super().__init__(bounds, minmax, **kwargs)<br><br>    # Function to be optimized<br>    def obj_func(self, pars):<br>        pars = self.decode_solution(pars)<br>        global best_model, best_metric, X_train, y_train<br><br>        # Define the tree classifier, change its default hyperparameter accordingly<br>        tree_model = HistGradientBoostingClassifier(<br>            # Optimize these parameters<br>            learning_rate = pars[&#39;lr&#39;],<br>            max_iter = pars[&#39;max_iter&#39;],<br>            max_leaf_nodes = pars[&#39;max_leaf_nodes&#39;],<br>            max_features = pars[&#39;max_features&#39;],<br>            min_samples_leaf = pars[&#39;min_samples_leaf&#39;],<br>            l2_regularization = pars[&#39;l2&#39;],<br>            <br>            # Not optimized<br>            early_stopping = True,<br>            random_state = 135,<br>        )<br><br>        # A stratified cross-validation instance<br>        cv = StratifiedKFold(3)<br><br>        # Compute the average f1-score across all cv-splits<br>        metric = np.mean(cross_val_score(tree_model, X_train, y_train, cv = cv, scoring = &#39;f1&#39;))<br><br>        # Save best model to avoid refitting, change the rule accordingly<br>        if ((best_metric is None) or (best_metric &gt; metric)):<br>            best_metric = metric<br>            best_model = tree_model<br><br>        # obj_func must return the metric<br>        return metric<br><br>best_model = None<br>best_metric = None</pre><p>Next, we need to define the search space (i.e possible values) of each individual hyperparameter. To do that, we will create a new list named <em>bounds</em>. For example, <em>learning_rate</em> must be set to float, so we use <em>FloatVar</em> function and set the lower bound (lb) to be 0.0001 and upper bound (ub) to 1.0. This means we will only try any <em>learning_rate</em> between 0.0001 and 1.0.</p><pre># Define hyperparameter space<br>bounds = [<br>      # Anything between lb and ub, either float (decimal) or integer<br>      FloatVar(lb = 0.0001, ub = 1.0, name = &#39;lr&#39;),<br>      IntegerVar(lb = 25, ub = 1000, name = &#39;max_iter&#39;),<br>      IntegerVar(lb = 4, ub = 64, name = &#39;max_leaf_nodes&#39;),<br>      FloatVar(lb = 0.5, ub = 1.0, name = &#39;max_features&#39;),<br>      IntegerVar(lb = 2, ub = 60, name = &#39;min_samples_leaf&#39;),<br><br>      # Only try given values<br>      MixedSetVar(valid_sets = (0.0, 0.0001, 0.001, 0.01), name = &#39;l2&#39;)<br>  ]</pre><p>The hyperparameter space above uses a config from <a href="https://www.kaggle.com/code/rayhanlahdji/tps-1121-simple-easy-tuning-histgbm-using-skopt">here</a>. Next, we simply run the algorithm. We specify the bounds, minmax (whether we want to minimize or maximize our obj_func), and give it a name. Then, we specify our meta-algorithm (the full list can be found <a href="https://mealpy.readthedocs.io/en/latest/pages/models/mealpy.html">here</a>), and in this case, we will try Cuckoo Search Algorithm (CSA).</p><p>CSA has several additional parameter that we can specify which may help us achieve a faster convergence.</p><pre># Create an instance of my_optimize. Specicy bound, minmax (i.e should be minimize/maximize the obj_function), also name the instance<br>problem = optimize(bounds = bounds, minmax = &quot;max&quot;, name = &#39;CSA&#39;)<br><br>meta_model = CSA.OriginalCSA(epoch = 5, pop_size = 100, p_a = 0.3)<br>meta_model.solve(problem)<br><br># to display best hyperparameter<br>best_model<br><br># to display best F1-score<br>best_metric</pre><p>The process may take considerable amount of time. Increasing<em> epoch</em> and <em>pop_size</em> usually lead to better result, but it also increases the fitting time. We can compare this directly to the result we would get from random search. We’ll use the same search space, cross-validation, and scoring.</p><pre>from scipy.stats import uniform<br><br># same search space<br>param_dist = {<br>    &#39;learning_rate&#39;: uniform(loc=0.0001, scale=1.0 - 0.0001), <br>    &#39;max_iter&#39;: range(25, 1001),  <br>    &#39;max_leaf_nodes&#39;: range(4, 65),<br>    &#39;max_features&#39;: uniform(loc=0.5, scale=1.0 - 0.5),  <br>    &#39;min_samples_leaf&#39;: range(2, 61),  <br>    &#39;l2_regularization&#39; : [0.0, 0.0001, 0.001, 0.01],<br>}<br><br># initialize random search with stratifiedKfold<br>random_search = RandomizedSearchCV(HistGradientBoostingClassifier(early_stopping = True, random_state = 135),<br>                                  param_distributions = param_dist,<br>                                  n_iter = 1000, scoring = &#39;f1&#39;, cv = StratifiedKFold(3), verbose = 1)<br>random_search.fit(X_train, y_train)<br><br># to display best hyperparameters<br>random_search.best_params_<br><br># to display best f1-score<br>random_search.best_score_</pre><h3>The Results</h3><p>The table below shows the comparison between Cuckoo-Search and Random-Search, including the training F1-score we found above and the F1-score on the test data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*JP9wCeJF1uxhFeXn7EwHBw.png" /></figure><p>We see that both approaches have converge into very similar hyperparameter combination, with the exception of <em>max_iter</em> and <em>min_samples_leaf</em>. The differences, although small, have a noticeable impact on our F1-score. The Cuckoo Search consistently yield better score in both training and test, avoiding overfitting (perhaps underfitting slightly), whereas random search seems to overfit.</p><p>Of course these results are just one example. It does not necessarily mean that meta-heuristic-based algorithms are the best, but given sufficient resources, it should be better than random-guessing. It will also be interesting to compare it to other approach, such as one provided by <a href="https://optuna.org/">Optuna</a> or <a href="https://scikit-optimize.github.io/stable/">skopt</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92c597ca256e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estimating ARIMA and SARIMA Coefficients using Genetic Algorithm]]></title>
            <link>https://medium.com/@mouse3mic3/estimating-arima-and-sarima-coefficients-using-genetic-algorithm-03f24ab66589?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/03f24ab66589</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 11:53:58 GMT</pubDate>
            <atom:updated>2024-02-26T11:53:58.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I7JqoJeF2fi7LLjq" /><figcaption>Photo by <a href="https://unsplash.com/@photoholgic?utm_source=medium&amp;utm_medium=referral">Photoholgic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Genetic algorithm has been implemented in many programming languages, including R, mainly used to optimize a given function. ARIMA(p, d, q) parameters (…) are often estimated using likelihood-based method and/or through state-space simulation. Likelihood estimates often have many advantages, such as interpretability and consistency, and moreover, it has been discussed in detail by many researchers. Post-analyses on residual behavior and parameter precision are also often employed since they can be derived mathematically. Not to mention that likelihood-based computation are vastly more efficient.</p><p>An important note to remember is that genetic algorithm won’t solve the local optima problem that the previously mentioned methods have. While it is possible that the parameters estimated from GA are better (in terms of AIC / MSE), they are usually not much different than that of the likelihood estimates. Here we will be using GA as a fun tool to estimate the ARIMA parameters. It is impractical and inefficient, but a useful and fun learning process.</p><h3>The Genetic Algorithm — Intuition</h3><p>GA itself is a class of algorithms made to solve optimization problems. “Optimizing” is often associated with maximizing (or minimizing) a given function. For example, we often wish to minimize AIC (Akaike Info Criterion) or RMSE (Root Mean Sq Error). These two can be considered functions.</p><p>Mathematically and generally speaking, we describe optimizing a function as finding the set of Θ* which gives the highest possible value of its function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*8FTxFnCwX2y6d07CwjGttw.png" /><figcaption><a href="https://doi.org/10.18637/jss.v053.i04">Scrucca, L. 2013</a></figcaption></figure><p>Often we also put bounds on the possible values of Θ. This is to ensure that the result makes sense. For example, if Θ represents all possible number of sales each day, we obviously don’t want negative values. Thus, we limit the “search” to the positive numbers.</p><p>GA is inspired by real-life genetic evolution.</p><p><strong>The Start</strong></p><p>At a certain time, a population is made of individuals (chromosomes). Each individual is made of genes and carry with them certain traits that can be passed onto future generations. Every individual is therefore a potential ‘solution’.</p><p><strong>Mixing</strong></p><p>In reality, there could be infinitely many combination of genes. So, we will have to be smart and eliminate those that are ‘bad’. Our task is to generate the highest quality individual with the best genotype. This is possible due to mixing, also known as ‘reproduction’. Upon mixing, the new generation will inherit genes from both parents, but it doesn’t have to be 50:50.</p><p>In each generation, we put every individual to a fitness test. An individual with the best fit is then selected as the ‘parent’ and then reproduces. Naturally, the best genes are more likely to be passed throughout generation since they will lead to a better ‘parent’. This also means that as time goes on, all the best genes will meet and form the best possible individual.</p><p><strong>Mutation</strong></p><p>We also adopt the concept of mutation. Given enough time and generations, some genes has a chance to mutate (i.e change its value naturally). This is important since mutation may introduce certain genes that were not present in both parents. It also keeps the population ‘diverse’ so that we are not limited to small number of individuals.</p><p><strong>End</strong></p><p>The algorithm ends when the offspring is not considered better than their parents, or when the maximum generation count is reached.</p><p>GA is often faster than random-search, and definitely faster than brute-force approach. Keep in mind that the solution is not guaranteed to be ‘best’, but in proper settings, it should be close.</p><h3>Implementation of Genetic Algorithm</h3><p>While GA may seem very complex, it is actually quite simple yet powerful general-purpose optimization method. GA has been implemented as a <a href="https://luca-scr.github.io/GA/">package in R</a> (<a href="https://doi.org/10.18637/jss.v053.i04">Scrucca, L. 2013</a>).</p><pre>require(GA)</pre><h3>Optimizing ARIMA with GA</h3><p>In R library ‘forecast’, there is a very popular function auto.arima, which automatically find the best (p,d,q) order in terms of AIC. We have discussed it in previous article <a href="https://medium.com/@mouse3mic3/a-practical-guide-to-arima-with-auto-arima-function-in-r-252aa84232af">here</a>. Simply put, it attempts to fit all possible combination of ARIMA orders (or stepwisely), then it compares the AIC and print out the best performing model. The parameter estimation process is still likelihood-based.</p><p>Let’s test it on a simulated ARIMA(2,0,1) data! This data also incorporates a 0.6 shift in mean.</p><pre># Generate ARIMA <br>set.seed(2323)<br>data = arima.sim(model = list(ar = c(0.6, 0.3), ma = c(0.5)), n = 50000) + 0.6<br>plot(data, type = &#39;l&#39;, main = &#39;ARIMA(2,0,1)&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UBUTNCLCn4iQRZO887YbQ.png" /></figure><p>We will show a simple implementation of GA to estimate ARIMA (2, 0, 1) coefficients. Usually, ARIMA is estimated using <em>arima(…)</em>. This function computes the log-likelihood and AIC, and it also accepts a fixed parameter and order. We can use the existing <em>arima(…)</em> as our objective function.</p><pre># Define objective function<br># The argument p is a numerical vector ...<br># ... with length equal to the number of ARIMA coefficients<br>param_optim_function = function(p){<br><br>  # We run ARIMA with specified order and coefficients<br>  # ARIMA(2,0,1) has four coefficients (including mean/constant)<br>  mod = arima(data, order = c(2, 0, 1), fixed = p)<br><br>  # Compute the AIC<br>  result = AIC(mod)<br><br>  # A safeguard. Sometimes the estimation fails due to weird coefficients.<br>  # In case of failure, we set the AIC as Infinite. <br>  # Thus, GA will consider this a &#39;very bad individual&#39;.<br>  if(length(result) &lt; 1){ result = Inf}<br>  return(result)<br>}</pre><p>Now, we use this objective function in GA. The explanation is provided within the code.</p><pre>GA_param &lt;- ga(<br>  # The ARIMA coefficients are bounded real-valued<br>  type = &quot;real-valued&quot;, <br><br>  # The fitness/objective function<br>  # The ga function automatically does maximization.<br>  # Thus to minimize AIC (reverse), we put the negative - sign.<br>  fitness = function(x) -param_optim_function(x),<br><br>  # The lower and upper bound of the parameters<br>  # Again, ARIMA(2,0,1) has 4 coefficients including constant<br>  lower = rep(0, 4), <br>  upper = rep(1, 4),<br>  <br>  # The population size (i.e num of individual) in each generation<br>  # More is usually better, but leads to longer computation<br>  popSize = 50, <br><br>  # The maximum iteration (generations)<br>  maxiter = 100,<br><br>  # The maximum consecutive generations without improvement<br>  run = 10,<br><br>  # Debug/Verbosing<br>  monitor = FALSE,<br><br>  # Enable parallel computing, leads to faster computation<br>  parallel = TRUE<br>)</pre><p>We can extract the results and compare the AIC with the arima(…) function.</p><pre># Best Solution from GA<br>GA_param@solution<br>#       x1        x2        x3        x4<br># 0.591974 0.3090469 0.5065879 0.3927844<br><br># Best AIC from GA<br>-1*GA_param@fitnessValue<br># 141255<br><br># Best Solution from LL arima(...)<br>coef(arima(data, order = c(2, 0, 1)))<br>#       ar1       ar2       ma1 intercept<br># 0.5914393 0.3080580 0.5048795 0.4653240<br><br># Best AIC from LL arima(...)<br>AIC(arima(data, order = c(2, 0, 1)))<br># 141261.2</pre><p>Both methods estimates are very similar to the ‘true’ coefficients. GA-based ARIMA is only better by a very miniscule margin (in terms of AIC), while taking significantly longer (approximately 30s vs. 1s on the default arima). This improvement is unlikely to be worth the effort.</p><p>However, let’s try a more complex SARIMA(4,1,2)(3,1,2)7. Do note that simulating peculiar sarima data is…. well, not very common.</p><pre># Generate Data SARIMA(4,1,2)(3,1,2)7 which is kinda dumb <br>require(astsa)<br>set.seed(2323)<br>data = sarima.sim(ar = c(-0.1, -0.2, 0.1, 0.2),<br>                  ma = c(0.1, 0.2),<br>                  d = 1,<br>                  sar = c(0.1, -0.5, 0.02),<br>                  sma = c(-0.7, -0.15),<br>                  D = 1,<br>                  S = 7,<br>                  n = 12000)<br>plot(data, type = &#39;l&#39;, main = &#39;SARIMA(4,3,2)(3,1,3)7&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhFUSHOH43cfi-ENxw3IMw.png" /></figure><p>This now requires 11 coefficients to be optimized (jeez). Also, enabling parallel argument would increase memory usage, beyond 8GB of what my machine can handle lol, so I would highly recommend disabling parallelization.</p><pre>param_optim_function = function(p){<br>  mod = arima(data, order = c(4, 1, 2), seasonal = list(order = c(3, 1, 2), period = 7), method = &#39;CSS-ML&#39;, <br>              optim.method = &#39;Nelder-Mead&#39;, fixed = p)<br>  result = AIC(mod)<br>  if(length(result) &lt; 1){ result = Inf}<br>  return(result)<br>}<br><br>GA_param &lt;- ga(type = &quot;real-valued&quot;, <br>               fitness = function(x) -param_optim_function(x),<br>               lower = rep(0, 11), <br>               upper = rep(1, 11),<br>               popSize = 50, <br>               maxiter = 100,<br>               run = 100,<br>               monitor = TRUE,<br>               parallel = FALSE)</pre><p>I left the code running for…? I’m not sure actually, it took so long that I left for a quick bath and dinner and it <strong>STILL WASN’T DONE YET</strong> so yeah this is why GA is probably not best for this kind of problem lol. As a benchmark, the computer I’m running has a Ryzen 7 4800U.</p><pre># Best Solution GA<br>GA_param@solution<br>#        x1        x2        x3         x4        x5        x6        x7        x8        x9       x10       x11<br># 0.1483993 0.2903742 0.4136625 0.08564639 0.5471199 0.3520466 0.2675962 0.2545827 0.3722336 0.4210016 0.2861576<br><br># Best Solution arima LL<br>a = arima(data, order = c(4, 1, 2), seasonal = list(order = c(3, 1, 2), period = 7), method = &#39;CSS-ML&#39;, <br>           optim.method = &#39;Nelder-Mead&#39;)<br>coef(a)<br>#        ar1         ar2         ar3         ar4         ma1         ma2        sar1        sar2        sar3        sma1 <br># 0.31578680  0.36177022  0.07761878  0.11708071 -0.33820063 -0.36666042  0.21253068 -0.50781697  0.10257276 -0.77904616 <br>#        sma2 <br># -0.09032874 <br><br># Best AIC GA<br>-1*GA_param@fitnessValue<br># 57186.22<br><br># Best AIC arima LL<br>AIC(a)<br># 34843.14</pre><p>Adding population size and maximum iteration will help (probably), but oh well, it would not be much better.</p><h3>Going Further with AutoARIMA and Exogenous Factors</h3><p>Again, as long as we have function to optimize (within reasons), we can use GA. We may also introduce exogenous factors into the equation and optimize them yet again with GA, although we can’t directly measure its bias-variance tradeoff due to the nature of the algorithm. Automated order selection is also possible since they can also be interpreted as individual parameters (with added constraint that they must be integers).</p><p>It should be noted that we may need to increase the population and/or iteration as well as adjusting the GA parameters in order to achieve a good solution within reasonable time. The key here is ‘reasonable time’ as most of the time, the improvement gain over built-in ARIMA is not worth our effort.</p><p>Well that’s it. Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03f24ab66589" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide on Scikit-learn for Time Series Forecasting]]></title>
            <link>https://medium.com/@mouse3mic3/a-practical-guide-on-scikit-learn-for-time-series-forecasting-bbd15b611a5d?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbd15b611a5d</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[forecast]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 15:08:56 GMT</pubDate>
            <atom:updated>2023-12-12T15:08:56.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IDhEPANq9fT-vgoj" /><figcaption>Photo by <a href="https://unsplash.com/@shawn99lee?utm_source=medium&amp;utm_medium=referral">Shawn Lee</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While most machine learning algorithms available in scikit-learn (and various other compatible libraries such as LightGBM) are commonly used for tabular regression and classification, there is no inherent reason why they cannot be effectively applied to time series forecasting.</p><p>From a theoretical perspective, these approaches may not necessarily satisfy the conditions required for a regression model. Time series data typically exhibit some degree of autocorrelation, meaning that the observed data at time<em> t</em> is related to the previous data (<em>t-1</em>) and possibly even more. An ordinary regression model typically assumes independent observations; thus, they may not be well-suited to capture autocorrelation. However, it is still possible to use lagged series as predictors and allow the model to learn existing autocorrelation or other patterns.</p><p>Scikit-learn offers a broad range of regression models, ranging from the fundamental linear regression to highly advanced boosted trees. Alongside these, hyperparameter tuning and the implementation of cross-validation are customary practices to ensure better generality and accuracy of the model.</p><p>Our focus here is on utilizing these models in a univariate time-series setting. Fortunately, several libraries have implemented this exact idea, and one such library is skforecast. Skforecast not only furnishes the necessary functions to utilize existing scikit-learn algorithms for time-series forecasting but also provides various cross-validation and hyperparameter tuning functionalities. Additionally, it allows for the inclusion of exogenous variables in the forecasting process.</p><h3>Pre-requisites</h3><p>This guide was written for Python 3.11. Several packages will be helpful during this tutorial, run these command to install them.</p><ul><li>pip install skforecast</li><li>pip install seaborn</li><li>pip install matplotlib</li><li>pip install pmdarima</li></ul><p>We will be predicting Jakarta’s air quality. Specifically, we will be predicting the city’s PM2.5 level, which stands for fine particles found in air. A high level of PM2.5 is considered dangerous to human’s health as it can remain for a very long time in the air and absorbed into the bloodstream if inhaled. A more detailed info about PM2.5 can be found <a href="https://www.iqair.com/newsroom/pm2-5">here</a>.</p><p>Air pollution is a big issue in Jakarta and it is not a new occurence either. It is an ongoing problem which poses a serious threat to many people who works there daily. The data used is South Jakarta daily average of PM2.5, which can be accessed freely <a href="https://aqicn.org/data-platform/register/">here</a>.</p><h3>The Basics</h3><p>Most of the basic discussed here is based on the <a href="https://skforecast.org/0.11.0/introduction-forecasting/introduction-forecasting">official documentation of skforecast</a>. Since we’re treating time-series forecasting as a regression problem, we would need to have predictor. Here we assume that we only have a univariate series. Let’s say 5 days of stock (closing) price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*mnIdEJm1BJBy0ugPF38ZSw.jpeg" /><figcaption>5 days of stock data example</figcaption></figure><p>At the start, we only have the stock price up until the 5th day. Let’s say that we use the previous 3 days as the predictor. This means we are using up to 3 lagged data. To predict the 4th day, we use the 1st-3rd data. To predict the 5th day, we use the 2nd-4th data. So, to predict the 6th day, we use the 3rd-5th data.</p><p>In tabular terms, we can write the predictor and response as follow. We label the yesterday data as Xt-1, two days ago as Xt-2, and three days ago as Xt-3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsvjYITIbT1zxY6fdhi3Bg.png" /><figcaption>Using lagged observation as the predictors</figcaption></figure><p>We have established a way to predict one step into the future. How about predicting 2 days ahead? Or 3? This is where we introduce the concept of recursive forecasting. In short, in order to predict 7th day, we make a prediction for 6th day and then use this predicted value as our Xt-1. Essentially, we are treating the previous forecast as a new predictor for the future. We do this as much as needed and is quite efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xL-cWlx1BWfnNsbx58Lk-g.png" /><figcaption>Recursive Forecasting</figcaption></figure><p>There are, however, several problems with this approach. If we wish to predict far into the future, the model may give a relatively flat prediction. It may also introduce new bias, since the predicted 6th data may be far from the true value. skforecast also provide an alternative called direct forecasting, which trains many different model, each is capable of predicting <em>n</em> step into the future. This approach may be more desirable in some cases.</p><p>Again, it is possible to include exogenous variates into the model. Keep in mind that to predict the 6th data, we must also provide the exogenous variate for that same index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKy3yhkWjKcHq9dMqpm34g.png" /><figcaption>Using exogenous variate</figcaption></figure><h3>Preprocessing</h3><p>Before we begin with modelling, we first run several basic pre-processing steps to tidy up our data. These steps are entirely optional and depends on the data we use.</p><pre>import pandas as pd<br><br># Load CSV<br>df = pd.read_csv(&#39;jakarta-south (us consulate)-air-quality.csv&#39;)<br><br># Re-format the date column and set it as index<br>df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;], format = &#39;%Y/%m/%d&#39;)<br>df.set_index(&#39;date&#39;, inplace = True)<br>df.sort_index(inplace = True)</pre><p>As seen above, we re-format the date to the correct datetime format. We also sort and set it as the series index.</p><pre># Set the dataset frequency to be (D)aily data<br>df = df.asfreq(&#39;D&#39;, method = &#39;bfill&#39;) </pre><p>I also highly recommend working with frequent data. Pandas support many different datafrequency through the <em>asfreq</em> method, in this case, we have daily data (D) and we fill any missing data by backfill (bfill). For different type of frequency, kindly read the docs <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases">here</a>.</p><pre># Change data type to float. Also, we only use data since Jan 2020 until Nov 2023<br>df = pd.to_numeric(df.loc[&#39;2020-01-01&#39;:&#39;2023-11-30&#39;, &#39; pm25&#39;], errors = &#39;coerce&#39;) <br><br># Fill missing value with the latest available data<br>df.ffill(inplace = True)</pre><p>Next, we select the <strong>pm25</strong> column and convert it into numerical float, and then, we fill any existing missing value with forward-fill.</p><h3>Simple Model</h3><p>We start by defining the train-test periods.</p><p>Let’s pretend that we have observed data up to 2023–04–30 and we want to predict the air quality in May 2023. To learn the concept of forecasting and cross-validation, we shall split the observed data into train and test period. Specifically, the train period ends in 2022–12–31, and the test period is between 2023–01–01 and 2023–04–30.</p><pre>train_start = &#39;2020-01-01&#39;<br>train_end = &#39;2022-12-31&#39;<br><br>test_start = &#39;2023-01-01&#39;<br>test_end = &#39;2023-04-30&#39;<br><br>forecast_start = &#39;2023-05-01&#39;<br>forecast_end = &#39;2023-05-31&#39;</pre><p>We visualize the train and test period using matplotlib.</p><pre>fig, ax = plt.subplots(figsize=(7, 3))<br>df.loc[train_start:train_end].plot(ax=ax, label = &quot;Train&quot;)<br>df.loc[test_start:test_end].plot(ax=ax, label = &quot;Test&quot;)<br>ax.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*KyNAQbwiOHzHvrus8VGGhQ.png" /><figcaption>Train and Test split</figcaption></figure><p>As seen above, the majority of our data is used for training. Our model will only learn the pattern of the train period, and then tries to predict the test period. We then measure the RMSE (Root Mean Squared Error), which is a popular method to measure prediction accuracy. The lower its value, the better.</p><pre># Define the forecaster<br>forecaster = ForecasterAutoreg(<br>    # Add the sklearn regressor and lags<br>    regressor = DecisionTreeRegressor(random_state = 123),<br>    lags = 30<br>)<br><br># Fit the model using train data<br>forecaster.fit(y = df.loc[train_start:train_end])<br><br># Predict the test period<br>predicted_test = forecaster.predict(steps = len(df.loc[test_start:test_end]))</pre><p>We define a forecaster object using the ForecasterAutoreg function. This function accepts several arguments, but for now, we only need to provide the regressor (i.e sklearn’s model) along with desirable hyperparameters, and the lags to be used as predictor.</p><p>For simple showcase, we begin with a Decision Tree model and 30 lags. We fit the model using only the train data. Finally, we use the fitted model to predict the test period.</p><p>For comparison, we also model an ARIMA model using AutoARIMA function in pmdarima using the following syntax. ARIMA is only used as a baseline.</p><pre>import pmdarima as pm<br><br>arima = pm.AutoARIMA(seasonal = False)<br>arima.fit(df.loc[train_start:train_end])<br><br># Predict train and test<br>arima_train = arima.predict_in_sample()<br>arima_test = arima.predict(len(df.loc[test_start:test_end]))</pre><p>We then compare the result using lineplot.</p><pre>fig, ax = plt.subplots(figsize=(7, 3))<br>df.loc[test_start:test_end].plot(ax=ax, label = &quot;Test&quot;)<br>predicted_test.plot(ax=ax, label = &#39;Predicted DT&#39;)<br>arima_test.plot(ax=ax, label = &#39;Predicted ARIMA&#39;)<br>ax.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*mk9eAFeKjYxma_UXAtikIA.png" /></figure><p>We see that, without any tuning whatsoever, our Decision Tree model tends to overestimate the true PM2.5 concentration. It also doesn’t seem to exhibit similar pattern to the actual data, but may look much better than what ARIMA had predicted. Selecting a different lags or tuning the decision tree’s parameters could help with this issue.</p><p>We can also measure its train and test RMSE. The residual of the train data can be accessed from the <em>in_sample_residual </em>method. We then compute the RMSE as follow.</p><pre>import numpy as np<br>from sklearn.metrics import mean_squared_error<br><br>rmse_train = np.sqrt(np.mean(np.square(forecaster.in_sample_residuals)))<br>rmse_test = np.sqrt(mean_squared_error(df.loc[test_start:test_end], predicted_test))<br>print(&#39;RMSE Train:&#39;, rmse_train,&#39;\nRMSE Test:&#39;, rmse_test)<br><br>arima_rmse_train = np.sqrt(mean_squared_error(df.loc[train_start:train_end], arima_train))<br>arima_rmse_test = np.sqrt(mean_squared_error(df.loc[test_start:test_end], arima_test))<br>print(&#39;RMSE Train ARIMA:&#39;, arima_rmse_train,&#39;\nRMSE Test ARIMA:&#39;, arima_rmse_test)<br><br># RMSE Train: 0.9037422198835241 <br># RMSE Test: 47.20593734725891<br># RMSE Train ARIMA: 20.275019309369004 <br># RMSE Test ARIMA: 23.31790195763905</pre><p>Our model seems to suffer from overfitting (and badly at that!). It performs really well on the train data compared to ARIMA, but falls apart on the test period. It turns out that using ARIMA to only predict the mean is a lot better and much more consistent.</p><h3>Backtesting (Cross-validation)</h3><p>Backtesting is a form of cross-validation for time series. It is similar in concept, but a key difference is that we can’t split the dataset in random order (i.e the test period must be after the train period). The goal is to yield a model that generalizes better and avoid overfitting. We can measure the model’s true accuracy by testing it on different slice of data at once.</p><p>Skforecast provides three different kind of backtesting with excellent explanation <a href="https://skforecast.org/0.11.0/introduction-forecasting/introduction-forecasting">here</a>. There are two main parameters, initial train size and forecast steps.</p><p>Let’s pretend we have 10 days worth of stock data. We set the initial train size to 4 and forecast steps to 2 (two steps ahead).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SshoBqwVh21n42u0csD8gA.png" /><figcaption>Different types of backtesting</figcaption></figure><ul><li><strong>No Refit</strong><br>This is the fastest method to backtesting. We train a model using the 1st-4th data. Then, we predict the 5th-6th data, the 7th-8th data, and 9th-10th data. We note the RMSE. This approach is fast since we only need to train the model once. However, when trying to predict the 9th data, it still only has information up until the 4th data, where the 5th-8th data is left unused. It’s like the model is handicapped intentionally.</li><li><strong>With Refit and Increasing Train Size</strong><br>We train a model using the 1st-4th data and predict the 5th-6th data. We note the RMSE. Next, we train the model again using the 1st-6th data and predict the 7th-8th data. Again, we note the RMSE. Lastly, we train the model using the 1st-8th data, predict the 9th-10th data, and note the RMSE. Using this approach, it’s like we created three different model with different time period.</li><li><strong>With Refit and Fixed Train Size</strong><br>Similar to the previous one, except we keep the training size constant. That is, we train a model using 1st-4th data and predict the 5th-6th data. Then, we train another model using the 3rd-6th data and predict the 7th-8th data. Lastly, we train another model using the 5th-8th data and predict the 9th-10th data.</li></ul><p>Let’s try it out! We will implement a backtest with refit and increasing train size. All train and test data will be used, but only the train data will be used as initial train size. We also set the steps to be 30 to reflect the fact that we are interested in forecasting 30 days ahead.</p><pre>from skforecast.model_selection import backtesting_forecaster<br><br>forecaster = ForecasterAutoreg(<br>    regressor = DecisionTreeRegressor(random_state = 123),<br>    lags = 30<br>)<br><br># With Refit and Increasing Train Size<br>metric, predicted_backtest = backtesting_forecaster(<br>    forecaster = forecaster,<br>    y = df.loc[train_start:test_end],<br>    steps = 30,<br>    metric = &#39;mean_squared_error&#39;,<br>    initial_train_size = len(df.loc[train_start:train_end]),<br>    fixed_train_size = False, # Set this to true for fixed train size<br>    allow_incomplete_fold = True,<br>    refit = True # Change this to False to disable refit<br>)<br><br># Display RMSE<br>np.sqrt(metric)<br># RMSE: 36.368713660691014</pre><p>The resulting RMSE is more representative of the true accuracy of the model. It’s not much better than what we had before, so we would need to do some tuning before we can deploy the model.</p><h3>Hyperparameter Tuning: Grid Search</h3><p>Grid search is one popular kind of hyperparameter tuning, although it is also considered inefficient. Each algorithm (e.g decision tree, XGBoost, LightGBM) has a ‘setting’ or ‘config’ that we can change accordingly. Different combinations will lead to a change in model performance. Theoretically, there should be combinations that are considered good or best for the data in hand. Grid search finds these by brute force. We provide a list of parameters to try out and we simply check every single combinations.</p><p>If we are not interested in tuning the regressor’s hyperparameter, we can also tune the lags used as predictor. skforecast automatically tries all the lags config given by the user, so it is recommended to keep it simple and focus more on the regressor hyperparameter. A list and detail of each hyperparameter can be found in the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html">official docs of sklearn</a>.</p><pre>from skforecast.model_selection import grid_search_forecaster<br><br>forecaster = ForecasterAutoreg(<br>    regressor = DecisionTreeRegressor(random_state = 123),<br>    lags = 30 # This is now a placeholder<br>)<br><br># Parameter Grid for Regressor<br>param_grid = {<br>    &#39;max_depth&#39; : [None, 1, 3, 5],<br>    &#39;min_samples_split&#39; : [2, 3, 4],<br>    &#39;ccp_alpha&#39; : [0.0, 0.001, 0.01]<br>}<br><br># Lags Grid<br>lags_grid = [30, 50, 100, 150, [1,2,3,4,5,7,9,13,15,20,50]]<br><br># Grid Search with Refit and Increasing Train Size<br>grid_forecaster = grid_search_forecaster(<br>    forecaster = forecaster,<br>    y = df.loc[train_start:test_end],<br>    param_grid = param_grid,<br>    lags_grid = lags_grid,<br>    steps = 30,<br>    refit = True,<br>    metric = &#39;mean_squared_error&#39;,<br>    initial_train_size = len(df.loc[train_start:train_end]),<br>    fixed_train_size = False,<br>    return_best = True,<br>    verbose = False<br>)<br><br># Lags: [1, ..., 150]<br># Parameters: {&#39;ccp_alpha&#39;: 0.01, &#39;max_depth&#39;: None, &#39;min_samples_split&#39;: 4}<br><br># Backtest RMSE<br>np.sqrt(grid_forecaster.iloc[0][&#39;mean_squared_error&#39;])<br># RMSE: 31.522720910895814</pre><p>We observe that the backtest RMSE is improving from the previous 36.38. With a better param_grid and lags_grid, it is perhaps possible to improve this further. The best lags config is 150, along with the regressor hyperparameters.</p><p>We’ll forecast the forecast period and compare the result later.</p><pre>DT_grid = forecaster.predict(steps = len(df.loc[forecast_start:forecast_end]))</pre><h3>Hyperparameter Tuning: Optuna/Bayesian Search</h3><p>Optuna is another approach to the hyperparameter problem. It is a smarter way to hyperparameter search. In order to use this, instead of supplying a list of parameters, we supply a search space (i.e a ‘range’ of numbers that can be randomly picked from).</p><p>We also introduce another popular algorithm LightGBM as the regressor.</p><pre>from lightgbm import LGBMRegressor<br>from skforecast.model_selection import bayesian_search_forecaster<br><br>forecaster = ForecasterAutoreg(<br>    regressor = LGBMRegressor(random_state = 123),<br>    lags = 30 # This is now a placeholder<br>)<br><br># Lags Grid<br>lags_grid = [30, 50, 100, 150, [1,2,3,4,5,7,9,13,15,20,50]]<br><br># Search Space<br>def search_space(trial):<br>    search_space = {<br>        &#39;num_leaves&#39; : trial.suggest_int(&#39;num_leaves&#39;, 10, 40),<br>        &#39;max_depth&#39; : trial.suggest_int(&#39;max_depth&#39;, -1, 10),<br>        &#39;learning_rate&#39; : trial.suggest_float(&#39;learning_rate&#39;, 0.001, 0.1),<br>        &#39;n_estimators&#39; : trial.suggest_int(&#39;n_estimators&#39;, 50, 1000),<br>        &#39;reg_alpha&#39; : trial.suggest_float(&#39;reg_alpha&#39;, 0.0, 0.5)<br>    }<br>    return search_space<br><br>results, frozen_trial = bayesian_search_forecaster(<br>    forecaster = forecaster,<br>    y = df.loc[train_start:test_end],<br>    lags_grid = lags_grid,<br>    search_space = search_space,<br>    steps = 30,<br>    refit = True,<br>    metric = &#39;mean_squared_error&#39;,<br>    initial_train_size = len(df.loc[train_start:train_end]),<br>    fixed_train_size = False,<br>    return_best = True,<br>    verbose = False,<br>    random_state = 123,<br>    engine = &#39;optuna&#39;<br>)<br><br># Backtest RMSE<br>np.sqrt(results.iloc[0][&#39;mean_squared_error&#39;])<br><br># Lags: [1, ..., 150]<br># Parameters: {&#39;num_leaves&#39;: 19, &#39;max_depth&#39;: 4, &#39;learning_rate&#39;: 0.08944552714859635, &#39;n_estimators&#39;: 947, &#39;reg_alpha&#39;: 0.2509183379421683}<br># RMSE: 26.4541643045085</pre><p>In terms of backtest RMSE, we obtain a much improved result, which could be the result of changing to a more sophisticated LightGBM model, and not specifically because we use Optuna as opposed to Grid Search.</p><p>Like before, we save the forecast for the forecast period.</p><pre>LGBM_Optuna = forecaster.predict(steps = len(df.loc[forecast_start:forecast_end]))</pre><h3>Comparing the Forecast</h3><p>We end the main section of this article by comparing the models created. We forecast the May 2023 period. Again, ARIMA will be used as baseline.</p><pre># ARIMA as Baseline<br>arima = pm.AutoARIMA(seasonal = False)<br>arima.fit(df.loc[train_start:test_end])<br>arima_predicted = arima.predict(len(df.loc[forecast_start:forecast_end]))</pre><p>First, we compare the RMSE on the forecast period between Decision Tree + Grid Search, LightGBM + Optuna, and ARIMA.</p><pre>rmse_dt_grid = np.sqrt(mean_squared_error(df.loc[forecast_start:forecast_end], DT_grid))<br>rmse_lgbm_optuna = np.sqrt(mean_squared_error(df.loc[forecast_start:forecast_end], LGBM_Optuna))<br>rmse_arima = np.sqrt(mean_squared_error(df.loc[forecast_start:forecast_end], arima_predicted))<br>print(&#39;DT Grid:&#39;, rmse_dt_grid, &#39;\nLGBM Optuna:&#39;, rmse_lgbm_optuna, &#39;\nARIMA:&#39;, rmse_arima)<br><br># DT Grid: 32.994111699059815 <br># LGBM Optuna: 29.965709671523367 <br># ARIMA: 33.36078377027257</pre><p>We observe that LightGBM+Optuna gives an overall better PM2.5 concentration forecast on May 2023, followed by Decision Tree+Grid Search, and ARIMA. While this result is not representative of the real world performance, it shows that using scikit-learn for time-series forecasting is not only possible, but practical and reasonable.</p><pre>fig, ax = plt.subplots(figsize=(7, 3))<br>df.loc[forecast_start:forecast_end].plot(ax=ax, label = &#39;Actual&#39;)<br>DT_grid.loc[forecast_start:forecast_end].plot(ax=ax, label = &#39;DT Grid&#39;)<br>LGBM_Optuna.loc[forecast_start:forecast_end].plot(ax=ax, label = &#39;LGBM Optuna&#39;)<br>arima_predicted.loc[forecast_start:forecast_end].plot(ax=ax, label = &#39;ARIMA&#39;)<br>ax.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*Irm94m66f7pNnNHjIKHWxA.png" /><figcaption>Forecast Result</figcaption></figure><p>With that said, I believe that all the model requires further tuning as they underestimate the true PM2.5 concentration in Jakarta. People who live in Jakarta may wrongly conclude that the air quality is ‘better’ than what it would be.</p><h3>Other Parameters of Forecaster</h3><p>There are several other parameter that we can pass to the ForecasterAutoreg object. These are discussed in detail by the official docs <a href="https://skforecast.org/0.11.0/introduction-forecasting/forecaster-parameters">here</a>. We shall discuss the important ones.</p><ul><li><strong>lags</strong><br>This value can be an integer or list. An integer indicates all lags up until that value. A list indicates specific lags to be used.</li><li><strong>transformer_y</strong><br>Add a transformer to transform the response before training (e.g Normalize, Standardize, etc). Try sklearn’s <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html">StandardScaler()</a> or <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html">MinMaxScaler()</a>.</li><li><strong>transformer_exog</strong><br>Similar but applied to exogenous variates</li><li><strong>differentiation</strong><br>Replacing the response by the difference between current and previous value. Forecasting the differenced series (which is basically the rate of change) is usually a lot easier.</li><li><strong>fit_kwargs</strong><br>Some regressor may allow the use of additional parameters. These are usually passed in the form of dictionary, with each key representing one parameter.</li></ul><h3>Exogenous Variates</h3><p>Note that each exogenous variable must be available for all time periods, including the train, test, and forecast periods. Here, we simulate two exogenous variates. These will act as additional predictors.</p><pre>exog_1 = np.log(np.float_power(df, 10))<br>exog_2 = np.float_power(df, 0.75) + 50 + np.random.normal(scale = 10)<br><br># Merge y and exogenous<br>df_exog = pd.concat([df, exog_1, exog_2], axis = 1)<br>df_exog.columns = [&#39;y&#39;, &#39;exog_1&#39;, &#39;exog_2&#39;]<br><br># Plot<br>fig, ax = plt.subplots(figsize=(7, 3))<br>df_exog.loc[train_start:test_end].plot(ax=ax)<br>ax.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*WIO6UyLjlsVJJcFRNhvkfQ.png" /><figcaption>Simulated exogenous variates</figcaption></figure><p>The only thing we need to change is adding the exogenous variates during model fitting and prediction. Keep in mind that the time periods between y and exog must match.</p><pre>forecaster_exog = ForecasterAutoreg(<br>    regressor = DecisionTreeRegressor(random_state = 123),<br>    lags = 30<br>)<br># Model Fit<br>forecaster_exog.fit(y = df_exog.loc[train_start:train_end, &#39;y&#39;],<br>               exog = df_exog.loc[train_start:train_end, [&#39;exog_1&#39;, &#39;exog_2&#39;]]<br>)<br># Model Predict<br>predicted_test_exog = forecaster_exog.predict(steps = len(df.loc[test_start:test_end]),<br>                                              exog = df_exog.loc[test_start:test_end, [&#39;exog_1&#39;, &#39;exog_2&#39;]])<br><br># Visualize<br>fig, ax = plt.subplots(figsize=(7, 3))<br>df.loc[test_start:test_end].plot(ax=ax, label = &quot;Test&quot;)<br>predicted_test_exog.plot(ax=ax, label = &#39;Predicted DT Exog&#39;)<br>ax.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*HmpNxPmxYRbb_O-nw3Sx6g.png" /><figcaption>Observed vs Predicted, Model with Exogenous Variates</figcaption></figure><p>We observe that even with a simple model, the addition of exogenous variates practically made the model perfect. Of course this is because the exogenous variates are heavily related to the response. In the real world, we usually limit ourselves to only use important exogenous variate to avoid unnecessarily complex model.</p><h3>Feature Importance</h3><p>We can also extract the feature importances, which is a measure of the contribution of each lag and exogenous variates. High value indicates big contribution. We can use this as a method of variable selection. By removing variates that don’t contribute much to the model, we can create a simpler model that may generalize better.</p><pre># Table<br>forecaster_exog.get_feature_importances()<br><br># Barplot<br>forecaster_exog.get_feature_importances().plot(kind = &#39;bar&#39;, x = &#39;feature&#39;)</pre><h3>Epilogue</h3><p>To close this, I would like the readers to also try out other state-of-the-art forecast methods. The popular <a href="https://facebook.github.io/prophet/">Facebook’s Prophet</a> library would be an excellent start, along with <a href="https://neuralprophet.com/">NeuralProphet</a> which is deeply tied to PyTorch deep learning approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbd15b611a5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Guide to Causal Impact Package with Custom Model and Prior]]></title>
            <link>https://medium.com/@mouse3mic3/a-practical-guide-to-causal-impact-package-with-custom-model-and-prior-31b5cb714a41?source=rss-c81b53ecc773------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b5cb714a41</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[analysis]]></category>
            <dc:creator><![CDATA[Zaki Nurkholis]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 02:56:11 GMT</pubDate>
            <atom:updated>2023-11-19T02:56:11.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbH1tgPkPgwbkdjD" /><figcaption>Photo by <a href="https://unsplash.com/@syinq?utm_source=medium&amp;utm_medium=referral">Susan Q Yin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For those curious about understanding the impact of interventions like government policies, app releases, or changes in work-from-home policies on specific metrics, the Causal Impact method by Brodersen et al. (2015) could be a valuable tool.</p><p>Imagine having the power into the data realm, where each governmental decision or organizational shift acts as a protagonist in the eye of metrics. The Causal Impact method helps you evaluate changes and its evolution throughout time in your chosen metrics.</p><h3>Prologue</h3><p>As I delve into my undergraduate thesis on this method, I appreciate its practicality. Implementing it is straightforward, thanks to the user-friendly CausalImpact R package.</p><p>Yet, delving into the theory behind Causal Impact might not be everyone’s cup of tea. It heavily relies on simulations, demanding computational skills. Ensuring the accuracy of these simulations requires understanding concepts like the consistency of Markov Chain Monte Carlo (MCMC) algorithms and Bayesian methodologies.</p><p>The good news is, recent advances in Bayesian approaches have made this process more accessible. Now, with just a standard computer, most individuals can efficiently run analyses. Causal Impact, grounded in a state-space model for time series, particularly Bayesian Structural Time Series, conducts inference on posterior samples (let’s simplify and say the p-value is obtained through a different method).</p><h3>About Causal Impact</h3><p>Here we shall discuss the important parts of Causal Impact method. A more detailed explanation of how it works can be found in the original paper <a href="https://storage.googleapis.com/pub-tools-public-publication-data/pdf/41854.pdf">here</a>. If possible, I will also write a different article on how it works in detail.</p><p>Causal Impact stands as a refinement of the widely used difference-in-differences (DD) design. It uses the concept of synthetic counterfactual, that is, we attempt to combine multiple different ‘predictors’ into one that closely mimic the response series. This enables us to predict the response as if there were no intervention.</p><p>The incorporation of predictors is entirely optional. Additionally, we leverage historical response patterns to forecast future trends using the structural time series model. This model is flexible, allowing the addition or removal of different ‘components.’ For instance, if our data exhibits a seasonal pattern, we can seamlessly integrate this seasonal component into the existing model. Predictors also function as one of the components we can add.</p><p>The objective is to precisely predict the response in the absence of an intervention. To illustrate, imagine running an advertising campaign across all user segments without a valid control group. By tracking the daily new user data for several weeks, we wish to measure the campaign’s impact on increasing this figure. Since we don’t have a control group, comparing this number becomes challenging, hindering our ability to evaluate the causal effect of the campaign. Causal Impact, and several other DD alternatives, helps us by providing a ‘control’ group, termed counterfactual. This helps determine the probability of a causal effect and its relative size.</p><p>There are several key strong, but flexible assumptions.</p><ul><li>The predictors must have some degree of correlation with the response, and this correlation should remain stable during both pre and post-intervention.</li><li>The predictors must also not directly influenced by the intervention itself. This is because if the predictors are influenced, then the predicted counterfactual is also influenced by the intervention.</li><li>Any common shock/effects should be captured by both the response and predictors, ensuring that changes affecting both series are reflected in the data.</li></ul><h3>Let’s Get Started!</h3><p>There are several packages that we’ll need. We’ll also set the number of MCMC iterations to be 3000. In practice, we should be using more samples to ensure convergence. I personally recommend 30000 to be safe, although this will increase memory usage quite significantly.</p><pre>require(CausalImpact) <br>require(ggplot2) # Optional, only for visualization purposes<br>require(timeDate) # Optional, only for simulating the data<br><br># Set iteration counts<br>niter = 3000<br><br># Set seed to ensure simulation reproducibility, entirely optional<br>addTaskCallback(function(...) {set.seed(1212);TRUE})</pre><h3>Data</h3><p>Our company specializes in selling car accessories through an app. In an attempt to increase user engagement and improve sales, we deploy a visual UI change in the checkout process. The new interface is much simpler, streamlined with fewer clutters and allows user to complete their purchase within one page.</p><p>We’ll be simulating <strong>daily transacting user (DTU)</strong>. This data counts how many (unique) users have done the checkout process (i.e buys our product) every day. We think that, due to the visual changes to the checkout page, we should be looking at a lift in transacting user.</p><p>We’ll also be generating several other variates, namely</p><ul><li><strong>daily active user (DAU)</strong>, which counts the number of (unique) user who accessed our app</li><li><strong>daily new user (DNU)</strong>, which counts the number of new user sign up</li><li><strong>push notification click-through-rate (PN CTR)</strong>, which is the proportion of user who clicked on the promo/news sent to their push notification</li><li><strong>personalized email click-through-rate (Email CTR)</strong>, which is the proportion of user who clicked on the promo/news sent to their email</li><li><strong>google ads click-through-rate (Ads CTR)</strong>, which is the proportion of user who clicked on our google ads targeted to them</li></ul><p>These covariates can be used as a predictor to daily transacting user since they are not directly affected by the change, should have some degree of correlation with DTU, and should follow similar trend with DTU before the visual change.</p><p>The simulation code is provided here (please kindly ignore the mess). In practice, this kind of data should be available 7 days a week. However, to highlight working with ‘irregular’ data, we will generate business day (5-days-a-week) data from June 1st, 2022 until May 31st, 2022. In total, we have 261 business days.</p><p>The change is implemented widely to all user in April 1st, 2022. In practice, this is a horrible idea since implementing a new change can be done more safely by A/B test. However, here we assume to have done A/B test earlier this year and found positive result on the treated group (i.e users who receive the new interface). We run Causal Impact analysis when the change is widely implemented to ensure that the positive result remains.</p><pre># Generate workdays from June 2021 until May 2022, totalling 261 days<br>time_idx = as.timeDate(seq(from = as.Date(&#39;2021-06-01&#39;), to = as.Date(&#39;2022-05-31&#39;), by = &#39;day&#39;))<br>time_idx = as.Date(time_idx[isBizday(time_idx, holidays = holidayNYSE(), wday = 1:5)])<br>length(time_idx)<br><br># Generate response: daily transacting user<br>dtu = arima.sim(n = 261, list(ar = c(0.5677, -0.132), ma = c(-0.2456)), sd = 180) + seq(from = 2540, to = 2400, length.out = 50) + 1000<br>dtu[1:220] = dtu[1:220] + (seq(from = 50000, to = 1, length.out = 220))^0.6<br>dtu[121:145] = dtu[121:145] + (seq(from = 1, to = 20000, length.out = 25))^0.5<br>dtu[146:170] = dtu[146:170] + (seq(from = 20000, to = 1, length.out = 25))^0.5<br><br># Generate predictors: daily active user<br>dau = dtu*20 + rnorm(261, sd = 60)<br><br># Generate predictors: push notification ctr<br>pn = (dtu-mean(dtu))/sd(dtu) + rgamma(n = 261, shape = 2, scale = 0.5)<br>pn = (pn-min(pn))/(max(pn)-min(pn)) * 0.03<br><br># Generate predictors: email ctr<br>email = (dtu-mean(dtu))/sd(dtu) + rgamma(n = 261, shape = 1.5, scale = 0.9)<br>email = (email-min(email))/(max(email)-min(email)) * 0.021<br><br># Generate predictors: Google ads ctr<br>gads = (dtu-mean(dtu))/sd(dtu) + rgamma(n = 261, shape = 15, scale = 10)<br>gads = (gads-min(gads))/(max(gads)-min(gads)) * 0.08<br><br># Generate predictors: daily new users<br>nu = sqrt(dtu*40) - sd(dtu) + rgamma(n = 261, shape = 6, scale = 29)<br><br># Add intervention effect on April 1st 2022. We also keep the true counterfactual.<br>dtu_counterfactual = dtu<br>dtu[219:261] = dtu[219:261] + (seq(from = 1, to = 50000, length.out = 43))^0.5<br><br># Finalization<br>data = zoo((cbind(round(dtu), round(dau), pn, email, gads, round(nu))), time_idx)<br>colnames(data) = c(&#39;DTU&#39;, &#39;DAU&#39;, &#39;PN&#39;, &#39;EMAIL&#39;, &#39;G-ADS&#39;, &#39;NU&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLeBxN001ckg_0ZVkX3sXA.png" /><figcaption>Taking a look at the simulated data</figcaption></figure><p>We see that in the past year, the number of transacting users have gone down slightly. DAU, PN, and EMAIL also exhibit a similar trend, whereas Google Ads and Daily New Users remain constant. The predictors seem to be related to DTU during the pre-intervention period (i.e before April 2022), suggesting that they are suitable to be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*Ipfe7GeIJPGKqjRdEVnzEg.png" /><figcaption>Observed DTU and its counterfactual</figcaption></figure><p>We see that there is indeed a clear positive intervention effect post-April 2022. Causal Impact analysis is designed to determine whether this effect is meaningful and show the effect size.</p><h3>Preparation</h3><p>Before we begin the analysis, there are several things we need to do. Since we are going to be using custom bsts model, we should ‘split’ the response (DTU) into pre and post-intervention.</p><p>First, we define the pre and post intervention periods. Remember that the change is implemented in 1st of April 2022.</p><pre># Define Pre and Post Intervention Periods<br>pre_intervention = as.Date(c(&#39;2021-06-01&#39;, &#39;2022-03-31&#39;))<br>post_intervention = as.Date(c(&#39;2022-04-01&#39;, &#39;2022-05-31&#39;))</pre><p>We also compute the standard deviation of response (DTU) in pre-intervention period. This value is useful to scale our prior parameters later, although entirely optional.</p><pre># Compute the standard deviation of response (DTU) in the pre-intervention period<br># useful for specifying prior later<br>sd_dtu = sd(data$DTU[index(data) &lt;= pre_intervention[2]])</pre><p>We copy the response (DTU) in the post-intervention period to a separate object named post_period_dtu. Then, in the original data table, we replace the DTU to NA in the post-intervention period.</p><pre># Set the response (DTU) in post-intervention to NA<br># We keep the observed post-intervention in a separate object (post_period_dtu)<br>post_period_dtu = as.vector(data$DTU[index(data) &gt;= post_intervention[1]])<br>data$DTU[index(data) &gt;= post_intervention[1]] = NA<br><br>tail(data) # DTU should be NA</pre><p>Working with irregular series (or non-daily series) is quite tricky. Even though I have specified the date index correctly, there seems to be a bug in the library causing the following error to show up no matter what.</p><pre>Error in data.frame(y.model, cum.y.model, point.pred, cum.pred) : <br>  arguments imply differing number of rows: 261, 365</pre><p>However, changing the date indexing to integer indexing solves this problem entirely (albeit, not very convenient). We just have to remember that the intervention day (April 1st 2022) corresponds to the 219th data.</p><pre>cat(&#39;Intervention of April 1st 2022 is the&#39;, which(time(data) == &#39;2022-04-01&#39;),&#39;th data&#39;)<br>time(data) = seq(1, NROW(data), length.out = NROW(data))<br># &gt; Output: Intervention of April 1st 2022 is the 219 th data</pre><p>Now we’re set!</p><h3>Creating Custom bsts Model and Prior</h3><p>There are three steps to use a custom bsts model in a Causal Impact analysis.</p><ul><li><strong>Define the state specification</strong> along with prior parameters. Prior parameters are optional and come with an uninformative default value. The state specification is essentially a list in which each element correspond to a single state component. Example: Local Level, Seasonal, and Dynamic Regression.</li><li><strong>Fit the bsts model</strong>. Since we have set the response to NA in post-intervention period, the model is only fitted to available pre-intervention data. There are several arguments that control the regression component, iterations, and observational error distribution.</li><li><strong>Run the Causal Impact analysis</strong> by supplying the custom model and observed post-intervention response.</li></ul><h3>State Specification</h3><p>A detailed information on available state components can be accessed <a href="https://cran.r-project.org/web/packages/bsts/bsts.pdf">here</a>. We shall discuss the important ones.</p><p>The bsts package offers many different state components, each with their own characteristics. These are provided as a function with the <strong>add</strong> prefix. A state specification begins with an empty list. For each new state component, we pass the existing specification as an argument.</p><pre>ss = list() # Initial<br>ss = AddLocalLevel(ss, ...) # Add Local Level, pass the empty list<br>ss = AddSeasonal(ss, ...) # Add Seasonality, pass the local level list<br>ss = AddAr(ss, ...) # Add Autoregressive, pass the local level and seasonal</pre><p>The following summarizes the popular available options, along with important parameters. Again, the details of each is available in the official docs <a href="https://cran.r-project.org/web/packages/bsts/bsts.pdf">here</a>.</p><ul><li><strong>add.ar(state.specification, y, lags, …)</strong><br>Adds autoregressive of order p to state component.</li><li><strong>add.dynamic.regression(state.specification, formula, data, …)</strong><br>Adds dynamic coefficients, evolving over time. If we are using static coefficients, we do not need to add a new component like this one.</li><li><strong>add.local.level(state.specification, y, …)</strong><br>Adds local level model, where the trend follows a random walk. The default of CausalImpact, and usually only provide relatively flat predictions.</li><li><strong>add.local.linear.trend(state.specification, y, …)</strong><br>Adds local linear trend, the slope is added and follow a random walk.</li><li><strong>add.semilocal.linear.trend(state.specification, y, …)</strong><br>Similar to local linear trend, but the slope is an AR(1) process with a long term slope parameter. Usually not ideal for data with changing trends.</li><li><strong>add.student.local.linear.trend(state.specification, y, …)</strong><br>Similar to local linear trend, but the random walk for trend and slope are t-distributed.</li><li><strong>add.random.walk.holiday(state.specification, y, holiday, …)</strong><br>Explicitly models the holiday component along with its evolution. Must provide a Holiday class object that specifies the holiday’s window of influence.</li><li><strong>add.seasonal(state.specification, y, nseasons, season.duration, …)</strong><br>Adds seasonality component. Must provide the number of seasons (nseasons) and length of each season (season.duration). If your data is daily and the seasonal effect is monthly, consider using <strong>add.monthly.annual.cycle</strong>.</li><li><strong>add.trig(state.specification, y, period, frequencies, …)</strong><br>Alternative to seasonal, in which the seasonality is trigonometric.</li></ul><p>Let’s try creating a local linear trend model with seasonality and static regression.</p><p>The local linear trend has two priors for the mean (level) term, and two for the slope term. These are the diffusion (error) variance (level.sigma.prior and slope.sigma.prior) and initial distribution for each term. We’re interested in the diffusion variance prior since the default value for initial distribution prior are usually adequate.</p><p>In Brodersen et al. (2015) and Scott &amp; Varian (2013) papers, the prior given to diffusion term is an <em>Inverse Gamma (v/2, s/2)</em>. The <em>v</em> parameter can be thought of as prior sample size, higher value indicates a more precise prior. The s = vσ₀² parameter is the sum-of-square of data, where σ₀² is the prior estimate of the diffusion variance. This prior estimate may be replaced by sample variance. This violates Bayesian paradigm where prior shall not be influenced by observed data, although in practice this is helpful to help scale the prior.</p><p>The function SdPrior must be used. This function allows us to specify <em>v </em>and <em>σ₀</em> estimate. Since we don’t have much information regarding prior observation, we shall set v to a small value, say 0.01, which happens to be the default value. The σ₀ prior can be obtained from sample standard deviation, which happens to be 248.08 (we’ll scale it down by multipliying it with 0.01). We’ll use this prior for the mean (level) term, and leave the slope to its default values. It is also possible to set σ₀ to a very small value (which is recommended as it is considered uninformative), but in this guide we shall try a custom value.</p><p>Next up is seasonality. We didn’t explicitly add a seasonal pattern to the simulated data, however, there is a weak repeating pattern as a result of</p><pre>... + seq(from = 2540, to = 2400, length.out = 50) + ...</pre><p>which may suggest a seasonal pattern every 50 workdays. Remember that each season follows a random walk and thus we can specify some prior parameters. However, in this case, we will use the default value.</p><p>Lastly, the static regression component. By default, the bsts model we create already account for static regression, and as such, we only need to specify its prior. We can split this into two parts, the ‘Spike’ and the ‘Slab’. We shall specify three important prior parameters, namely expected R-squared (how well the predictors explain our response DTA), the prior degree of freedom (related to precision), and expected model size (how many of our predictors are likely to be included in the model).</p><p>The expected model size M is related to the π parameter, which is the probability that a predictor is included in the model. Higher value increases a possibility of a more complex model. Thus, if we wish to include as many predictors as possible, we shall increase M. Remember that M &lt; J (number of predictors available).</p><p>The slab is a bit more complicated as it deals with the distribution of regression coefficient β. Each β is distributed normally, initially with zero mean and a certain variance. Since we’re dealing with many β’s, we assume that the coefficients follow a multivariate normal. There are several estimate to the covariance matrix, but the authors of this package uses a slightly modified Zellner’s g-prior to account for collinearity. The detail is fascinating, but in short, we only need to determine the expected R-squared and prior degree of freedom.</p><p>Again, we don’t have much information for this prior. However, we can try simple methods such as linear regression to obtain a reasonable prior estimates.</p><pre>summary(lm(DTU~., data = data))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*_zJoSM-sFIRfhU1UvDdRhg.jpeg" /><figcaption>A linear model to help specify prior for static regression</figcaption></figure><p>A linear model is not suitable for time series data since it assumes independency, however, it is still quite useful for this instance. We see a very high R-squared of 99%, with two parameters (DAU and Email CTR) being significant (or almost). Thus, we shall use expected model size of 2, expected R-squared of 90% (being a bit conservative here), and prior degree of freedom of 25 as this is a quite informative prior.</p><p>Putting it all together, we have the following state specification and priors. As a note, to specify a prior to the static regression, we also need to pass the predictor as a matrix, with the additional column of 1’s to act as intercepts. Again, we only pass the pre-intervention data as the argument which ends at index 218.</p><pre>ss = list()<br><br># Local Linear Trend<br>ss = AddLocalLinearTrend(ss, y = data$DTU, level.sigma.prior = SdPrior(sigma.guess = sd_dtu, sample.size = 0.01))<br><br># Seasonality<br>ss = AddSeasonal(ss, y = data$DTU, nseasons = 50, season.duration = 1)<br><br># Static Regression, we only specify the prior<br>reg_prior = SpikeSlabPrior(x = cbind(1, as.matrix(data[1:218, -1])), <br>                           y = as.matrix(data[1:218, 1]), <br>                           expected.r2 = 0.9, <br>                           prior.df = 25,<br>                           expected.model.size = 2)</pre><h3>Model Fitting</h3><p>We now begin the model fitting. The arguments we must pass is the model formula, the state specification, number of iterations, and prior for the static regression.</p><pre>bsts_model = bsts(DTU~., data = data, <br>                  state.specification = ss,<br>                  niter = niter,<br>                  prior = reg_prior)</pre><p>The fitting process took almost 1 minute on a Ryzen 7 4800U CPU. Before we begin with the Causal Impact analysis, we could also see the summary of our bsts model.</p><pre># See each predictor&#39;s probability of being included in the model<br>PlotBstsCoefficients(bsts_model)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*bj040YTfka13Ct87snYmBw.png" /><figcaption>Predictors inclusion probability</figcaption></figure><p>We observe that the DAU has a very high probability of being included in the model, with the rest having very little contribution. This suggest that the model size is expected to be 1 for most of the time, with DAU having the ability to explain the changes in DTU quite well.</p><pre># See the contribution of each state components<br>PlotBstsComponents(bsts_model, same.scale = F)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*KIOQ2yaQTHqxYurF5H1xWg.png" /><figcaption>State component contributions</figcaption></figure><p>The plot above shows the contribution of each state component (trend level, seasonal, and regression), also note that each have a different scale. The regression component contributes the most at predicting DTU, with the trend correcting for the existing negative trend, and the seasonal accounting for the presumed seasonality.</p><h3>Causal Impact Analysis</h3><p>Finally, we run the Causal Impact analysis, passing the fitted bsts model and the post intervention response we kept earlier.</p><pre>result = CausalImpact(bsts.model = bsts_model, <br>                      post.period.response = post_period_dtu)<br>summary(result)<br>plot(result)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*mj9aaA5FGZiZnltlbbBeGg.jpeg" /><figcaption>The posterior inference summary of Causal Impact</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*X6osc0AVCRWY7sc-LZ1fCg.jpeg" /><figcaption>Top panel: the original (solid black) vs predicted counterfactual (dotted blue), Middle panel: the pointwise impact distribution, Bottom panel: the cumulative impact distribution</figcaption></figure><p>The actual DTU for the post-intervention period is expected to be around 3607, meaning that the daily transacting user is around 3607 every day. This is considerably higher than the predicted counterfactual (i.e DTU when we didn’t have app changes) which is around 3460 per day with a quite narrow credible interval of [3364, 3559]. The actual DTU lies outside this interval, suggesting a quite significant uplift in DTU.</p><p>We also observe the cumulative DTU to be 155114, compared to the predicted 148773. This means that we have gained about 6341 transacting user compared to if we didn’t run the app change. In terms of relative effect, we have gained a lift of 4.3% in DTU, with a 99.5% probability of a true causal effect. This suggests that a visual change in the checkout page did help increase our transacting user. This is also not just a novelty effect since from the pointwise plot, we see that the effect stays throughout the entire post-intervention period.</p><h3>Epilogue</h3><p>And… that’s it! In practice, you may wish to try many different state specification, just remember that a more complex model may require more MCMC iterations. Also, it is not wise to ‘tune’ the prior parameters since this is against the Bayesian principle. We want our analysis to be data driven, so if we don’t have any prior information, we should leave the posterior to be dominated by the likelihood. This is also quite tricky, we may have information about the data in the past, but don’t really know how to incorporate this as a prior.</p><p>What do you think about this? Any suggestions and/or discussions are always appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b5cb714a41" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>