【问题标题】:Problem with simulation kernel density with python使用python模拟内核密度的问题
【发布时间】:2019-04-14 07:26:05
【问题描述】:

我想使用内核密度进行模拟观察,但我有以下错误类型:TypeError: unsupported operand type(s) for +: 'float' and 'NoneType'

如何解决? 这是我使用的代码:

    from matplotlib.pyplot import *
    from math import *
    from array import *
    import numpy as np 
    from numpy.random import *
    from scipy.misc import *
    from scipy.stats import *
    from scipy import *
    from random import *


    N=1000
    n=30
    lamb=0.5
    X=lamb*tan(pi*(np.reshape(rand(n,1),n)-0.5)) #loi de Cauchy  
    x=1
    alpha=0.45

    def k_gaussien(x):
        sigma=1
        if(sigma<=0):
            return((1/(sigma*sqrt(2*pi)))*exp(-(x**2/(2*sigma**2))))

    def h(n,alpha):
        for i in range(1,n):   
            return (i**(1-alpha))

    def f_PR(x,X,alpha):
        global F;
        F = ones((n,1))
        h_n = h(n,alpha)
        for k in range(2,n):
            for i in  range(1,k):
                F[k] = F[k-1] + k_gaussien((x-X[i])*i**alpha)
            F[k] = F[k-1] * h_n
        return F

    # Almost sure convergence f_n(x)--> f(x) ps
    figure(figsize=(20,10))
    fPR=f_PR(x,X,alpha)
    T=linspace(1,n,n);
    plot(cumsum(fPR)/T)
    plot(T,(1/pi)*(lamb/(lamb**2 + y**2))*linspace(1,1,N),"r--",lw=3)#with Cauchy density
    grid(True)
    title("convergence presque sure",fontsize=20,color="blue")

    #Convergence in mean N(0,e2f(x))
    hist(fPR,bins=linspace(-10,10,50),normed=True)
    y=linspace(-10,10,100);
    v=(1/pi)*(lamb/(lamb**2 + y**2))
    plot(y,(1/sqrt(2*pi)*v)*exp ((-(y*y)/(2*v**2)))*linspace(1,1,n),'r--') #with cauchy density
    title("convergence asymptotique", fontsize=20,color="blue")

TypeError Traceback(最近一次调用最后一次)

<ipython-input-76-13bc86608417> in <module>()
         38 # Almost sure convergence f_n(x)--> f(x) ps
         39 figure(figsize=(20,10))
    ---> 40 fPR=f_PR(x,X,alpha)
         41 T=linspace(1,n,n);
         42 plot(cumsum(fPR)/T)

    <ipython-input-76-13bc86608417> in f_PR(x, X, alpha)
         32     for k in range(2,n):
         33         for i in  range(1,k):
    ---> 34             F[k] = F[k-1] + k_gaussien((x-X[i])*i**alpha)
         35         F[k] = F[k-1] * h_n
         36     return F

TypeError:+ 不支持的操作数类型:“float”和“NoneType”

【问题讨论】:

  • 嗨,欢迎来到 Stackoverflow。请发布完整的堆栈跟踪。

标签: python simulation


【解决方案1】:

在你的定义中:

def k_gaussien(x):
    sigma=1
    if(sigma<=0):
        return((1/(sigma*sqrt(2*pi)))*exp(-(x**2/(2*sigma**2))))

您对sigma=1 进行了硬编码,但您的函数仅在sigma&lt;=0 的情况下才返回某些内容,而这绝不会是这种情况。所以k_gaussien((x-X[i])*i**alpha) 将返回None。因此F[k] = F[k-1] + k_gaussien((x-X[i])*i**alpha) 尝试对 float 和 None 类型求和,这是行不通的。

【讨论】:

    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 2017-10-14
    • 2021-01-20
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    相关资源
    最近更新 更多