LoginSignup
0
1

データセットを使ってみる

Last updated at Posted at 2024-05-20

はじめに

bdrccです。
データ分析に関心がある、職業訓練生です。
Pythonに関する記事(備忘録?)、初めてあげてみます。

背景

GW明けにPython3エンジニア認定データ分析試験を受験し、合格しました。
その後、何かを分析してみたいとデータを探し、下記記事・サイトを発見しました。

その中で、UC Irvine Machine Learning Repository に遭遇。

復習しながら、使ってみます。

目的

  1. UC Irvine Machine Learning Repository 内のデータセットの使い方を知る
  2. Pythonの分析(特に、ランダムフォレスト)を復習する

環境

言語

     Python 3.10.6

モジュール 各種

     jupyterlab 3.4.3
     numpy 1.24.4
     pandas 1.4.2
     matplotlib 3.5.2
     scikit-learn 1.4.1.post1

開発環境

     MacOS

データセットを確認する

まずは、Pythonを起動。
復習を兼ねて、仮想環境を使用します。

$ python3 -m venv env #最後は仮想環境名
$ source env/bin/activate

さて、uciのサイトを確認。データセット(記事投稿時点665件)のうち、209件がpythonで使用できるらしい。ということで、定番のIrisデータを見てみます。

スクリーンショット 2024-05-17 21.18.21.png

ucimlrepoをインストールすれば使用できるようなので、pip installしてimport

from ucimlrepo import fetch_ucirepo 
  
# 使用するデータセットをidで決定
iris = fetch_ucirepo(id=53) 
  
X = iris.data.features 
y = iris.data.targets 

得られたデータは辞書型になっていて、その中にデータがあります。
サイト通りに実行すると、PandasのDataFrameが得られました。

分類

参考文献を参考に、今回は教師あり学習のランダムフォレストを行います。
ただし、このまま分析に入ると、下記の警告文が出ます。

/~/sklearn/base.py:1474: DataConversionWarning: 
A column-vector y was passed when a 1d array was expected. 
Please change the shape of y to (n_samples,), for example using ravel().
  return fit_method(estimator, *args, **kwargs)

そのため、カテゴリ変数のエンコーディングを行ってから、分析。

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y2 = le.fit_transform(y.loc[:,'class'])
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
X_train, X_test, y_train, y_test = train_test_split(X, y2, test_size=0.3, random_state=123)
forest = RandomForestClassifier(n_estimators=100, random_state=123)
forest.fit(X_train,y_train)
y_pred = forest.predict(X_test)
y_pred

結果はこちら

スクリーンショット 2024-05-20 21.45.12.png

混同行列も見てみます。

print(classification_report(y_test, y_pred))

スクリーンショット 2024-05-20 21.46.38.png

さすがIrisデータといったところ、Setosaデータが通常あり得ない値を叩き出している・・・。

終わりに

かなりの頻度でデータセットが追加されており、おすすめの分析手法まで書かれていました。
勉強用には持ってこいな気がします。
欠損値処理も復習しつつ、他のデータセットでも試していきます。

足りない等お気付きの点ありましたら、教えてくださると助かります。
最後まで見ていただきありがとうございました。

参考文献

0
1
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
1