パーセプトロン Python コードの実装

目次

1. データセットの準備

1.1 パッケージのインポート

1.2 データの読み込み

1.3 生データの視覚化

 1.4 データセットとラベルの分割

2. パーセプトロンの実現

2.1 w、b、およびステップ サイズの初期化

2.2 意匠活性化機能

2.3 確率的勾配降下法

2.4 実装

 3. 検査


1. データセットの準備

        この記事では、sklearn の虹彩データを使用しています。

       sklearn.datasets.load_iris(*, return_X_y=False, as_frame=False)
       Iris データセットは、1936 年に Fisher によって収集された、一般的に使用される分類実験データセットです。アイリスは、アイリスの花のデータ セットとも呼ばれ、多変量解析用のデータ セットです。データ セットには 150 個のデータ サンプルが含まれ、3 つのカテゴリに分けられ、各カテゴリに 50 個のデータがあり、各データには 4 つの属性 (それぞれ、がく片の長さ、がく片の幅、花弁の長さ、花弁の幅) が含まれています。これらの 4 つの属性を使用して、3 種類のアヤメの花 (Setosa、Versicolour、Virginica) のどれに属するかを予測できます。
Iris には iris.data と iris.target の 2 つのプロパティがあります。データは行列で、各列はがく片または花びらの長さと幅を表し、合計 4 列、各列は測定されたアイリス植物、合計 150 レコードを表します。

1.1 パッケージのインポート

import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt

1.2 データの読み込み

iris = load_iris() を使用してデータをロードします
df['label'] = iris.target パーティション データのラベル
ここでは、がく片の長さ、がく片の幅、花弁の長さ、および花弁の幅のみを属性として取得します
df.columns = ['がく片の長さ'、'がく片の幅'、'花弁の長さ'、'花弁の幅'、'ラベル']
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
df.label.value_counts()

1.3 生データの視覚化

萼の長さと萼の幅によって可視化データを分け、0~49をクラス0、50~99をクラス1としています。

plt.scatter(df[:50]['sepal length'], df[:50]['sepal width'], label='0')
plt.scatter(df[50:100]['sepal length'], df[50:100]['sepal width'], label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')

 1.4 データセットとラベルの分割

        パーセプトロンは 2 つのカテゴリの分割であるため、今回は最初の 2 種類の虹彩がトレーニングと予測のために選択されます。つまり、最初の 100 データ (0 ~ 99) です。また、入力次元は 2 次元に制御されているため、0 列目と 1 列目の特徴が選択されます。最後の列はターゲットです。そして、パーセプトロンの原理に従って、バイナリ分類のために y 値が -1、1 に設定されます。

data = np.array(df.iloc[:100, [0, 1,-1]])
X, y = data[:, :-1], data[:, -1]
y = np.array([1 if i == 1 else -1 for i in y])

2. パーセプトロンの実現

2.1 w、b、およびステップ サイズの初期化

    def __init__(self):
        self.w = np.ones(len(data[0]) - 1, dtype=np.float32)
        self.b = 0
        self.l_rate = 0.1

2.2 意匠活性化機能

    def sign(self, x, w, b):
        y = np.dot(x, w) + b
        return y

2.3 確率的勾配降下法

    def fit(self, X_train, y_train):
        is_wrong = False
        while not is_wrong:
            wrong_count = 0
            for d in range(len(X_train)):
                X = X_train[d]
                y = y_train[d]
                if y * self.sign(X, self.w, self.b) <= 0:
                    self.w = self.w + self.l_rate * np.dot(y, X)
                    self.b = self.b + self.l_rate * y
                    wrong_count += 1
            if wrong_count == 0:
                is_wrong = True
        return 'Perceptron Model!'

2.4 実装

上記のクラスを実装して視覚的に表示する

バイナリ線形関数の場合

x_points = np.linspace(4, 7, 10) y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1] plt.plot(x_points, y_) その中:y_ = -
( perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]

y の値を求めるには、法線ベクトルと x と切片 b を知ることと理解できます。

perceptron = Model()
perceptron.fit(X, y)
x_points = np.linspace(4, 7, 10)
y_ = -(perceptron.w[0] * x_points + perceptron.b) / perceptron.w[1]
plt.plot(x_points, y_)
#
plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0')
plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()

 3. 検査

sklearn に付属のパーセプトロン関数を使用してテストする

from sklearn.linear_model import Perceptron

# In[13]:


clf =  Perceptron(fit_intercept=True, max_iter=1000, shuffle=True, eta0=0.1, tol=None)
clf.fit(X, y)

# In[14]:


# Weights assigned to the features.
print(clf.coef_)

# In[15]:


# 截距 Constants in decision function.
print(clf.intercept_)

# In[16]:


x_ponits = np.arange(4, 8)
y_ = -(clf.coef_[0][0] * x_ponits + clf.intercept_) / clf.coef_[0][1]
plt.plot(x_ponits, y_)

plt.plot(data[:50, 0], data[:50, 1], 'bo', color='blue', label='0')
plt.plot(data[50:100, 0], data[50:100, 1], 'bo', color='orange', label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()
plt.show()

Guess you like

Origin blog.csdn.net/maggieyiyi/article/details/125553011