import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as pltimport plotly.express as pxsns.set_theme(style="whitegrid", context="notebook")# Plotly is used only as a convenient source of Gapminder data.df = px.data.gapminder()print(df.shape)print(df.head())
(1704, 8)
country continent year lifeExp pop gdpPercap iso_alpha \
0 Afghanistan Asia 1952 28.801 8425333 779.445314 AFG
1 Afghanistan Asia 1957 30.332 9240934 820.853030 AFG
2 Afghanistan Asia 1962 31.997 10267083 853.100710 AFG
3 Afghanistan Asia 1967 34.020 11537966 836.197138 AFG
4 Afghanistan Asia 1972 36.088 13079460 739.981106 AFG
iso_num
0 4
1 4
2 4
3 4
4 4
sns.histplot(data=df2007, x="lifeExp", bins=15, color="steelblue")plt.xlabel("Life expectancy (years)")plt.title("Distribution of Life Expectancy, 2007")plt.show()
sns.violinplot(data=df2007, x="continent", y="lifeExp", inner="quart", color="steelblue")plt.title("Distribution of Life Expectancy by Continent, 2007")plt.show()
Bar Plot สามารถแสดงอายุคาดเฉลี่ยของประเทศโดยเฉลี่ยในแต่ละทวีป
คลิกเพื่อดูโค้ดไพธอน
sns.barplot(data=df2007, x="continent", y="lifeExp", errorbar=None, color="steelblue")plt.ylabel("Mean country-level life expectancy (years)")plt.title("Unweighted Mean Life Expectancy by Continent, 2007")plt.show()
ตัวอย่างการตีความที่เหมาะสม: “ในข้อมูลตัวอย่างปี 2007 ประเทศที่มี GDP ต่อหัวสูงกว่ามีแนวโน้มมีอายุคาดเฉลี่ยสูงกว่า” ต่างจาก “การเพิ่ม GDP ต่อหัวทำให้อายุคาดเฉลี่ยสูงขึ้น” ซึ่งเป็นข้อความเชิงสาเหตุและต้องใช้การออกแบบการศึกษาต่างออกไป
16.12 Scatter Plot: รายได้กับอายุคาดเฉลี่ย
คลิกเพื่อดูโค้ดไพธอน
sns.scatterplot(data=df2007, x="gdpPercap", y="lifeExp", color="steelblue")plt.xlabel("GDP per capita")plt.ylabel("Life expectancy (years)")plt.title("GDP per Capita and Life Expectancy, 2007")plt.show()
เนื่องจาก GDP ต่อหัวมักมีการแจกแจงเบ้ขวา การใช้แกนนอนแบบลอการิทึมจึงช่วยให้เห็นรูปแบบความสัมพันธ์ระหว่างประเทศได้ชัดเจนขึ้น
คลิกเพื่อดูโค้ดไพธอน
sns.scatterplot( data=df2007, x="gdpPercap", y="lifeExp", hue="continent", alpha=0.8)plt.xscale("log")plt.xlabel("GDP per capita (log scale)")plt.title("Income and Life Expectancy by Continent, 2007")plt.show()
regional = ( df.groupby(["continent", "year"], as_index=False) .agg(mean_lifeExp=("lifeExp", "mean")))sns.lineplot(data=regional, x="year", y="mean_lifeExp", hue="continent", marker="o")plt.ylabel("Mean country-level life expectancy (years)")plt.title("Unweighted Country Means by Continent")plt.show()
การแสดง Confidence Band จาก regplot() จึงเป็นเพียงภาพความไม่แน่นอนของเส้นที่ประมาณ และไม่สามารถใช้แทนช่วงพยากรณ์รายประเทศ (prediction interval) ได้
16.18 Regression Line และ Confidence Band
Regression Plot เพิ่มเส้นถดถอยที่ประมาณจากข้อมูลเข้ากับ Scatter Plot ในกรณีนี้ การแปลง GDP ต่อหัวด้วยลอการิทึมช่วยแสดงความสัมพันธ์ที่อาจไม่เป็นเส้นตรงเมื่อพิจารณาในหน่วย GDP เดิม
ใช้ลอการิทึมธรรมชาติจาก NumPy ดังนี้
คลิกเพื่อดูโค้ดไพธอน
import numpy as npdf2007["log_gdpPercap"] = np.log(df2007["gdpPercap"])sns.regplot(data=df2007, x="log_gdpPercap", y="lifeExp", color="steelblue")plt.xlabel("Log GDP per capita")plt.ylabel("Life expectancy (years)")plt.title("Life Expectancy and Log Income, 2007")plt.show()
comparison_corr = pd.DataFrame({"variable": ["GDP per capita", "Log GDP per capita"],"pearson_r": [ df2007["lifeExp"].corr(df2007["gdpPercap"]), df2007["lifeExp"].corr(df2007["log_gdpPercap"]), ],})print(comparison_corr.round(3))
variable pearson_r
0 GDP per capita 0.679
1 Log GDP per capita 0.809
GDP ต่อหัวมักมีการกระจายเบ้ขวา การแสดงแกน x แบบลอการิทึมช่วยให้อ่านความแตกต่างระหว่างประเทศได้ดีขึ้น แต่การเปลี่ยนสเกลการแสดงผลไม่เท่ากับการแปลงตัวแปรในแบบจำลอง
คลิกเพื่อดูโค้ดไพธอน
fig, axes = plt.subplots(1, 2, figsize=(12, 4))for ax in axes: sns.scatterplot(data=df2007, x="gdpPercap", y="lifeExp", color="teal", ax=ax) ax.set_ylim(35, 90)axes[0].set_title("Linear GDP Axis")axes[1].set_xscale("log")axes[1].set_title("Log GDP Axis")plt.tight_layout()plt.show()
หากต้องการประมาณเส้นถดถอยเชิงเส้นกับ log(GDP per capita) ให้สร้างคอลัมน์ที่แปลงแล้วและนำไปใช้ใน regplot() โดยตรง (ไม่ใช่เพียงเปลี่ยนแกนกราฟ)
คลิกเพื่อดูโค้ดไพธอน
reg_data = df2007.assign(log_gdp=np.log(df2007["gdpPercap"]))fig, ax = plt.subplots(figsize=(8, 5))sns.regplot(data=reg_data, x="log_gdp", y="lifeExp", scatter_kws={"alpha": 0.55, "s": 30}, line_kws={"color": "darkred", "linewidth": 2}, ax=ax)ax.set_xlabel("Natural log of GDP per capita")ax.set_ylabel("Life expectancy (years)")ax.set_title("Regression on Log GDP per Capita")plt.show()
Agrawal, Rakesh, และ Ramakrishnan Srikant. 1994. “Fast Algorithms for Mining Association Rules in Large Databases”. Proceedings of the 20th International Conference on Very Large Data Bases, 487–99. https://www.vldb.org/dblp/db/conf/vldb/vldb94-487.html.
Bergmeir, Christoph, Rob J. Hyndman, และ Bonsoo Koo. 2018. “A Note on the Validity of Cross-Validation for Evaluating Autoregressive Time Series Prediction”. Computational Statistics & Data Analysis 120: 70–83. https://doi.org/10.1016/j.csda.2017.11.003.
Bishop, Christopher M. 2006. Pattern Recognition and Machine Learning. Springer.
Breunig, Markus M., Hans-Peter Kriegel, Raymond T. Ng, และ Jörg Sander. 2000. “LOF: Identifying Density-Based Local Outliers”. ACM SIGMOD Record 29 (2): 93–104. https://doi.org/10.1145/335191.335388.
Chen, Tianqi, และ Carlos Guestrin. 2016. “XGBoost: A Scalable Tree Boosting System”. Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 785–94. https://doi.org/10.1145/2939672.2939785.
Chernozhukov, Victor, Denis Chetverikov, Mert Demirer, และคณะ. 2018. “Double/Debiased Machine Learning for Treatment and Structural Parameters”. The Econometrics Journal 21 (1): C1–68. https://doi.org/10.1111/ectj.12097.
Cleveland, William S., และ Robert McGill. 1984. “Graphical Perception: Theory, Experimentation, and Application to the Development of Graphical Methods”. Journal of the American Statistical Association 79 (387): 531–54. https://doi.org/10.1080/01621459.1984.10478080.
Croushore, Dean. 2011. “Frontiers of Real-Time Data Analysis”. Journal of Economic Literature 49 (1): 72–100. https://doi.org/10.1257/jel.49.1.72.
Davies, David L., และ Donald W. Bouldin. 1979. “A Cluster Separation Measure”. IEEE Transactions on Pattern Analysis and Machine Intelligence PAMI-1 (2): 224–27. https://doi.org/10.1109/TPAMI.1979.4766909.
Diebold, Francis X., และ Roberto S. Mariano. 1995. “Comparing Predictive Accuracy”. Journal of Business & Economic Statistics 13 (3): 253–63. https://doi.org/10.1080/07350015.1995.10524599.
Efron, Bradley, และ Robert J. Tibshirani. 1993. An Introduction to the Bootstrap. Chapman; Hall.
Ester, Martin, Hans-Peter Kriegel, Jörg Sander, และ Xiaowei Xu. 1996. “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise”. Proceedings of the Second International Conference on Knowledge Discovery and Data Mining, 226–31. https://www.aaai.org/Papers/KDD/1996/KDD96-037.pdf.
Friedman, Jerome H. 2001. “Greedy Function Approximation: A Gradient Boosting Machine”. The Annals of Statistics 29 (5): 1189–232. https://doi.org/10.1214/aos/1013203451.
Giannone, Domenico, Lucrezia Reichlin, และ David Small. 2008. “Nowcasting: The Real-Time Informational Content of Macroeconomic Data”. Journal of Monetary Economics 55 (4): 665–76. https://doi.org/10.1016/j.jmoneco.2008.05.010.
Goldstein, Alex, Adam Kapelner, Justin Bleich, และ Emil Pitkin. 2015. “Peeking Inside the Black Box: Visualizing Statistical Learning with Plots of Individual Conditional Expectation”. Journal of Computational and Graphical Statistics 24 (1): 44–65. https://doi.org/10.1080/10618600.2014.907095.
Hahsler, Michael, Bettina Grün, และ Kurt Hornik. 2005. “arules – A Computational Environment for Mining Association Rules and Frequent Item Sets”. Journal of Statistical Software 14 (15): 1–25. https://doi.org/10.18637/jss.v014.i15.
Hastie, Trevor, Robert Tibshirani, และ Jerome Friedman. 2009. The Elements of Statistical Learning: Data Mining, Inference, and Prediction. 2 พิมพ์ครั้งที่. Springer. https://doi.org/10.1007/978-0-387-84858-7.
Hoerl, Arthur E., และ Robert W. Kennard. 1970. “Ridge Regression: Biased Estimation for Nonorthogonal Problems”. Technometrics 12 (1): 55–67. https://doi.org/10.1080/00401706.1970.10488634.
Hyndman, Rob J., และ George Athanasopoulos. 2021. Forecasting: Principles and Practice. 3 พิมพ์ครั้งที่. OTexts. https://otexts.com/fpp3/.
Hyndman, Rob J., และ Anne B. Koehler. 2006. “Another look at measures of forecast accuracy”. International Journal of Forecasting 22 (4): 679–88. https://doi.org/10.1016/j.ijforecast.2006.03.001.
James, Gareth, Daniela Witten, Trevor Hastie, Robert Tibshirani, และ Jonathan Taylor. 2023. An Introduction to Statistical Learning: With Applications in Python. Springer. https://doi.org/10.1007/978-3-031-38747-0.
Jolliffe, Ian T., และ Jorge Cadima. 2016. “Principal Component Analysis: A Review and Recent Developments”. Philosophical Transactions of the Royal Society A: Mathematical, Physical and Engineering Sciences 374 (2065): 20150202. https://doi.org/10.1098/rsta.2015.0202.
Kapoor, Sayash, และ Arvind Narayanan. 2023. “Leakage and the Reproducibility Crisis in Machine-Learning-Based Science”. Patterns 4 (9): 100804. https://doi.org/10.1016/j.patter.2023.100804.
Kuhn, Max, และ Kjell Johnson. 2019. Feature Engineering and Selection: A Practical Approach for Predictive Models. CRC Press. https://bookdown.org/max/FES/.
Little, Roderick J. A., และ Donald B. Rubin. 2019. Statistical Analysis with Missing Data. 3 พิมพ์ครั้งที่. Wiley. https://doi.org/10.1002/9781119482260.
Liu, Fei Tony, Kai Ming Ting, และ Zhi-Hua Zhou. 2008. “Isolation Forest”. Proceedings of the Eighth IEEE International Conference on Data Mining, 413–22. https://doi.org/10.1109/ICDM.2008.17.
McInnes, Leland, John Healy, และ James Melville. 2018. UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction. https://doi.org/10.48550/arXiv.1802.03426.
Mitchell, Margaret, Simone Wu, Andrew Zaldivar, และคณะ. 2019. “Model Cards for Model Reporting”. Proceedings of the Conference on Fairness, Accountability, and Transparency, 220–29. https://doi.org/10.1145/3287560.3287596.
Mullainathan, Sendhil, และ Jann Spiess. 2017. “Machine Learning: An Applied Econometric Approach”. Journal of Economic Perspectives 31 (2): 87–106. https://doi.org/10.1257/jep.31.2.87.
Niculescu-Mizil, Alexandru, และ Rich Caruana. 2005. “Predicting Good Probabilities with Supervised Learning”. Proceedings of the 22nd International Conference on Machine Learning, 625–32. https://doi.org/10.1145/1102351.1102430.
OECD, European Union, และ European Commission, Joint Research Centre. 2008. Handbook on Constructing Composite Indicators: Methodology and User Guide. OECD Publishing. https://doi.org/10.1787/9789264043466-en.
Pedregosa, Fabian, Gael Varoquaux, Alexandre Gramfort, และคณะ. 2011. “Scikit-learn: Machine Learning in Python”. Journal of Machine Learning Research 12: 2825–30. https://jmlr.org/papers/v12/pedregosa11a.html.
Roberts, David R., Volker Bahn, Simone Ciuti, และคณะ. 2017. “Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure”. Ecography 40 (8): 913–29. https://doi.org/10.1111/ecog.02881.
Rosenbaum, Paul R., และ Donald B. Rubin. 1983. “The Central Role of the Propensity Score in Observational Studies for Causal Effects”. Biometrika 70 (1): 41–55. https://doi.org/10.1093/biomet/70.1.41.
Rousseeuw, Peter J. 1987. “Silhouettes: A Graphical Aid to the Interpretation and Validation of Cluster Analysis”. Journal of Computational and Applied Mathematics 20: 53–65. https://doi.org/10.1016/0377-0427(87)90125-7.
Sandve, Geir Kjetil, Anton Nekrutenko, James Taylor, และ Eivind Hovig. 2013. “Ten Simple Rules for Reproducible Computational Research”. PLOS Computational Biology 9 (10): e1003285. https://doi.org/10.1371/journal.pcbi.1003285.
Stock, James H., และ Mark W. Watson. 2002. “Macroeconomic Forecasting Using Diffusion Indexes”. Journal of Business & Economic Statistics 20 (2): 147–62. https://doi.org/10.1198/073500102317351921.
Tibshirani, Robert. 1996. “Regression Shrinkage and Selection via the Lasso”. Journal of the Royal Statistical Society: Series B (Methodological) 58 (1): 267–88. https://doi.org/10.1111/j.2517-6161.1996.tb02080.x.
Varian, Hal R. 2014. “Big Data: New Tricks for Econometrics”. Journal of Economic Perspectives 28 (2): 3–28. https://doi.org/10.1257/jep.28.2.3.
Varma, Sudhir, และ Richard Simon. 2006. “Bias in error estimation when using cross-validation for model selection”. BMC Bioinformatics 7: 91. https://doi.org/10.1186/1471-2105-7-91.
Ward, Joe H. 1963. “Hierarchical Grouping to Optimize an Objective Function”. Journal of the American Statistical Association 58 (301): 236–44. https://doi.org/10.1080/01621459.1963.10500845.
Waskom, Michael L. 2021. “seaborn: Statistical Data Visualization”. Journal of Open Source Software 6 (60): 3021. https://doi.org/10.21105/joss.03021.
Wilkinson, Mark D. และคณะ. 2016. “The FAIR Guiding Principles for Scientific Data Management and Stewardship”. Scientific Data 3: 160018. https://doi.org/10.1038/sdata.2016.18.
Wilson, Greg, Jennifer Bryan, Karen Cranston, Justin Kitzes, Lex Nederbragt, และ Tracy K. Teal. 2017. “Good Enough Practices in Scientific Computing”. PLOS Computational Biology 13 (6): e1005510. https://doi.org/10.1371/journal.pcbi.1005510.
Zou, Hui, และ Trevor Hastie. 2005. “Regularization and Variable Selection via the Elastic Net”. Journal of the Royal Statistical Society: Series B (Statistical Methodology) 67 (2): 301–20. https://doi.org/10.1111/j.1467-9868.2005.00503.x.