【问题标题】:TypeError: only length-1 arrays can be converted to Python scalars Dot ProductTypeError:只有长度为 1 的数组可以转换为 Python 标量点积
【发布时间】: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)

【问题讨论】:

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


【解决方案1】:

x 是一个 numpy 数组,Python 的内置 float 函数无法处理。试试:

hypothesis = np.dot(x.astype(float), theta)

【讨论】:

  • 感谢您的帮助。但是又出现了一个。 x = [['600,20,0.5,0.63'] ['600,20,1,1.5'] ['600,20,1.5,1.95'].....] 你能帮我吗?
  • ValueError: 无法将字符串转换为浮点数:'1000,40,1.5,2.67'
  • 哦,现在我看到x 包含 rows 字符串格式的数字。您可能必须在对 read_csv 的调用中指定每列的数据类型,以确保它们被导入为数字,而不是字符串。
猜你喜欢
  • 2014-09-27
  • 2013-03-15
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多