TypeError:只有长度为1的数组可以转换为Python标量点积 [英] TypeError: only length-1 arrays can be converted to Python scalars Dot Product

查看:286
本文介绍了TypeError:只有长度为1的数组可以转换为Python标量点积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为我的最后一年的项目编写此算法.调试了一些,但是坚持了下来.尝试更改float方法,但没有真正改变.

Writing this algorithm for my final year project. Debugged a few, but stuck on this. Tried changing the float method but nothing really changed.

----> 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)

推荐答案

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

x is a numpy array, which Python's builtin float function can't handle. Try:

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

这篇关于TypeError:只有长度为1的数组可以转换为Python标量点积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆