開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
はじめての機械学習 (小高知宏(著)、オーム社)の第2章(パラメーター調整による学習)、2.2(パラメーター調整による時系列データの学習)、2.2.2(時系列データの変動傾向の学習)、機械学習プログラムをC言語ではなくPythonで取り組んでみる。
コード
Python 3
sample_data.py
#!/usr/bin/env python3
import random
with open('sample_data.txt', 'w') as f:
for _ in range(25):
print(15 + random.random(), file=f)
ml1.py
#!/usr/bin/env python3
import sys
from typing import Union
last1 = ''
last2 = ''
last3 = ''
kb = {f'{i}{j}{k}': 0
for i in '+-'
for j in '+-'
for k in '+-'}
def learning(last1: str, last2: str, last3: str) -> None:
if last1 != '' and last2 != '' and last3 != '':
kb[f'{last1}{last2}{last3}'] += 1
def predication(last1: str, last2: str, last3: str) -> None:
if last1 == '' or last2 == '':
print('データ不足')
elif kb[f'{last1}{last2}+'] >= kb[f'{last1}{last2}-']:
print('+')
else:
print('-')
for line in sys.stdin:
pm = line.strip()
if pm in ['+', '-']:
last3 = last2
last2 = last1
last1 = pm
else:
print(f'無効な入力: {pm}')
break
learning(last1, last2, last3)
predication(last1, last2, last3)
print('学習結果')
for k, v in kb.items():
print(f'{k}: {v}')
入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal、Jupyter(IPython))
$ ./sample_data.py $ cat sample_data.txt 15.403276380639113 15.480095489860913 15.657186724719718 15.218552004527233 15.23506391765869 15.11552784587029 15.090900085916758 15.331499245208228 15.235475060757516 15.600910225201774 15.919085816718162 15.22643657925234 15.728078822760192 15.877755900796462 15.090088226905245 15.184713621911973 15.064473587832868 15.71182779504552 15.702352209069705 15.749378900691404 15.113322840276908 15.156068823237481 15.543606574552758 15.364495306008578 15.428508507808928 $ ./updown.py < sample_data.txt > sample_pm.txt $ cat sample_pm.txt + + - + - - + - + + - + + - + - + - + - + + - + $ ./ml1.py < sample_pm.txt データ不足 + + + + + + - + - + + - + + + + - + - + - - + 学習結果 +++: 0 ++-: 3 +-+: 8 +--: 1 -++: 4 -+-: 5 --+: 1 ---: 0 $
0 コメント:
コメントを投稿