Sharki
Sharki

Reputation: 424

Python, how to avoid the loop using numpy

So I have two matrix, W and X.

print(W)
array([ 5.76951515, 19.        ])

print(X)
array([[ 1.,  5.],
       [ 1.,  6.],
       [ 1.,  7.],
       [ 1.,  8.],
       [ 1.,  9.],
       [ 1., 10.],
       [ 1., 11.],
       [ 1., 12.],
       [ 1., 13.],
       [ 1., 14.]])

and I'd like multiply both matrix W and X, varying the value of W[1] for each i iterations, like this.

for i in range(10):
  W[1] = i
  yP_ = W @ X.T
  ecm = np.mean((Y - yP_ ) ** 2)
  plt.plot(W[1], ecm, 'o')
plt.show()

is there any way to avoid that for?

Upvotes: 0

Views: 139

Answers (2)

yatu
yatu

Reputation: 88236

You can start by generating the modified W array, and then apply the matrix product just as you where:

N=10
W_ = np.c_[[W[0]]*N, np.arange(N)]
yP_ = [email protected]

Quick check:

yP_ = []
for i in range(N):
    W[1] = i
    yP_.append(W @ X.T)

np.allclose(np.array(yP_), [email protected])
# True

Upvotes: 1

stevemo
stevemo

Reputation: 1097

Try making W shape (10,2), and keeping the range 0-9 in the second column. Then the rows of the product W @ X.T are the iterations of your current for-loop.

W2 = np.full((10,2), W[0])
W2[:,1] = np.arange(10)
W2
# array([[5.76951515, 0.        ],
#        [5.76951515, 1.        ],
#          ...
#        [5.76951515, 9.        ]])

So you can do

ecm = np.mean((Y - W2 @ X.T)**2, axis=1)  # average across columns
plt.plot(W2[:,1], ecm, 'o')

Upvotes: 2

Related Questions