멀티미디어처리응용(퍼셉트론)

Seok·2022년 1월 24일
0

REPORT#멀티미디어처리응용

프로그램 구현

단층 퍼셉트론 기계학습 구현

<소스 코드>

def fn_step(x):
    if(x<=0):
        return 0
    return 1

class Perceptron:
    def __init__(self, w1, w2, b, activateFn):
        self.ws=[w1,w2]
        self.bias=b
        self.activateFn=activateFn

    def calculate(self, *xs):
        result=self.bias
        for x, w in zip(xs, self.ws):
            result+=x*w
        y=self.activateFn(result)
        return y

    def train(self, inputSet, labelSet, LT=0.05, e=0.01):
        for xs,t in zip(inputSet, labelSet):
            y=self.calculate(*xs) 
            if(abs(y-t)<=e):
                continue
            self.bias=self.bias+LT*(t-y)*1 #가중치 갱신
            for i, x in enumerate(xs):
                self.ws[i]=self.ws[i]+LT*(t-y)*x

    def showWeight(self):
        print("Bias : {:.03} ".format(self.bias))
        for i,w in enumerate(self.ws):
            print("Weight {} : {:.03}".format(i, w))
            


if __name__ == '__main__':
    x1=[0,0,1,1]
    x2=[0,1,0,1]
    y= [0,0,0,1]

    perc=Perceptron(0.1,0.2,-1,fn_step)
    #5회 학습
    for i in range(5):
        perc.train(zip(x1,x2),y,0.05)
        print("train {} result ".format(i+1))
        perc.showWeight()

    for i in range(4):
        print("입력값 : "+str(x1[i])+ ", "+str(x2[i])+" ",end='')
        out=perc.calculate(x1[i],x2[i])
        print("예측 : "+ str(out) + ", 정답 : "+ str(y[i]))

<실행 결과>

단층 퍼셉트론과 다층 퍼셉트론의 텐서플로우 구현

<단층 퍼셉트론 소스 코드>

import tensorflow as tf
import numpy as np

# AND
x_train = np.array([[0, 0],
            [0, 1],
            [1, 0],
            [1, 1]], dtype=np.float32)
y_train = np.array([[0],
            [0],
            [0],
            [1]], dtype=np.float32)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(1, input_dim = 2, activation='relu'))
sgd = tf.keras.optimizers.SGD(learning_rate=0.05)
model.compile(loss='mean_squared_error',optimizer=sgd)

model.fit(x_train, y_train, epochs=1000, verbose=0)
print(model.predict(x_train))

<작업화면>

<실행결과>

<다층 퍼셉트론 소스 코드>

import tensorflow as tf
import numpy as np

x_train = np.array([[0, 0],
            [0, 1],
            [1, 0],
            [1, 1]], dtype=np.float32)
y_train = np.array([[0],
            [1],
            [1],
            [0]], dtype=np.float32)
            
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(2, input_dim = 2, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='relu'))
sgd = tf.keras.optimizers.SGD(learning_rate=0.025)
model.compile(loss='mean_squared_error', optimizer=sgd)

model.fit(x_train, y_train, epochs=1000, batch_size=1, verbose=0)
print(model.predict(x_train))

<작업화면>

<실행결과>

profile
네이티브 앱개발에 관심많은 주니어 개발자

0개의 댓글