Fitting a Weibull distribution using Scipy

前端 未结 7 759
误落风尘
误落风尘 2020-12-04 09:22

I am trying to recreate maximum likelihood distribution fitting, I can already do this in Matlab and R, but now I want to use scipy. In particular, I would like to estimate

7条回答
  •  生来不讨喜
    2020-12-04 09:44

    I know it's an old post, but I just faced a similar problem and this thread helped me solve it. Thought my solution might be helpful for others like me:

    # Fit Weibull function, some explanation below
    params = stats.exponweib.fit(data, floc=0, f0=1)
    shape = params[1]
    scale = params[3]
    print 'shape:',shape
    print 'scale:',scale
    
    #### Plotting
    # Histogram first
    values,bins,hist = plt.hist(data,bins=51,range=(0,25),normed=True)
    center = (bins[:-1] + bins[1:]) / 2.
    
    # Using all params and the stats function
    plt.plot(center,stats.exponweib.pdf(center,*params),lw=4,label='scipy')
    
    # Using my own Weibull function as a check
    def weibull(u,shape,scale):
        '''Weibull distribution for wind speed u with shape parameter k and scale parameter A'''
        return (shape / scale) * (u / scale)**(shape-1) * np.exp(-(u/scale)**shape)
    
    plt.plot(center,weibull(center,shape,scale),label='Wind analysis',lw=2)
    plt.legend()
    

    Some extra info that helped me understand:

    Scipy Weibull function can take four input parameters: (a,c),loc and scale. You want to fix the loc and the first shape parameter (a), this is done with floc=0,f0=1. Fitting will then give you params c and scale, where c corresponds to the shape parameter of the two-parameter Weibull distribution (often used in wind data analysis) and scale corresponds to its scale factor.

    From docs:

    exponweib.pdf(x, a, c) =
        a * c * (1-exp(-x**c))**(a-1) * exp(-x**c)*x**(c-1)
    

    If a is 1, then

    exponweib.pdf(x, a, c) =
        c * (1-exp(-x**c))**(0) * exp(-x**c)*x**(c-1)
      = c * (1) * exp(-x**c)*x**(c-1)
      = c * x **(c-1) * exp(-x**c)
    

    From this, the relation to the 'wind analysis' Weibull function should be more clear

提交回复
热议问题