【问题标题】:TypeError: unsupported operand type(s) for -: 'float' and 'str'TypeError: 不支持的操作数类型 -: 'float' 和 'str'
【发布时间】:2021-04-13 22:08:09
【问题描述】:

我是 Python 的新手,我一直在坚持现在该做什么,因为我不断收到此错误。我正在尝试更改以下等式:

z = np.power(((float(X) * theta.T)-float(Y)), 2)

但我似乎无法让它工作。

我的代码:

# convert from data frames to numpy matrices
X = np.matrix(x.values)  
Y = np.matrix(y.values)  
theta = np.matrix(np.array([0,0]))
# cost functionstrong text
def computeCost(X, Y, theta):
    z = np.power(((X * theta.T)-Y), 2)
    return np.sum(z) / (2 * len(X))
print('computeCost(X, y, theta) = ' , computeCost(X, Y, theta))

矩阵充满了浮点数:

 X = [[ 1.      6.1101] [ 1.      5.5277] [ 1.      8.5186] ...

错误信息:

TypeError: unsupported operand type(s) for -: 'float' and 'str'

感谢我能得到的所有帮助。非常感谢

【问题讨论】:

  • 哪一行导致了这个错误?
  • 计算成本中的行 z = np.power(((X * theta.T)-Y), 2)
  • 您需要检查 X thetaY 的数据类型,其中一个似乎是 str 而您希望它们是 float
  • 认为你是对的 :)

标签: python numpy


【解决方案1】:

检查数据框的数据类型

df.info()

如果有 'object' 数据类型,那就是你的字符串

您可能希望数据框中的所有数据类型都是浮点数,您可以这样做

df.astype('float')

【讨论】:

    猜你喜欢
    • 2017-08-23
    • 2013-10-29
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    相关资源
    最近更新 更多