-1

I'm a beginner to machine learning and have been trying to implement gradient descent to try and optimize the weights of my model. I am trying to develop the model from scratch and I have reviewed a lot of code online but my implementation still doesnt seem to decrease the loss of the model with the loss oscillating between 0.2 and 0.1. The loss function I used is L = (y - hypothesis)**2. Any help would be appreciated

    for z in range(self.iterations):
        print(z)
        cost = 0
        for x in range(self.batch_size):
            derivatives = np.zeros(self.num_weights)
            ran = self.random_row()
            row = self.X.iloc[[ran]]
            cost += self.loss(row, self.y[ran])
            error = self.y[ran] - self.predict(row)
            for i in range(len(derivatives)):
                derivatives[i] = derivatives[i] + (error * (row.iloc[0,i] * -2))
                derivatives[i] = derivatives[i] * learning_rate
                self.weights[i] = self.weights[i] - derivatives[i]

2 Answers2

1

This is the incorrect loss function. For binary/two-class logistic regression you should use the cost function of

binary logistic regression cost equation

where h is the hypothesis.

You can find an intuition for the cost function and an explaination of why it is what it is in the 'Cost function intuition' section of this article here.

With this cost function, you will need to use a different gradient: gradient equation.

Note that here different notation is used and the cost function is represented by J(θ) where θ is a vector of weights for this model. A derivation of this equation can be found here.

In general, here are some helpful articles about implementing logistic regression:

  1. https://towardsdatascience.com/building-a-logistic-regression-in-python-301d27367c24
  2. https://www.baeldung.com/cs/gradient-descent-logistic-regression
  3. https://machinelearningmastery.com/implement-logistic-regression-stochastic-gradient-descent-scratch-python/
  4. https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac
  5. https://dhirajkumarblog.medium.com/logistic-regression-in-python-from-scratch-5b901d72d68e
Dharman
  • 30,962
  • 25
  • 85
  • 135
E. Turok
  • 106
  • 1
  • 7
0

iam beginner in learning machine learning. I usually use sklearn library in python. you can put the code at head line from sklearn.linear model import SGDlassifier then the SGDClassifer fit with your data by using SGDClassifier.fit(X_train,y_train)