Sam Hammamy Sam Hammamy - 1 month ago 18
Python Question

Numpy syntax for linear equation

I'm new to numpy but not python. Have a question about the

numpy
way to do this, consider:

Edit : correcting the function**

def _my_function(weights, features, bias):
# the pure python way
value = 0.
for i in range(len(weights)):
value += (weights[i]*features[i])

return value+bias


What is the numpy way to do this?

Answer

Approach #1: Using dot-product with np.dot -

weights.dot(features) + bias*len(weights)

Approach #2: Bringing in np.einsum to perform the sum-reduction -

np.einsum('i,i->',weights,features) + bias*len(weights)

I would think approach #1 would be the better one.

Comments