You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整矩阵维度以使用np.dot()计算不同维度矩阵的点积

解决Numpy点积维度不匹配问题

报错原因

你遇到的ValueError: shapes (1,5) and (3,5) not aligned: 5 (dim 1) != 3 (dim 0),是因为Numpy的dot()函数要求第一个数组的最后一维长度必须等于第二个数组的倒数第二维长度。你的w维度为(1,5)、X维度为(3,5),5≠3,不符合运算要求。

操作说明(翻译自原图片)

我们定义损失函数为预测值与真实值差值的平方和:
$$ L(w) = \sum_{i=1}^m (y^{(i)} - \hat{y}{(i)})2 $$
其中 $\hat{y}^{(i)} = w^T x{(i)}$,$x{(i)}$ 表示矩阵X的第i行(即第i个样本),$w$ 为特征权重向量。

解决方案与修改代码

根据损失函数逻辑,我们需要让预测值yhat的维度和真实标签y(维度(m,))匹配,有两种可行的调整方式:

方式一:转置X矩阵

将X转置为(5,3),让w(1,5)和X.T(5,3)做点积,得到(1,3)的预测结果,再展平为(3,)和y维度一致:

import numpy as np
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 ###
    yhat = np.dot(w, X.T).flatten()
    L1 = y - yhat
    loss = np.dot(L1, L1)
    ### END CODE HERE ###
    
    return loss

方式二:调整w的维度

把w从(1,5)重塑为(5,1),让X(3,5)和w(5,1)做点积得到(3,1),再展平为(3,):

import numpy as np
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 ###
    yhat = np.dot(X, w.reshape(-1, 1)).flatten()
    L1 = y - yhat
    loss = np.dot(L1, L1)
    ### END CODE HERE ###
    
    return loss

注意:原代码缺少import numpy as np,必须补上才能正常运行。

内容的提问来源于stack exchange,提问作者Brian Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:45:41