【问题标题】:TypeError: unsupported operand type(s) for -: 'str' and 'float' when trying to loop over a function in Python类型错误:尝试循环 Python 中的函数时 - 的不支持的操作数类型:“str”和“float”
【发布时间】:2021-02-25 10:49:38
【问题描述】:

我正在尝试让内核估计器(如The Article 中给出的)预测给定向量的值,而不是单个值。代码如下:

from scipy.stats import norm
import numpy as np 
import pandas as pd
import matplotlib.pyplot as plt
import math

class GKR:
    def __init__(self, x, y, b):
        self.x = x
        self.y = y
        self.b = b

    '''Implement the Gaussian Kernel'''
    def gaussian_kernel(self, z):
        return (1/math.sqrt(2*math.pi))*math.exp(-0.5*z**2)

    '''Calculate weights and return prediction'''
    def predict(self, X):
        kernels = [self.gaussian_kernel((xi-X)/self.b) for xi in self.x]
        weights = [len(self.x) * (kernel/np.sum(kernels)) for kernel in kernels]
        return np.dot(weights, self.y)/len(self.x)


llke = GKR(x, y, 0.2)

y_hat=pd.DataFrame(index=range(x.shape[0]))
for row in range(x.shape[0]):
    y_hat.iloc[row] = llke.predict(float(x.iloc[row]))
y_hat

但我收到错误消息:TypeError: unsupported operand type(s) for -: 'str' and 'float'。据我了解,问题出在self.gaussian_kernel((xi-X) 中,它出于某种原因将xi 视为字符串。我试图将它包装在 float() 函数中,但它没有帮助。可能是什么问题呢?或者,您可以随意提出将函数 predict 应用于向量而不是单个值的替代方法。

【问题讨论】:

    标签: python vectorization typeerror kernel-density


    【解决方案1】:

    问题在于x 和y 以错误的格式给出(作为列表的列表,而不是列表),这就是解释器可以正确处理它的原因。

    【讨论】:

      猜你喜欢
      • 2022-12-03
      • 1970-01-01
      • 2020-11-28
      • 2018-12-26
      • 2013-05-08
      • 1970-01-01
      • 2013-10-29
      • 1970-01-01
      相关资源
      最近更新 更多