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

手动实现Linear Regression与Gradient Descent时遇ValueError求助

问题原因

报错ValueError: not enough values to unpack (expected 2, got 1)出现在n_samples, n_features = X.shape,因为你提取的X是一维numpy数组(df['volume'].values返回形状为(n_samples,)的数组),此时X.shape仅返回一个维度值,无法解包成样本数和特征数两个变量。你的线性回归代码默认输入的特征矩阵是二维结构(每行对应一个样本,每列对应一个特征)。

修复步骤

  1. 将一维特征数组转为二维
    提取特征时,通过以下两种方式将一维数组转为二维:

    # 方式1:使用双层方括号提取列,直接得到二维数组
    X = df[['volume']].values
    # 方式2:对已有一维数组增加维度
    X = df['volume'].values.reshape(-1, 1)
    

    转换后X的形状变为(n_samples, 1),X.shape会返回两个值,解包操作即可正常执行。

  2. 纠正类中的属性拼写错误
    在fit方法的梯度更新部分,你错误地将self.weights(复数)写成了self.weight(单数),这会导致属性不存在的错误,修改为:

    self.weights = self.weights - self.lr * dw
    
  3. 修复梯度计算的维度不匹配问题
    原代码中dw = (1/n_samples) * np.dot(X, (y_pred - y))存在维度不匹配问题,需要将X转置后再进行点乘,确保计算出的梯度与权重形状一致:

    dw = (1/n_samples) * np.dot(X.T, (y_pred - y))
    

完整修复后的代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('/Users/MyName/Downloads/archive/prices.csv')
# 将X转为二维数组
X = df[['volume']].values
y = df['close'].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)

class Lin_Reg():
    def __init__(self, lr=0.01, n_iters=10000):
        self.lr = lr
        self.n_iters = n_iters
        self.weights = None
        self.bias = None
        
    def fit(self, X, y):
        n_samples, n_features = X.shape
        self.weights = np.zeros(n_features)
        self.bias = 0
        
        for _ in range(self.n_iters):
            y_pred = np.dot(X, self.weights) + self.bias

            dw = (1/n_samples) * np.dot(X.T, (y_pred - y))
            db = (1/n_samples) * np.sum(y_pred-y)

            self.weights = self.weights - self.lr * dw
            self.bias = self.bias - self.lr * db
    
    def predict(self, X):
        y_pred = np.dot(X, self.weights) + self.bias
        return y_pred

reg = Lin_Reg()
reg.fit(X_train, y_train)
predictions = reg.predict(X_test)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:13:27