Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wannaphong/e265b8d01e4ed7fe1e3aa6481adeb1a6 to your computer and use it in GitHub Desktop.
Save wannaphong/e265b8d01e4ed7fe1e3aa6481adeb1a6 to your computer and use it in GitHub Desktop.
ทำนายจำนวนประชากรของไทยด้วย Scikit-learn ใน Python https://python3.wannaphong.com/2017/05/thailand-population-scikit-learn-python.html
# ทำนายจำนวนประชากรของไทยด้วย Scikit-learn ใน Python
# เขียนโดย นาย วรรณพงษ์ ภัททิยไพบูลย์
# https://python3.wannaphong.com
# อ่านได้ที่ https://python3.wannaphong.com/2017/05/thailand-population-scikit-learn-python.html
# 14 พ.ค. 2560
'''
สร้าง dataset ข้อมูลประชากร
'''
thai = [20986780,
21550597,
22137264,
22748483,
23385735,
24050281,
24743156,
25465173,
26216916,
26998728,
27810693,
28652623,
29524040,
30424188,
31352065,
32305948,
33283799,
34284723,
35308874,
36355859,
37424920,
38513462,
39613484,
40712254,
41797247,
42860900,
43901427,
44919725,
45917876,
46898818,
47861110,
48801246,
49724352,
50644272,
51573453,
52522122,
53491139,
54456532,
55373178,
56197809,
56904398,
57493773,
57999623,
58480220,
58994428,
59572522,
60211946,
60897956,
61612466,
62333640,
63054248,
63775922,
64476962,
65110888,
65634248,
66019230,
66264029,
66403414,
66500726,
66620111,
66797491,
67033544,
67307776,
67588701,
67842669,
68098436,
68355167]
'''
นำเข้า dataset เข้ามาใช้ใน Scikit-learn
'''
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
time = pd.date_range('1951', periods=67, freq='A') # สร้างช่วงเวลา โดยจะเรียงจาก ปี 1951 ไล่ต่อมา 67 ปี
listtime=time.tolist()
plt.plot(listtime,thai)
plt.show() # แสดงข้อมูลประชากรจากอดีต
data=pd.DataFrame({'date':time.values,'value':thai})
data['date_ordinal'] = data['date'].apply(lambda x: x.toordinal()) # แปลงวันเดือนปีไปเป็น proleptic Gregorian ordinal
'''
เลือก Algorithms ที่ใช้งาน
'''
from sklearn.linear_model import LinearRegression
model = LinearRegression()
'''
ลงมือทำการทำนายข้อมูลประชากรด้วย Scikit-learn ในภาษา Python
'''
X = data[['date_ordinal']]
y =np.asarray(data['value'])
model.fit(X, y) # ทำการวิเคราะห์
# ทำนายแบบปีเดียว
time2 = pd.date_range('2018', periods=1)
x= time2.tolist()
x=x[0].toordinal()
print(model.predict(x))
# ทำนายแบบแสดงกราฟ 10 ปี
time2 = pd.date_range('2018', periods=10, freq='A')
data2=pd.DataFrame({'date':time2.values})
data2['date_ordinal'] = data2['date'].apply(lambda x: x.toordinal())
x= data2[['date_ordinal']]
aa=pd.DataFrame({'date':time2,'value':model.predict(x)})
plt.plot(listtime+time2.tolist(),thai+list(model.predict(x))) # หากเติม a1 กับ thai จะแสดงปีทั้งหมดรวมถึงที่ทำนาย
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment