3

I have the following code snippet:

def func1(self, X, y):
    #X.shape = (455,13)
    #y.shape = (455)

    num_examples, num_features = np.shape(X)
    self.weights = np.random.uniform(-1 / (2 * num_examples), 1 / (2 * num_examples), num_features)

    while condition:
        new_weights = np.zeros(num_features)
        K = (np.dot(X, self.weights) - y)

        for j in range(num_features):
            summ = 0

            for i in range(num_examples):
                summ += K[i] * X[i][j]

            new_weights[j] = self.weights[j] - ((self.alpha / num_examples) * summ)

        self.weights = new_weights

This code works too slow. Is there any optimization, which I can do?

8
  • What is condition? Commented May 3, 2015 at 14:21
  • @unutbu, count of iteration > 0. Commented May 3, 2015 at 14:22
  • 1
    So is the while-loop infinite? Commented May 3, 2015 at 14:24
  • @unutbu, no. I just remove counter from example. Commented May 3, 2015 at 14:24
  • 2
    Do you really want to reset summ=0 inside the for j loop? By doing so, you throw away all the work done by every iteration of the for j loop except the last iteration when j equals num_features-1. Commented May 3, 2015 at 14:30

2 Answers 2

4

You can efficiently use np.einsum(). See a testing version below:

def func2(X, y):
    num_examples, num_features = np.shape(X)
    weights = np.random.uniform(-1./(2*num_examples), 1./(2*num_examples), num_features)

    K = (np.dot(X, weights) - y)

    return weights - alpha/num_examples*np.einsum('i,ij->j', K, X)
Sign up to request clarification or add additional context in comments.

Comments

2

You can get new_weights directly using matrix-multiplication with np.dot like so -

new_weights = self.weights- ((self.alpha / num_examples) * np.dot(K[None],X))

2 Comments

thanks for the help! It seems that your code works correctly, but a bit slower than Saullo Castro.
@Denis Yeah, that einsum seems to be the best one for optimizing solutions!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.