【发布时间】:2018-09-14 10:54:53
【问题描述】:
为我最后一年的项目编写这个算法。调试了一些,但坚持这一点。尝试更改 float 方法,但没有真正改变。
----> 8 hypothesis = np.dot(float(x), theta)
TypeError: only length-1 arrays can be converted to Python scalars
完整代码 -
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)
【问题讨论】:
-
您应该提供一个您尝试加载的 csv 文件的示例。我可以使用您在stackoverflow.com/questions/49640823/… 中发布的示例运行您的代码,没有问题(但结果是无穷大)。此外,您可能希望将
.as_matrix()替换为.values,如pandas.pydata.org/pandas-docs/stable/generated/… 中所述 -
是的,正如你所说,它正在运行。但是无限不是我们想要的......
-
但是您的问题是关于 TypeError...
-
是的,但是您在stackoverflow.com/questions/49640823/… 上的回答也没有运行
标签: python pandas numpy machine-learning gradient-descent