Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def model(args):
return {"y": st.norm(args['x'], sigma).rvs()}
def test_neg_log_normal():
neg_log_p = neg_log_normal(2, 0.1)
true_rv = st.norm(2, 0.1)
for x in np.random.randn(10):
assert_almost_equal(neg_log_p(x), -true_rv.logpdf(x))
def d2norm(filespec):
""" Local routine to read data and produce the norm loc and size dict.
"""
x = np.loadtxt(filespec)
loc, scale = sp.norm.fit(x)
dictout = {'loc':loc, 'scale':scale}
return 'norm', dictout
endog = results.model.endog
nobs = endog.shape[0] #TODO: use attribute, may need to be added
fitted = results.predict()
#fitted = results.fittedvalues # discrete has linear prediction
#this assumes Poisson
resid2 = results.resid_response**2
var_resid_endog = (resid2 - endog)
var_resid_fitted = (resid2 - fitted)
std1 = np.sqrt(2 * (fitted**2).sum())
var_resid_endog_sum = var_resid_endog.sum()
dean_a = var_resid_fitted.sum() / std1
dean_b = var_resid_endog_sum / std1
dean_c = (var_resid_endog / fitted).sum() / np.sqrt(2 * nobs)
pval_dean_a = stats.norm.sf(np.abs(dean_a))
pval_dean_b = stats.norm.sf(np.abs(dean_b))
pval_dean_c = stats.norm.sf(np.abs(dean_c))
results_all = [[dean_a, pval_dean_a],
[dean_b, pval_dean_b],
[dean_c, pval_dean_c]]
description = [['Dean A', 'mu (1 + a mu)'],
['Dean B', 'mu (1 + a mu)'],
['Dean C', 'mu (1 + a)']]
# Cameron Trived auxiliary regression page 78 count book 1989
endog_v = var_resid_endog / fitted
res_ols_nb2 = OLS(endog_v, fitted).fit(use_t=False)
stat_ols_nb2 = res_ols_nb2.tvalues[0]
pval_ols_nb2 = res_ols_nb2.pvalues[0]
results_all.append([stat_ols_nb2, pval_ols_nb2])
stock_mean = stock_day_change[0].mean()
# 标准差
stock_std = stock_day_change[0].std()
print('股票0 mean均值期望:{:.3f}'.format(stock_mean))
print('股票0 std振幅标准差:{:.3f}'.format(stock_std))
# 绘制股票0的直方图
plt.hist(stock_day_change[0], bins=50, normed=True)
# linspace从股票0 最小值-> 最大值生成数据
fit_linspace = np.linspace(stock_day_change[0].min(),
stock_day_change[0].max())
# 概率密度函数(PDF,probability density function)
# 由均值,方差,来描述曲线,使用scipy.stats.norm.pdf生成拟合曲线
pdf = scs.norm(stock_mean, stock_std).pdf(fit_linspace)
print(pdf)
# plot x, y
plt.plot(fit_linspace, pdf, lw=2, c='r')
plt.show()
fit_probability=logit_fit,
success_params=success_params,
alpha=alpha,
B=1000)[0]
pvalues.append(pvalue)
pivots.append(pivot)
covered.append((interval[0] < true_target[0]) * (interval[1] > true_target[0]))
print(interval, 'interval')
lengths.append(interval[1] - interval[0])
lower.append(interval[0])
upper.append(interval[1])
target_sd = np.sqrt(dispersion * XTXi[idx, idx])
observed_target = np.squeeze(XTXi[idx].dot(X.T.dot(y)))
quantile = ndist.ppf(1 - 0.5 * alpha)
naive_interval = (observed_target - quantile * target_sd, observed_target + quantile * target_sd)
naive_pivot = (1 - ndist.cdf((observed_target - true_target[0]) / target_sd))
naive_pivot = 2 * min(naive_pivot, 1 - naive_pivot)
naive_pivots.append(naive_pivot)
naive_pvalue = (1 - ndist.cdf(observed_target / target_sd))
naive_pvalue = 2 * min(naive_pivot, 1 - naive_pivot)
naive_pvalues.append(naive_pvalue)
naive_covered.append((naive_interval[0] < true_target[0]) * (naive_interval[1] > true_target[0]))
naive_lengths.append(naive_interval[1] - naive_interval[0])
if len(pvalues) > 0:
return pd.DataFrame({'pivot':pivots,
'target':targets,
qchisq = np.sum(np.abs(residq)**2)
uchisq = np.sum(np.abs(residu)**2)
pchisq = np.sum(np.abs(residp)**2)
mchisq = np.sum(np.abs(residm)**2)
print "Q Chi^2/2N: %f" % (qchisq/(2*len(vis)))
print "U Chi^2/2N: %f" % (uchisq/(2*len(vis)))
print "P Chi^2/2N: %f" % (pchisq/(2*len(vis)))
print "m Chi^2/2N: %f" % (mchisq/(2*len(vis)))
# plot the histograms
plt.figure()
plt.subplot(241)
n,bins,patches = plt.hist(np.real(residq), normed=1, range=(-5,5), bins=50, color='b', alpha=0.5)
n,bins,patches = plt.hist(np.imag(residq), normed=1, range=(-5,5), bins=50, color='r', alpha=0.5)
y = scipy.stats.norm.pdf(bins)
plt.plot(bins, y, 'b--', linewidth=3)
plt.xlabel('Q Normalized Residual Re/Imag')
plt.ylabel('p')
plt.subplot(242)
n,bins,patches = plt.hist(np.real(residu), normed=1, range=(-5,5), bins=50, color='b', alpha=0.5)
n,bins,patches = plt.hist(np.imag(residu), normed=1, range=(-5,5), bins=50, color='r', alpha=0.5)
y = scipy.stats.norm.pdf(bins)
plt.plot(bins, y, 'b--', linewidth=3)
plt.xlabel('U Normalized Residual Re/Imag')
plt.ylabel('p')
plt.subplot(243)
n,bins,patches = plt.hist(np.real(residp), normed=1, range=(-5,5), bins=50, color='b', alpha=0.5)
n,bins,patches = plt.hist(np.imag(residp), normed=1, range=(-5,5), bins=50, color='r', alpha=0.5)
y = scipy.stats.norm.pdf(bins)
ax.imshow(x_mean[k].squeeze())
ax.set_title("reconstructed")
plt.axis("off")
figfile = save_figure(fig, args.image_dir, '03_reconstructions.png')
#fig.savefig(figfile, dpi=300, facecolor=[0, 0, 0, 0])
log.info(f"the figure of original and reconstructed image samples is stored to {figfile}")
# display a 2D manifold of the digits
n = 7 # figure with 15x15 digits
digit_size = 28
figure = np.zeros((digit_size * n, digit_size * n))
# linearly spaced coordinates on the unit square were transformed through the inverse CDF (ppf) of the Gaussian
# to produce values of the latent variables z, since the prior of the latent space is Gaussian
grid_x = norm.ppf(np.linspace(0.05, 0.95, n))
grid_y = norm.ppf(np.linspace(0.05, 0.95, n))
null_image = Variable(torch.Tensor(np.zeros((1, 784))))
fig = plt.figure(figsize=(12, 30))
for y in range(10):
plt.subplot(5, 2, y + 1)
y_hot = np.zeros((1, 10))
y_hot[0, y] = 1
y_hot = Variable(torch.FloatTensor(y_hot))
my = (ys == y)
for i, z0i in enumerate(grid_x):
for j, z1j in enumerate(grid_y[-1::-1]):
z = np.array([[z0i, z1j]])
if NUM_STYLE > 2:
z = zs2_mean[None, :] + zs2_std[None, :] * z
n = ((zs2[my] - z) ** 2).sum(1).argmin()
z = zs[my][n][None, :]
def normalCdf(x,mu=0.0,sigma=1.0):
"""
Computation of normal cdf
@ In, x, list or np.array, x values
@ In, mu, float, optional, mean
@ In, sigma, float, optional, sigma
@ Out, cdfReturn, list or np.array, cdf
"""
return stats.norm.cdf(x,mu,sigma)
def __call__(self, x):
if not len(x) == self._n_parameters:
raise ValueError('x must be of same dimensions as density')
return scipy.stats.norm.logpdf(
np.linalg.norm(x), self._r0, self._sigma)