Created
July 13, 2020 12:39
-
-
Save kotoripiyopiyo/b12c191a4d09649f726b045bafbf8a81 to your computer and use it in GitHub Desktop.
[Pythonで機械学習]日本の人口推移の予測というのをやってみた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#必要なライブラリのインポート | |
import pandas as pd | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from sklearn.linear_model import LinearRegression | |
%matplotlib inline | |
#ファイル読み込み | |
df = pd.read_csv("downloaded_japan_population_utf8.csv") | |
#ベースとなるデータ作成 | |
df_year = pd.pivot_table(df, index="集計年", values="総人口(人)", aggfunc=sum) | |
# 1960年から2018年までの東京都の総人口数データを機械学習にかける。 | |
# ある年の総人口数を説明変数X、その翌年の総人口数を目的変数yに設定する | |
# (Xとyの両方とも、縦59行×横1列のndarrayで作成する) | |
X = np.empty((59, 1), dtype=np.uint32) | |
y = np.empty((59, 1), dtype=np.uint32) | |
#配列に人口を入れていく | |
for i in range(59): | |
X[i, 0] = df_year.iloc[i, 0] | |
y[i, 0] = df_year.iloc[i+1, 0] | |
#1960年から2012年までを訓練データ | |
#2013年から2018年までをテストデータとして分割する | |
X_train = X[:53] | |
X_test = X[53:] | |
y_train = y[:53] | |
y_test = y[53:] | |
#線形回帰モデルの作成と学習の実行 | |
model = LinearRegression() | |
model.fit(X_train, y_train) | |
#テストデータで「翌年の総人口」予測の実施 | |
y_pred = model.predict(X_test) | |
#予測値が実数値のため、整数値に変換 | |
y_pred = y_pred.astype(np.uint32) | |
#正解値とグラフで比較するため | |
#実数値と予測値の連結させた配列を作成 | |
y_pred_gr = np.concatenate([y_train, y_pred]) | |
#正解値と予測値のグラフ表示 | |
plt.plot(range(59), y_pred_gr, label="Predicted", color="red") | |
plt.plot(range(59), y, label="Actual", color="blue") | |
plt.xlabel("Years") | |
plt.ylabel("Popuration") | |
plt.title("Japan's population") | |
plt.grid(True) | |
plt.legend(loc = "upper left") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment