How to align dimensions to use np.dot() between two different matrices

Viewed 25

I'm trying to use the dot product in Numpy between two matrices with different dimensions. w is (1, 5) and X is (3, 5) I'm not sure which command I can use to change the dimensions as I am new to python. Thank you.

When I try running my function, it gives me an error saying:

ValueError: shapes (1,5) and (3,5) not aligned: 5 (dim 1) != 3 (dim 0)
from numpy.core.memmap import ndarray
def L(w, X, y):
    """
    Arguments:
    w -- vector of size n representing weights of input features n
    X -- matrix of size m x n represnting input data, m data sample with n features each 
    y -- vector of size m (true labels)
  
    Returns:
    loss -- the value of the loss function defined above
    """
    
    ### START CODE HERE ### (2-4 lines of code)
    #w needs to match X matrix
    # w = (1, 5)
    # x = (3, 5)
    yhat = np.dot(w, X)
    L1 = y - yhat
    loss = np.dot(L1, L1)

    
    ### END CODE HERE ###
    
    return loss

Here is the picture of directions: image of directions

1 Answers

The dot product of two vectors is the sum of the products of elements with regards to position. The first element of the first vector is multiplied by the first element of the second vector and so on. The sum of these products is the dot product which can be done with np.dot() function.

Since we multiply elements at the same positions, the two vectors must have same length in order to have a dot product.

import numpy as np 
a = np.array([[1,2],[3,4]]) 
b = np.array([[11,12],[13,14]]) 
np.dot(a,b)

It will produce the following output −

[[37  40] 
 [85  92]] 

Note that the dot product is calculated as −

[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]]
Related