简体   繁体   English

错误:mat1 和 mat2 形状不能相乘(1000x10 和 1x1)

[英]Error: mat1 and mat2 shapes cannot be multiplied (1000x10 and 1x1)

I am trying to implement Ridge Regression in pytorch, defining the loss function and plotting said function over different iterations.我正在尝试在 pytorch 中实现岭回归,定义损失 function 并在不同的迭代中绘制 function。 The only issue is, I keep getting an error code: mat1 and mat2 shapes cannot be multiplied (1000x10 and 1x1).唯一的问题是,我不断收到错误代码:mat1 和 mat2 形状无法相乘(1000x10 和 1x1)。 I would like to convert the second matrix to a 1x10 in order to complete the code but I can't seem to get it to work.我想将第二个矩阵转换为 1x10 以完成代码,但我似乎无法让它工作。

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): 
        super(MyLinear, self).__init__()
        self.linear = nn.Linear(1, 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()
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()

I tried changing the theta_true definition to transform the matrix but the same error occurred.我尝试更改 theta_true 定义以转换矩阵,但发生了同样的错误。

theta_true = np.concatenate((np.ones((5,1)), np.zeros((5,1)))).reshape(10, 1)

Your Linear layer in MyLinear (line 37) is what is causing the issue. MyLinear 中的线性层(第 37 行)是导致问题的原因。

self.linear = nn.Linear(1, 1)

means 1 input channel, one output channel, but x, as you have it here has shape (1000, 10), meaning it has 10 channels.表示 1 个输入通道,一个 output 通道,但是 x,因为你在这里有它的形状 (1000, 10),这意味着它有 10 个通道。 So you will need to change that line to所以你需要将该行更改为

self.linear = nn.Linear(10, 1)

that will do the trick, here is the image I get with that change:这样就可以了,这是我通过更改获得的图像:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RuntimeError:mat1 和 mat2 形状不能相乘(1x20 和 1x1) - RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x20 and 1x1) 如何解决 NeuroDiffEq 中的错误“mat1 和 mat2 形状不能相乘(1000x1 和 3x512)”? - How to resolve the error 'mat1 and mat2 shapes cannot be multiplied (1000x1 and 3x512)' in NeuroDiffEq? RuntimeError:mat1 和 mat2 形状不能相乘(951x10 和 951x4) - RuntimeError: mat1 and mat2 shapes cannot be multiplied (951x10 and 951x4) RuntimeError:mat1 和 mat2 形状不能相乘(2x720 和 784x10) - RuntimeError: mat1 and mat2 shapes cannot be multiplied (2x720 and 784x10) Pytorch RuntimeError: mat1 和 mat2 形状不能相乘(32x246016 和 3136x1000) - Pytorch RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x246016 and 3136x1000) Pytorch 上的 1D CNN:mat1 和 mat2 形状不能相乘(10x3 和 10x2) - 1D CNN on Pytorch: mat1 and mat2 shapes cannot be multiplied (10x3 and 10x2) mat1 和 mat2 形状不能相乘 - mat1 and mat2 shapes cannot be multiplied 运行时错误:mat1 和 mat2 形状不能在 pytorch 中相乘 - Runtime Error: mat1 and mat2 shapes cannot be multiplied in pytorch 运行时错误:mat1 和 mat2 形状不能相乘(5376x28 和 784x512) - RuntimeError: mat1 and mat2 shapes cannot be multiplied (5376x28 and 784x512) PyTorch 自动编码器:mat1 和 mat2 形状不能相乘(1x512 和 12x64) - PyTorch AutoEncoder : mat1 and mat2 shapes cannot be multiplied (1x512 and 12x64)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM