lighting
lighting

Reputation: 400

Solving equation with for loops python

I have arrays like this:

x = np.array([-1,-1,-1,1,-1,-1])

weight = np.array([[0.5,-0.5,0.5,-0.5,0.5,-0.5],
                   [-0.5,0.5,-0.5,0.5,-0.5,0.5],
                   [0.5,0.5,0.5,0.5,0.5,0.5]]) 
print(weight.shape)

bias=np.array([2, 2, 2])
print(bias)
weight = np.transpose(weight)
weight

You can run the above code which results to arrays bias and weight_ham and x:

bias = [2 2 2]

weight = array([[ 0.5, -0.5,  0.5],
                [-0.5,  0.5,  0.5],
                [ 0.5, -0.5,  0.5],
                [-0.5,  0.5,  0.5],
                [ 0.5, -0.5,  0.5],
                [-0.5,  0.5,  0.5]])
x = array([-1, -1, -1,  1, -1, -1])

Now i want to calculate this equation:

enter image description here

the y_in array should be like this:

y_in = np.zeros((1, len(bias)))

What i don't understand is how can i compute that equation with for loop since i'm not really familiar with how should i write for loops. if you didn't understand the equation you can see this example below:

enter image description here

Upvotes: 0

Views: 556

Answers (2)

Pygirl
Pygirl

Reputation: 13349

Posting answer for your screenshot problem. You can use the same code for your original problem:

x = np.array([1,1,-1,-1])

weight = np.array([[0.5,-0.5,-0.5,-0.5],
                   [-0.5,-0.5,-0.5,0.5],
                   ]) 

bias=np.array([2, 2])
weight = np.transpose(weight)

One Liner:

np.add(bias, np.dot(weight.T, x))

Using Loop:

y_arr = []
for j in range(weight.shape[1]):
    y = (bias[j] + np.dot(weight[:,j].T, x))
    y_arr.append(y)
y_arr = np.array(y_arr)

y_arr:

array([3., 1.])

Upvotes: 1

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

I don't understand why you are required to use loops when you are already working with numpy, however the correct way would be:

>>> np.add(bias, np.dot(x[None, :], weight)).flatten()
array([1., 3., 0.])

But if you want loops:

y = []
for index_1, b in enumerate(bias):
    sum_ = b
    for index_2, val in enumerate(x):
        sum_ += x[index_2] * weight[index_2, index_1]
    y.append(sum_)

>>> y
[1.0, 3.0, 0.0]

# OR

>>> [b + sum(x_val * w for x_val, w in zip(x, weight[:,i])) for i, b in enumerate(bias)]
[1.0, 3.0, 0.0]

Upvotes: 1

Related Questions