Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Im implementing logistic regression ,but somehow this code not seems to be working..please help me.

This is the python code for logisticRegression using Preceptron Trick but not working.. im having doubt in finding coefficients..please check and correct the code.

 

 

class LogisticRegression:
    def __init__(self,learning_rate=0.01,epochs=1000):
        self.epochs=epochs
        self.learning_rate=learning_rate
        self.coef_=0
        self.intercept_=0
    
    def fit(self,x,y):
        x=x.copy()
        y=y.copy()
        import numpy as np
        x.insert(loc=0,column='ones',value=np.ones(x.shape[0]))
        w = np.ones(x.shape[1])
        for i in range(self.epochs):
            j=np.random.randint(0,x.shape[0])
            y_hat = self.step(np.dot(x.iloc[j,:], w))
            w=w+(y.iloc[j,]-y_hat)*x.iloc[j,:]
        
        self.coef_=-w[1:x.shape[1]]/w[x.shape[1]-1]
        self.intercept_ = -w[0]/w[x.shape[1]-1]
        return w[0],w[1:]
    def step(self,v):
        return 1 if v>0 else 0

    def predict(self, X_test):
        import numpy as np
        y_pred = np.dot(X_test,self.coef_) + self.intercept_
        return y_pred

 

 

 

0 2 256
2 REPLIES 2

Hi!

Welcome to Google Cloud Community!

To properly replicate your use case, can you show any error message you are having? And what is your expected output/behavior?

ankit869_0-1675486837145.pngankit869_1-1675486888852.png

Look at this r2_score is coming worst negetive.