0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

単純パーセプトロンの重みを数式で追いかける

Last updated at Posted at 2023-11-02

イメージ
image.png

コード

from sympy import *
import sympy
import sys

# 特徴量の数(変数の命名規則のため最大9までを想定)
xDimension = 2

# サンプル数
xSampleSize = 2

# 注: updateNumber - 1 < xSampleSizeの必要あり
updateNumber = 2

xList = []
for i in range(xSampleSize + 1):
  
  #"xList[0]の各要素は使わない"
  xList.append([])
  for j in range(1, xDimension + 1):

     xList[i].append(sympy.var("x" + str(i) + str(j)))

# print(xList)

x = []
for i in range(xSampleSize + 1):

  x.append(sympy.Matrix(xList[i]))

# print(x)

yList = []
for i in range(xSampleSize + 2):

  # yList[0]は使わない
  yList.append(sympy.var("y" + str(i)))

# print(yList)

eta = sympy.var("eta")

wList = []
# 重みを0で初期化するか
zeroFlag = int(sys.argv[1])
for i in range(1, xDimension + 1):
   
   if zeroFlag == 1:
      wList.append(0)
   else:
      wList.append(sympy.var("w0" + str(i)))

# print(wList)

w = sympy.Matrix(wList)
# print(w)

# 重みを0で初期化(w.subs([(w01, 0), (w02, 0)])の書き方だとエラーが出てしまうので、代わりにzeroFlagで対応)

print("------------------------------------------------------w0")
pprint(w)
for i in range(1, updateNumber + 1):
  
   try:
   
      # ヘヴィサイドの階段関数を利用 https://docs.sympy.org/latest/modules/functions/special.html
      # pprintによる出力はθであることに注意
      y_hat = 2 * (sympy.Heaviside(sympy.expand((w.transpose() * x[i])[0, 0]), 1) - 0.5)
      print("---------------------------------------------------yhat{}".format(i))
      pprint(y_hat)

   except IndexError as e: 
      
      print('IndexError updateNumber - 1 < xSampleSizeを満たしてません プログラムを終了します')
      sys.exit()

   wDelta = eta * (yList[i] - y_hat) * x[i]
   print("-------------------------------------------------wDelta{}".format(i))
   pprint(wDelta)

   w = w + wDelta
   print("------------------------------------------------------w{}".format(i))
   pprint(w)

実行(ターミナル: コマンドライン引数で1を指定すると重みベクトルを0で初期化)

python .\Perceptron.py 1

実行結果
image.png

参考
https://datascience.stackexchange.com/questions/26134/initialize-perceptron-weights-with-zero/27305#27305

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?