【问题标题】:Python gradient-descent multi-regression - cost increases to infinityPython梯度下降多重回归 - 成本增加到无穷大
【发布时间】:2018-09-13 09:56:45
【问题描述】:

为我最后一年的项目编写这个算法。使用梯度下降来找到最小值,但代价却是无穷大。

我已经检查了 gradientDescent 功能。我相信这是正确的。

我正在导入的 csv 及其格式导致了一些错误。 CSV 中的数据格式如下。

'|' 之前的每个四边形是一行。

前 3 列是自变量 x。 第 4 列依赖于 y。

600 20 0.5 0.63 | 600 20 1 1.5 | 800 20 0.5 0.9

import numpy as np
import random
import pandas as pd

def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.transpose()
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y
        # avg cost per example (the 2 in 2*m doesn't really matter here.
        # But to be consistent with the gradient, I include it)
        cost = np.sum(loss ** 2) / (2 * m)
        print("Iteration %d | Cost: %f" % (i, cost))
        # avg gradient per example
        gradient = np.dot(xTrans, loss) / m
        # update
        theta = theta - alpha * gradient
    return theta

df = pd.read_csv(r'C:\Users\WELCOME\Desktop\FinalYearPaper\ConferencePaper\NewTrain.csv', 'rU', delimiter=",",header=None)

x = df.loc[:,'0':'2'].as_matrix()
y = df[3].as_matrix()

print(x)
print(y)

m, n = np.shape(x)
numIterations= 100
alpha = 0.001
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)

【问题讨论】:

  • 为什么将分隔符设置为, 而不是|
  • 它可能是分隔符,数据被空格分隔。
  • @Brayden 我相信这就是导入 csv 的方式。让我知道你的想法?
  • @forayer 我已经提到了 { delimiter=",",header=None }。你觉得别处吗?
  • @forayer 猜这些 cmets 被愚蠢的指南禁用了

标签: python pandas numpy machine-learning gradient-descent


【解决方案1】:

正如 cmets 中提到的,问题出在您读取 csv 的那一行。您正在设置delimiter=",",这意味着python 期望数据中的每一列都用逗号分隔。但是,在您的数据中,列显然是用空格分隔的。

只需用

替换该行
df = pd.read_csv(r'C:\Users\WELCOME\Desktop\FinalYearPaper\ConferencePaper\NewTrain.csv', 'rU', delimiter=" ",header=None)

【讨论】:

  • 改变它,我得到另外几个错误,包括 in () 21 22 x = df.loc[:,'0':'2' ].as_matrix() ---> 23 y = df[3].as_matrix() 24 25 打印(x)
  • 能否请您完整地粘贴错误信息?就像现在一样,它只是指出错误在哪里,而不是它是什么。此外,创建一个 csv 文件,其中仅包含您作为示例放置的三行,并尝试将其作为输入运行程序。
  • 现在运行出现上述错误。但是新的出现了。 [链接]stackoverflow.com/questions/49658448/…
  • 那么如果它解决了您的问题,请您接受答案吗?这是 StackExchange 网站内部的标准程序:它表彰社区中最有帮助的成员,并帮助访问者浏览答案。
  • 是的,我接受了你的回答。感谢您的帮助。但我真的坚持这一点。如果你能请帮忙。 stackoverflow.com/questions/49658448/…
猜你喜欢
  • 1970-01-01
  • 2017-02-07
  • 2020-02-23
  • 2018-12-22
  • 2021-02-20
  • 1970-01-01
  • 2021-06-23
  • 1970-01-01
  • 2018-10-25
相关资源
最近更新 更多