我正在尝试制作一个Kernel Estimator (如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()函数中,但是没有用。可能的问题是什么?或者,您可以随意建议将函数预测应用于向量而不是单个值的替代方法。
发布于 2021-02-26 12:25:45
问题是x和y给出了错误的格式(作为列表的列表,而不是列表),这就是为什么解释器可以正确地处理它。
https://stackoverflow.com/questions/66367056
复制相似问题