def test_kernel_parzen(): def w(k): w = np.empty(k + 1) for i in range(k + 1): z = i / (k + 1) if z > 0.5: w[i] = 2 * (1 - z)**3 else: w[i] = 1 - 6 * z**2 + 6 * z**3 return w assert_equal(w(0), kernel_weight_parzen(0)) assert_equal(w(1), kernel_weight_parzen(1)) assert_equal(w(10), kernel_weight_parzen(10))
def test_kernel_weight_direct(weight_data, center, debias): bandwidth = 12 wm = KernelWeightMatrix(center, debias, kernel="parzen", bandwidth=bandwidth) x, z, eps, sigma = weight_data weights = wm.weight_matrix(x, z, eps, sigma=sigma) k = len(z) ze = [z[i] * eps[:, i:i + 1] for i in range(k)] ze = np.concatenate(ze, 1) if center: ze = ze - ze.mean(0) nobs = ze.shape[0] direct = ze.T @ ze / nobs w = kernel_weight_parzen(bandwidth) for i in range(1, bandwidth + 1): op = ze[:-i].T @ ze[i:] / nobs direct += w[i] * (op + op.T) if debias: df = [vx.shape[1] * np.ones(vz.shape[1]) for vx, vz in zip(x, z)] df = np.concatenate(df)[:, None] df = np.sqrt(df) adj = nobs / (nobs - df @ df.T) direct *= adj assert_allclose(weights, direct)
def test_kernel_direct(cov_data, debias): x, z, eps, sigma = cov_data k = len(x) bandwidth = 12 cov = KernelCovariance(x, eps, sigma, sigma, gls=False, debiased=debias, kernel='parzen', bandwidth=bandwidth) assert cov.bandwidth == 12 xe = [x[i] * eps[:, i:i + 1] for i in range(k)] xe = np.concatenate(xe, 1) w = kernel_weight_parzen(12) nobs = xe.shape[0] xeex = np.zeros((xe.shape[1], xe.shape[1])) xeex += xe.T @ xe / nobs for i in range(1, bandwidth + 1): op = xe[:-i].T @ xe[i:] / nobs xeex += w[i] * (op + op.T) xpxi = _xpxi(x) direct = xpxi @ xeex @ xpxi / nobs direct = (direct + direct.T) / 2 if debias: df = [x[i].shape[1] * np.ones(x[i].shape[1]) for i in range(k)] df = np.concatenate(df)[:, None] adj = nobs / (nobs - np.sqrt(df) @ np.sqrt(df).T) direct *= adj direct = (direct + direct.T) / 2 assert_allclose(np.diag(direct), np.diag(cov.cov)) s = np.sqrt(np.diag(direct))[:, None] r_direct = direct / (s @ s.T) s = np.sqrt(np.diag(cov.cov))[:, None] c_direct = direct / (s @ s.T) assert_allclose(r_direct, c_direct, atol=1e-5)