【问题标题】:ValueError: Unable to coerce to Series, length must be 1: given 506ValueError:无法强制转换为系列,长度必须为 1:给定 506
【发布时间】:2020-12-14 21:38:30
【问题描述】:

我正在尝试通过梯度下降应用简单线性回归 但我被困在这里

我收到一个错误 ValueError

ValueError:无法强制转换为 Series,长度必须为 1:给出 506 谁能帮我看看这段代码出了什么问题

X_train_std:X 的标准值,X.shape = (506, 13) X 有 int 值 y.shape = (506,1)

class LinearRegressionGD(object):
    def __init__(self, eta = 0.001, n_iter = 20):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X_train_std, y):
        self.w_ = np.zeros(1+X_train_std.shape[1])
        self.cost = []

        for i in range(self.n_iter):
            output = self.net_input(X_train_std)
            errors = (y - output)
            self.w_[1:] += self.eta * X_train_std.T.dot(errors)
            self.w_[0] += self.eta * errors.sum()
            cost = (errors**2).sum() /2.0
            self.cost_.append(cost)
        return self

    def net_input(self,X_train_std):
        return np.dot(X_train_std, self.w_[1:]) + self.w_[0]
    
    def predict(self, X_train_std):
        return self.net_input(X_train_std)


lr = LinearRegressionGD()
lr.fit(X_train_std, y)



---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    
    <ipython-input-24-29cc349fb131> in <module>()
          1 lr = LinearRegressionGD()
    ----> 2 lr.fit(X_train_std, y)
    
    3 frames
    
    /usr/local/lib/python3.6/dist-packages/pandas/core/ops/__init__.py in to_series(right)
        637             if len(left.columns) != len(right):
        638                 raise ValueError(
    --> 639                     msg.format(req_len=len(left.columns), given_len=len(right))
        640                 )
        641             right = left._constructor_sliced(right, index=left.columns)

【问题讨论】:

  • 试试y = y.squeeze()
  • 这不起作用,但感谢您的建议

标签: python pandas machine-learning gradient-descent


【解决方案1】:

output 是一维的,而y 是二维的。这就是为什么你必须重塑output。

output = self.net_input(X_train_std).reshape(-1, 1)

我也没有与你的权重更新一致。如果您将其替换为

self.w_[1:] += self.eta * np.sum(errors * X_train_std, axis=0)

并且可能调整学习率它应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2020-03-08
    • 2021-05-18
    • 2021-04-22
    • 2019-09-03
    • 2022-01-24
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多