Python returns an error when trying to multiply two numpy matrices of the appropriate size

my code is pretty simple, but when I try to multiply the 3x2 and 2x1 matrix, I get the following error (which does not make sense to me):

ValueError: operands could not be broadcast together with shapes (3,2) (2,1) 

In this program, the first thing I do is randomly generate two points in the domain [-1,1] x [-1,1] and determine the line by these points using the variables slopeand y_int. Then I create N random values ​​of the xform {x_0, x_1, x_2}, where x_0 is always 1, and x_1, x_2 are randomly generated numbers in the range [-1,1]. These N values ​​contain code x_matrixin code.

y_matrixis a classification of each of the values ​​x_1, ..., x_N. If x_1 is to the right of the random string indicated by slopeand y_int, then the value of y_1 is +1, otherwise -1.

Now that the x_matrixand tags have been specified y_matrix, I just want to multiply the pseudo-inverse value x_matrix( pinv_xin code) by y_matrix. Here an error occurs. I am at my end and I cannot come up with anything that could be wrong.

Any help is appreciated. Code below:

from numpy import *
import random

N = 2

# Determine target function f(x)                                                                                
x_1 = [random.uniform(-1,1),random.uniform(-1,1)]
x_2 = [random.uniform(-1,1),random.uniform(-1,1)]
slope = (x_1[1] - x_2[1]) / (x_1[0] - x_2[0])
y_int = x_1[1] - (slope * x_1[0])

# Construct training data.                                                                                       
x_matrix = array([1, random.uniform(-1,1), random.uniform(-1,1)])
x_on_line = (x_matrix[1] / slope) - (y_int / slope)
if x_matrix[1] >= x_on_line:
    y_matrix = array([1])
else:
    y_matrix = array([-1])

for i in range(N-1):
    x_val = array([1, random.uniform(-1,1), random.uniform(-1,1)])
    x_matrix = vstack((x_matrix, x_val))
    x_on_line = (x_val[1] / slope) - (y_int / slope)
    if x_val[1] >= x_on_line:
    y_matrix = vstack((y_matrix, array([1])))
    else:
        y_matrix = vstack((y_matrix, array([-1])))

pinv_x = linalg.pinv(x_matrix)
print y_matrix
print pinv_x
w =  pinv_x*y_matrix
+3
source share
1 answer

, . , dot(), *. . . * , , .

+5

All Articles