LoginSignup
0
0

More than 1 year has passed since last update.

Pythonでスクレイピング&機械学習(プロ野球データをもとにHR数を予測)

Last updated at Posted at 2022-02-01

はじめに

今回、スクレイピングをして得たデータから、機械学習を行いHR数の予測を行った。その手順をここに残しておく。

Target

スクレイピング&機械学習の初学者。私自身初心者であるので、今回のスクリプト等は平易になっている。参考にしていただけると幸いである。

概要

流れを時系列で確認する。

  1. webページから、プロ野球の5年分のデータをスクレイピングする。(今回は、プロ野球データFreak様のデータを使用した。)
  2. スクレイピングしたデータをCSVファイルに保存する。
  3. CSVファイルのデータを用い、HR数を予測する機械学習モデルを作る。

データをスクレイピングし、各年ごとにCSVファイルに出力

import pandas as pd

da = []

for n in range(21, 16, -1):
    if n == 21:
        url = "https://baseball-data.com//stats/hitter-all/tpa-3.html"
    else:
        url = f"https://baseball-data.com/{n}//stats/hitter-all/tpa-3.html"
    da = pd.read_html(url, header=1)[0]
    np = pd.DataFrame(da)
    np_h = np.drop("順位", axis=1)
    np_h.to_csv(f"npb_h{n}.csv", index=False)

print(np_h)

pandasを用いてスクレイピングする。ここでは21~17年までの打者成績を取得している。urlは21年度のみ少々違っている為、このような処理になった。

.dropを使い、順位のデータを落としている。あとで盗塁のデータ等も落とすので、ここで不必要なデータをすべて削除しておくべきだった。

データクレンジングを行う

import pandas as pd
import glob

csv_files = glob.glob('~/*.csv')
li = []
print(csv_files)
for f in csv_files:
    li.append(pd.read_csv(f))

print(li)
dd = pd.concat(li, ignore_index=True)
dd.to_csv("npb_h.csv", index=False)

各年のCSVファイルを一つに結合する。glob.globでディレクトリ内の.csvが付くファイルを取得している。

import pandas as pd

npb = pd.read_csv("npb_h.csv")

dr_npb = ["選手名", "チーム", "盗塁", "本塁打"]
npb_t = npb.drop(dr_npb, axis=1)
npb_hr = npb.loc[range(0, 289), "本塁打"]

npb_t.to_csv("npb_ht.csv", index=False)
npb_hr.to_csv("npb_htr.csv", index=False)

いらないデータを削除する。ここでは、選手名、チーム名、盗塁を落とし、目的変数である本塁打も落としている。そして、本塁打だけのデータを作成する。

機械学習を行う

from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
import pandas as pd

hr_features = pd.read_csv("npb_ht.csv")
hr_target = pd.read_csv("npb_htr.csv")

x_train, x_test, y_train, y_test = train_test_split(hr_features, hr_target, test_size =0.25, random_state=0)

Lasso = Lasso(alpha=0.1, random_state=0)
Lasso.fit(x_train, y_train)

target_Lasso = Lasso.predict(x_test)
print(np.round(target_Lasso))

このコードで行った。今回は練習がてら行ったので、特に何も考えずLassoを用いて学習した。

結果

HR数の多少は、ある程度は判断できたが、精度は低かった。また、ホームラン数が負になる等、明らかにおかしい値も出た。

おわりに

機械学習の練習を、プロ野球のデータを用いて行った。どのモデルがいいのか等、推敲はまだしていない。初学者がとりあえずプログラムを組むのに参考にしていただけると幸いである。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0