【问题标题】:Python returning error when attempting to multiply two numpy matrices of appropriate dimension尝试将两个适当维度的numpy矩阵相乘时,Python返回错误
【发布时间】:2012-04-14 00:56:48
【问题描述】:

我的代码非常简单,但是当我尝试将 3x2 和 2x1 矩阵相乘时,出现以下错误(对我来说,这没有意义):

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

在这个程序中,我做的第一件事是在域[-1,1] x [-1,1]中随机生成两个点,并通过这些点定义一条线,使用变量slope和@ 987654323@。然后,我创建了 N 个随机 x 值,格式为 {x_0, x_1, x_2},其中 x_0 始终为 1,x_1,x_2 是 [-1,1] 范围内随机生成的数字。这 N 个值构成代码中的 x_matrix

y_matrix 是每个值 x_1、...、x_N 的分类。如果 x_1 在slopey_int 指定的随机行的右侧,则y_1 的值为+1,否则为-1。

现在,一旦指定了x_matrixy_matrix,我只想将x_matrix(代码中的pinv_x)的伪逆乘以y_matrix。这就是错误出现的地方。我无计可施,我想不出任何可能出错的地方。

非常感谢任何帮助。代码如下:

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

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您使用的是数组,而不是矩阵。要从数组中获取矩阵乘法,您需要使用dot() 函数,而不是*。见this page。当数据在数组中时,* 运算符是逐元素乘法,因此形状必须完全匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-27
      • 2021-05-25
      • 1970-01-01
      • 2018-04-08
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多