Lear regression using python error - ValueError: operands could not be broadcast together with shapes (1,3) (1,2)

0 votes

Here is my attempt to perform linear regression utilizing just numpy and linear algebra :

def linear_function(w , x , b):
    return np.dot(w , x) + b

x = np.array([[1, 1,1],[0, 0,0]])
y = np.array([0,1])

w = np.random.uniform(-1,1,(1 , 3))

print(w)
learning_rate = .0001

xT = x.T
yT = y.T

for i in range(30000):

    h_of_x = linear_function(w , xT , 1)
    loss = h_of_x - yT

    if i % 10000 == 0:
        print(loss , w)
    w = w + np.multiply(-learning_rate , loss)

linear_function(w , x , 1)

This causes an error :

ValueError                                Traceback (most recent call last)
<ipython-input-137-130a39956c7f> in <module>()
     24     if i % 10000 == 0:
     25         print(loss , w)
---> 26     w = w + np.multiply(-learning_rate , loss)
     27 
     28 linear_function(w , x , 1)

ValueError: operands could not be broadcast together with shapes (1,3) (1,2)
May 24 in Machine Learning by Neel
27 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

Hey! Your array shapes seem inconsistent. Try something like this:

# input, augmented
x = np.array([[1, 1, 1], [0, 0, 0]])
x = np.column_stack((np.ones(len(x)), x))
# predictions
y = np.array([[0, 1]])   
# weights, augmented with bias
w = np.random.uniform(-1, 1, (1, 4))

learning_rate = .0001

loss_old = np.inf
for i in range(30000):  
    h_of_x = w.dot(x.T)
    loss = ((h_of_x - y) ** 2).sum()

    if abs(loss_old - loss) < 1e-5:
        break

    w = w - learning_rate * (h_of_x - y).dot(x)
    loss_old = loss
answered May 24 by Vaishu

Related Questions In Machine Learning

0 votes
1 answer

Example to run KNN algorithm using python

Have a look at this one: from sklearn.datasets ...READ MORE

answered May 8 in Machine Learning by Harvy
33 views
0 votes
1 answer
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
55 views
0 votes
1 answer

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.