Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

machine learning - Perceptron algorithm is not working as I desired

I recently tried implementing perceptron algorithm but I was not getting the desired output.
Here is the code:

import numpy as np
import pandas as pd

with open("D:/data.txt",'r') as data:  #importing the data
    column = data.read()
split = np.array(column.split('
'))

final =[]
for string in split:
    final.append(string.split(','))
df = pd.DataFrame(final,columns=['x','y','response'])
df['x'] = df['x'].astype(float)
df['y'] = df['y'].astype(float)
df['response'] = df['response'].astype(int)

X = np.array(df[['x','y']])
y = np.array(df['response'])

def perceptron_algorithm(x,y,learning_rate=0.01,num_epoch=25):
    np.random.seed(2)
    
    x_min, x_max = min(x.T[0]), max(x.T[0])
    y_min, y_max = min(x.T[1]), max(x.T[0])
    
    w = np.array(np.random.rand(2,1))
    b = np.random.rand(1)[0] + x_max
    
    print(w,b)
    
    for i in range(num_epoch):
        w,b = perceptronstep(x,y,w,b,learning_rate)
        print(w,b)
    return w,b

def perceptronstep(x,y,w,b,learning_rate):
    
    for i in range(len(x)):
        y_hat = prediction(x[i],w,b)
        
        if y_hat-y[i] == 1:
            for j in range(len(w)):
                w[j] += x[i][j]*learning_rate
            b += learning_rate
        elif y_hat-y[i] == -1:
            for j in range(len(w)):
                w[j] -= x[i][j]*learning_rate
            b -= learning_rate
    return w,b

def prediction(x,w,b):
    return step(np.matmul(x,w)+b)

def step(t):
    if t >=0:
        return 1
    else:
        return 0

w,b = perceptron_algorithm(X,y)

This is the resulting line:

scatter plot with the predicted line

This is how the data looks:

data

Is there something wrong with my code ?

Here is the link to the data file:

https://drive.google.com/drive/folders/1TSug9tE6bljyBFv-u3mIGWW6F_3ZY2oa?usp=sharing

Edit: I have added the initial part of the code so it will be clear what I am trying to do.
Edit 2: I have added the data file and the "import pandas as pd" line of code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...