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, 2019 in Machine Learning by Neel
3,066 views

1 answer to this question.

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, 2019 by Vaishu

Related Questions In Machine Learning

0 votes
1 answer
+1 vote
1 answer

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-8nhf9w2t/grpcio/

Hi@akhtar, You may get this error because of ...READ MORE

answered May 16, 2020 in Machine Learning by MD
• 95,460 points
32,772 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Markov chain using processing - Python

Try something like this @Gujjar HashMap<String, int> wordCount; int ...READ MORE

answered Aug 2, 2019 in Machine Learning by Ashish
917 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP