ここでは、「ディープラーニングAIはどのように学習し、推論しているのか」の「3章 ディープラーニングの基礎となる仕組み」のP30にある表 3-2-01「過去5日間の最高気温とビールの販売数」のデータをExcelに入力して、そこから 図 3-2-01 (P30) や図 3-2-02 (P31) を描くPythonのプログラムを作成する。
まず、表 3-2-01 をExcelに入力したものを図1に示す。
| 図1.過去5日間の最高気温とビールの販売数 |
次に、リスト1に必要なパッケージのインストールと読み込みを行うコードを示す。
!pip install japanize-matplotlib import pandas as pd import matplotlib.pyplot as plt import japanize_matplotlib
リスト1.必要なパッケージのインストールと読み込み
図1に示したExcelファイルを読み込んで、散布図を描くプログラムをリスト2に示す。
path = '/content/drive/MyDrive/Colab Notebooks/表3-2-01.xlsx'
df = pd.read_excel(path)
x = df[['最高気温']].values # must be a 2D array
y = df['販売数'].values # must be a 1D array
plt.plot(x[:,0], y, 'o') # x: 1st column should be selected
plt.xlim(25, 37)
plt.ylim(100, 240)
plt.xlabel('最高気温')
plt.ylabel('販売数')
リスト2.Excelの読み込みと散布図描画
図2にリスト2で描画した散布図を示す。これがテキストP30の 図 3-2-01 である。
![]() |
| 図2.散布図 |
次に、Excelから読み込んだデータを線形回帰分析をして回帰直線を描くプログラムをリスト3に示す。
# 単回帰
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x, y)
plt.plot(x[:,0], y, 'o') # x: 1st column should be selected
plt.plot(x[:,0], model.predict(x), linestyle="solid")
plt.xlim(25, 37)
plt.ylim(100, 240)
plt.xlabel('最高気温')
plt.ylabel('販売数')
print('モデル関数の回帰変数 w1: %.3f' %model.coef_)
print('モデル関数の切片 w2: %.3f' %model.intercept_)
print('y= %.3fx + %.3f' % (model.coef_ , model.intercept_))
print('決定係数 R^2: ', model.score(x, y))
リスト3.単回帰分析
図3にリスト3で描画した単回帰直線を加えた散布図を示す。これがテキストP31の 図 3-2-02 である。なお、線形回帰分析には機械学習ライブラリ scikit-learn の LinearRegression を利用している。
![]() |
| 図3.単回帰直線 |
モデル関数の回帰変数 w1: 4.096 モデル関数の切片 w2: 62.693 y= 4.096x + 62.693 決定係数 R^2: 0.6769502489415324


0 件のコメント:
コメントを投稿