DAY 30
0

## [Day30]Preceptron實作(With Python)

``````import numpy as np
from math import exp,pow
``````

``````class preceptron():
def __init__(self):                    #初始參數
self.bias = 0                      #偏差
self.weights = np.array([])        #權重
# monitor
def show_weights(self):             #外部監控參數用
print(self.weights)
def show_bias(self):
print(self.bias)
# math function
def Active_value(self,data):        #計算激發強度(訊息*權重的加權合+偏差)
value = np.dot(self.weights,data)-self.bias
return value
def Sigmoid (self,x):               #激活函數
result = 1/(1+exp(-x))
return result
def Err (self,predict,label):       #誤差
return(label - predict)
def MSE (self,err):                 #均方誤差(Loss Function)
MSError = 0.5*pow(err,2)
return MSError
# Process control
def initalization(self,data,label,input_dim,lr):     #讀資料，完全初始化
self.weights = np.zeros(input_dim)
self.bias = np.random.rand(1)
self.data = data
self.label = label
self.lr = lr
self.input_dim = input_dim
def fit(self):                                       #開始訓練
totalLoss=0
for dat in range(data.shape[0]):
Act = self.Active_value(self.data[dat])
result = self.Sigmoid(Act)
Err = self.Err(result,self.label[dat])
Loss = self.MSE(Err)
totalLoss +=Loss                            #計算Loss

print("Activevalue =",Act)                  #印出來監控
print("result =",result)
print("Error = ",Err)
print("Loss =",Loss)
for weight in range(self.input_dim):
self.bias =self.bias-self.lr*(Err*result*(1-result))
print("==============================================")     #分隔線
``````

``````from sklearn import datasets
data,label = iris["data"][:100],iris["target"][:100]    #取前100
``````

``````model = preceptron()
``````

``````model.initalization(data = data,label = label,input_dim=4 ,lr = 0.1)
``````

``````model.fit()
``````

``````for i in range(100):
model.fit()
``````