Friday, 13 July 2018

Single Layer Perceptron Algorithm in Python

Training Code:

# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 22:10:42 2018

@author: Jubayer Hasan
"""

import numpy as np
print('No. of bits:')
n=int(input())
a=np.zeros((1000,11))
m=2**n
for i in range(0,m):
    t=i
    j=0
    while t!=0:
        remainder = t % 2
        a[i][j]=int(remainder)
        if i<m//2:
            a[i][10]=int(0)
        else:
            a[i][10]=int(1)
        t = t // 2
        j+=1
w=np.random.random(n)
theFile=open("Threshlod.txt","r") 
for val in theFile.read().split():
    th=val
th=float(th)
i=0
t1=m//2
eta=0.45
while i<m:
    #print(w)
    sum=0.0
    for j in range(0,n):
        sum+=(w[j]*a[i][j])
    if sum>=th:
        op=1
    else:
        op=0
    for j in range(0,n):
        w[j]+=((a[i][10]-op)*(eta*a[i][j]))
    if a[i][10]!=op:
        i=0
    else:
        i+=1
f = open('Weights.txt','w')
for i in range(0,n):
     f.write("%f\n" % w[i])
f.close()
f = open('Bits.txt','w')
for i in range(0,1):
     f.write("%d\n" % n)
f.close()
print(w)

Testing Code:

# -*- coding: utf-8 -*-
"""
Created on Wed Jun 20 21:19:30 2018

@author: Jubayer Hasan
"""

import numpy as np
w=[]
print('Enter no of test cases:')
test=int(input())
f = open('Threshlod.txt','r')
for val in f.read().split():
    th=val
th=float(th)
f = open('Bits.txt','r')
for val in f.read().split():
    n=val
n=int(n)
f = open('Weights.txt','r')
for val in f.read().split():
    x=val
    x=float(val)
    w.append(x)
print('Enter numbrs with ',n,' bits.')
for i in range(0,test):
    sum=0.0
    j=0
    inp=int(input())
    for k in range(0,n):
        remainder = inp % 2
        sum+=(w[j]*remainder)
        inp = inp // 2
        j+=1
    print(sum)
    if sum<th:
        print('Class 0.')
    else:
        print('Class 1.')