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

PyTorch实现岭回归遇矩阵形状不匹配错误,求解决方案

解决PyTorch岭回归中矩阵形状不匹配的问题

错误根源

你遇到的mat1 and mat2 shapes cannot be multiplied (1000x10 and 1x1)错误,核心原因是自定义线性层的输入输出维度定义错误:

  • 输入数据X_t的形状是(1000, 10)(1000个样本,每个样本包含10个特征),但你定义的nn.Linear(1, 1)强制要求输入为1维特征,导致矩阵乘法时维度完全不匹配。
  • 修改theta_true的形状无法解决该问题,因为错误出在模型结构,而非真实参数的定义。

修正步骤

1. 修正线性层维度

将MyLinear类中的线性层改为输入10个特征、输出1个值(回归任务的单输出特性),同时把输入维度作为参数传入,保证代码灵活性:

class MyLinear(nn.Module):
    def __init__(self, input_dim): 
        super(MyLinear, self).__init__()
        self.linear = nn.Linear(input_dim, 1)  # 输入维度对应样本特征数,输出维度为1
    def forward(self, x): 
        out = self.linear(x)
        return out

实例化模型时传入特征数p:

model = MyLinear(p)

2. 其他细节确认

  • 你的y和y_t形状为(1000,1),修正后的模型输出y_pred形状也会是(1000,1),与真实标签维度匹配,MSE损失可正常计算。
  • L2_norm函数无需修改,线性层的weight参数会自动变为(1,10),平方和计算逻辑完全正确。

修正后的完整代码

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

n = 1000
p = 10

mean = np.zeros((p))
val = 0.8
cov = np.ones((p,p))*val
cov = cov + np.eye(p)*(1-val)

np.random.seed(10)
X = np.random.multivariate_normal(mean, cov, n)
theta_true = np.concatenate((np.ones((5,1)), np.zeros((5,1))),axis=0)

delta=0.5
Sigma = np.eye(n,n,k=-1)*0.4 + np.eye(n,n)*1 + np.eye(n,n,k=1)*0.4
mean = np.zeros(n)
e = np.random.multivariate_normal(mean, Sigma, 1)

y=X@theta_true + delta*e.T

import torch
X_t = torch.from_numpy(X).float()
y_t = torch.from_numpy(y).float()
Sigma_t = torch.from_numpy(Sigma).float()

import torch.nn as nn
import torch.nn.functional as F

class MyLinear(nn.Module):
    def __init__(self, input_dim): 
        super(MyLinear, self).__init__()
        self.linear = nn.Linear(input_dim, 1)  
    def forward(self, x): 
        out = self.linear(x)
        return out

def L2_norm(model):
    return torch.sum(list(model.parameters())[0]**2)    

def L1_norm(model):
    return torch.sum(torch.abs(list(model.parameters())[0]))

def ridge_loss(y_pred, y_true, model, lambda_):
    mse = F.mse_loss(y_pred, y_true)
    regularization = lambda_ * L2_norm(model)
    return mse + regularization

import matplotlib.pyplot as plt

model = MyLinear(p)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

lambda_ = 0.1
num_epochs = 1000
loss_values = []

for epoch in range(num_epochs):
    optimizer.zero_grad()
    y_pred = model(X_t)
    loss = ridge_loss(y_pred, y_t, model, lambda_)
    loss_values.append(loss.item())
    loss.backward()
    optimizer.step()

plt.plot(loss_values)
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.title('Ridge Regression Loss over Iterations')
plt.show()

运行效果

修正后代码可正常执行,损失曲线会随迭代次数逐步下降并趋于平稳,符合岭回归的训练预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:40:21