開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
はじめての機械学習 (小高知宏(著)、オーム社)の第2章(パラメーター調整による学習)、2.1(パラメータ調整と学習)、2.1.1(学習データセットの機械学習とパラメタ調整)、2.1.2(パラメタ調整の実行例)をC言語ではなくPythonで取り組んでみる。
コード
Python 3
#!/usr/bin/env python3
import sys
import matplotlib.pyplot as plt
sigma_xi = 0
sigma_yi = 0
sigma_xiyi = 0
sigma_xi2 = 0
n = 0
xis = []
yis = []
for line in sys.stdin:
line = line.strip()
try:
xi, yi = [float(x) for x in line.split()]
except ValueError as err:
print(f"ValueError: {err} '{line}'", file=sys.stderr)
else:
xis.append(xi)
yis.append(yi)
sigma_xi += xi
sigma_yi += yi
sigma_xiyi += xi * yi
sigma_xi2 += xi ** 2
n += 1
if n >= 2:
a0 = (sigma_xi2 * sigma_yi - sigma_xiyi * sigma_xi) / \
(n * sigma_xi2 - sigma_xi ** 2)
a1 = (n * sigma_xiyi - sigma_xi * sigma_yi) / \
(n * sigma_xi2 - sigma_xi ** 2)
print(f'a0 = {a0}, a1 = {a1}')
plt.scatter(xis, yis, color='green')
xs = range(int(min(xis)), int(max(xis)) + 2)
plt.plot(xs, [a0 + a1 * x for x in xs], color='blue')
plt.legend([f'{a0} + {a1}x', 'input', ])
# plt.show()
plt.savefig('sample1.png')
else:
print('データ不足', file=sys.stderr)
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
C:\Users\...>type input1.txt 1 2.1 3 3.7 2.5 3.4 3.9 3.1 C:\Users\...>py sample1.py < input1.txt a0 = 2.0102941176470583, a1 = 0.4095022624434396 C:\Users\...>py sample1.py 1 2.1 3 ValueError: not enough values to unpack (expected 2, got 1) '3' 4 xyz ValueError: could not convert string to float: 'xyz' '4 xyz' データ不足 C:\Users\...>
0 コメント:
コメントを投稿