I’m trying to adapt the following matlab code to julia
% MATLAB code to perform the cross validation
lambda = 1;
n = 1000;
X = exprnd(1/lambda,[n,1]);
m = 6:200;
J = zeros(1,195);
for i=1:195
[num,binc] = hist(X,m(i));
h = n/m(i);
J(i) = 2/((n-1)*h)-((n+1)/((n-1)*h))*sum( (num/n).^2 );
end
plot(m,J,'LineWidth',4,'Color',[0.9,0.2,0.0]);
Similar implemetation in Python:
# Python code to perform the cross validation
import numpy as np
import matplotlib.pyplot as plt
lambd = 1
n = 1000
X = np.random.exponential(1/lambd, size=n)
m = np.arange(5,200)
J = np.zeros((195))
for i in range(0,195):
hist,bins = np.histogram(X,bins=m[i])
h = n/m[i]
J[i] = 2/((n-1)*h)-((n+1)/((n-1)*h))*np.sum((hist/n)**2)
plt.plot(m,J);
Which output is:
With the Julia code:
using Plots,Random,Distributions,StatsBase
λ = 1
n = 1_000
d = Exponential(1/λ)
X = rand(d,n)
m = 6:200
J = zeros(195)
for i = 1:195
hist = fit(Histogram,X,nbins = m[i])
h = n/m[i]
J[i] = 2/((n-1)*h)-((n+1)/((n-1)*h))*sum( (hist.weights/n).^2 )
end
plot(m,J)
But the ouput is :
Am I missing something?