Here are the examples of the python api numpy.testing.assert_array_almost_equal taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
174 Examples
3
Example 51
Project: seaborn Source File: test_linearmodels.py
@skipif(_no_statsmodels)
def test_fast_regression(self):
p = lm._RegressionPlotter("x", "y", data=self.df, n_boot=self.n_boot)
# Fit with the "fast" function, which just does linear algebra
yhat_fast, _ = p.fit_fast(self.grid)
# Fit using the statsmodels function with an OLS model
yhat_smod, _ = p.fit_statsmodels(self.grid, smlm.OLS)
# Compare the vector of y_hat values
npt.assert_array_almost_equal(yhat_fast, yhat_smod)
3
Example 52
Project: astroML Source File: test_iterative_PCA.py
def test_iterative_PCA(n_samples=50, n_features=40):
np.random.seed(0)
# construct some data that is well-approximated
# by two principal components
x = np.linspace(0, np.pi, n_features)
x0 = np.linspace(0, np.pi, n_samples)
X = np.sin(x) * np.cos(0.5 * (x - x0[:, None]))
# mask 10% of the pixels
M = (np.random.random(X.shape) > 0.9)
# reconstruct and check accuracy
for norm in (None, 'L1', 'L2'):
X_recons = iterative_pca(X, M, n_ev=2, n_iter=10, norm=norm)
assert_array_almost_equal(X, X_recons, decimal=2)
3
Example 53
Project: SpiceyPy Source File: test_support_types.py
def test_SpiceEllipse():
spice.kclear()
spice.reset()
viewpt = [2.0, 0.0, 0.0]
limb = spice.edlimb(np.sqrt(2), 2.0 * np.sqrt(2), np.sqrt(2), viewpt)
expectedSMinor = [0.0, 0.0, -1.0]
expectedSMajor = [0.0, 2.0, 0.0]
expectedCenter = [1.0, 0.0, 0.0]
npt.assert_array_almost_equal(limb.center, expectedCenter)
npt.assert_array_almost_equal(limb.semi_major, expectedSMajor)
npt.assert_array_almost_equal(limb.semi_minor, expectedSMinor)
assert str(limb).startswith("<SpiceEllipse")
spice.reset()
spice.kclear()
3
Example 54
def test_featureselector():
trajectories = AlanineDipeptide().get_cached().trajectories
fs = FeatureSelector(FEATS, which_feat='phi')
assert fs.which_feat == ['phi']
y1 = fs.partial_transform(trajectories[0])
y_ref1 = FEATS[0][1].partial_transform(trajectories[0])
np.testing.assert_array_almost_equal(y_ref1, y1)
3
Example 55
Project: PyEMMA Source File: test_api_source.py
def test_various_formats_source(self):
chunksizes = [0, 13]
X = None
bpti_mini_previous = None
for cs in chunksizes:
for bpti_mini in self.bpti_mini_files:
Y = api.source(bpti_mini, top=self.bpti_pdbfile).get_output(chunk=cs)
if X is not None:
np.testing.assert_array_almost_equal(X, Y, err_msg='Comparing %s to %s failed for chunksize %s'
% (bpti_mini, bpti_mini_previous, cs))
X = Y
bpti_mini_previous = bpti_mini
3
Example 56
Project: holoviews Source File: comparison.py
@classmethod
def compare_arrays(cls, arr1, arr2, msg='Arrays'):
try:
assert_array_equal(arr1, arr2)
except:
try:
assert_array_almost_equal(arr1, arr2)
except AssertionError as e:
raise cls.failureException(msg + str(e)[11:])
3
Example 57
def test_model():
# Check basics about the model fit
# Check we fit the mean
assert_array_almost_equal(RESULTS.theta[1], np.mean(Y))
# Check we get the same as R
assert_array_almost_equal(RESULTS.theta, [1.773, 2.5], 3)
try:
percentile = np.percentile
except AttributeError:
# Numpy <=1.4.1 does not have percentile function
raise SkipTest('Numpy does not have percentile function')
pcts = percentile(RESULTS.resid, [0, 25, 50, 75, 100])
assert_array_almost_equal(pcts, [-1.6970, -0.6667, 0, 0.6667, 1.6970], 4)
3
Example 58
Project: ttpy Source File: riemannian_test.py
def test_project_sum_equal_ranks(self):
for debug_mode in [False, True]:
for use_jit in [False, True]:
X = tt.rand([4, 4, 4], 3, [1, 4, 4, 1])
Z = [0] * 7
for idx in range(7):
Z[idx] = tt.rand([4, 4, 4], 3, [1, 2, 3, 1])
project_sum = riemannian.project(X, Z, use_jit=use_jit,
debug=debug_mode)
sum_project = X * 0
for idx in range(len(Z)):
sum_project += riemannian.project(X, Z[idx],
use_jit=use_jit,
debug=debug_mode)
np.testing.assert_array_almost_equal(sum_project.full(),
project_sum.full())
3
Example 59
Project: numdifftools Source File: test_extrapolation.py
def test_epsal(self):
true_vals = [0.78539816, 0.94805945, 0.99945672]
dea = EpsAlg(limexp=7)
vals = [dea(val) for val in [0.78539816, 0.94805945, 0.98711580]]
assert_array_almost_equal(true_vals, vals)
dea2 = EpsAlg(limexp=7)
vals2 = [dea2(val) for val in self.e_i[:-1]]
assert_array_almost_equal(vals2,
[0.99979919432001874, 0.99994980009210122,
0.99999999949599017, 0.99999999996850009,
1.0, 1.0])
3
Example 60
Project: pyRiemann Source File: test_utils_geodesic.py
def test_geodesic_riemann_middle():
"""Test riemannian geodesic when alpha = 0.5"""
A = 0.5*np.eye(3)
B = 2*np.eye(3)
Ctrue = np.eye(3)
assert_array_almost_equal(geodesic_riemann(A,B,0.5),Ctrue)
3
Example 61
Project: megaman Source File: test_isomap.py
def test_isomap_simple_grid():
# Isomap should preserve distances when all neighbors are used
N_per_side = 5
Npts = N_per_side ** 2
radius = 10
# grid of equidistant points in 2D, n_components = n_dim
X = np.array(list(product(range(N_per_side), repeat=2)))
# distances from each point to all others
G = squareform(pdist(X))
g = geom.Geometry(adjacency_kwds = {'radius':radius})
for eigen_solver in EIGEN_SOLVERS:
clf = iso.Isomap(n_components = 2, eigen_solver = eigen_solver, geom=g)
clf.fit(X)
G_iso = squareform(pdist(clf.embedding_))
assert_array_almost_equal(G, G_iso)
3
Example 62
Project: mdp-toolkit Source File: _tools.py
def verify_ICANode(icanode, rand_func = uniform, vars=3, N=8000, prec=3):
dim = (N, vars)
mat,mix,inp = get_random_mix(rand_func=rand_func,mat_dim=dim)
icanode.train(inp)
act_mat = icanode.execute(inp)
cov = mdp.utils.cov2(old_div((mat-mean(mat,axis=0)),std(mat,axis=0)), act_mat)
maxima = numx.amax(abs(cov), axis=0)
assert_array_almost_equal(maxima,numx.ones(vars), prec)
3
Example 63
Project: hyperspy Source File: test_model.py
def test_model_function(self):
m = self.model
m.append(hs.model.components1D.Gaussian())
m[0].A.value = 1.3
m[0].centre.value = 0.003
m[0].sigma.value = 0.1
param = (100, 0.1, 0.2)
np.testing.assert_array_almost_equal(176.03266338,
m._model_function(param))
nt.assert_equal(m[0].A.value, 100)
nt.assert_equal(m[0].centre.value, 0.1)
nt.assert_equal(m[0].sigma.value, 0.2)
3
Example 64
Project: lyman Source File: test_model.py
def test_dot_by_slice_submatrix(self):
n_x, n_y, n_z, n_t, n_pe = 11, 10, 9, 25, 4
X = Bunch(design_matrix=pd.DataFrame(self.rs.randn(n_t, n_pe)),
confound_vector=np.array([[1, 0, 0, 1]]).T)
pes = self.rs.randn(n_x, n_y, n_z, n_pe)
ms = model.ModelSummary()
out = ms.dot_by_slice(X, pes, "confound")
nt.assert_equal(out.shape, (n_x, n_y, n_z, n_t))
for i, j, k in product(range(n_x), range(n_y), range(n_z)):
pe_ijk = pes[i, j, k] * X.confound_vector.T
yhat_ijk = X.design_matrix.dot(pe_ijk.T).squeeze()
npt.assert_array_almost_equal(yhat_ijk, out[i, j, k])
3
Example 65
Project: yellowbrick Source File: test_radviz.py
def test_normalize_x(self):
"""
Test the static normalization method on the RadViz class
"""
expected = np.array(
[[ 1. , 0.00332594, 0. , 0.07162791, 0.01543943],
[ 0.98557692, 0.00221729, 0.16666667, 0.00465116, 0.00475059],
[ 0.98557692, 0. , 0. , 0. , 0. ],
[ 0. , 0.98115299, 0.33333333, 0.79069767, 0.96912114],
[ 0. , 1. , 0.33333333, 0.99348837, 1. ],
[ 0. , 0.99334812, 1. , 1. , 0.98931116]]
)
Xp = RadViz.normalize(self.X)
npt.assert_array_almost_equal(Xp, expected)
3
Example 66
Project: brainx Source File: test_metrics.py
def test_nodal_pathlengths_conn(self):
mean_path_lengths = metrics.nodal_pathlengths(self.g)
desired = 1.0 / (self.n_nodes - 1) * np.array([1 + 1 + 2 + 3,
1 + 1 + 2 + 3,
1 + 1 + 1 + 2,
2 + 2 + 1 + 1,
3 + 3 + 2 + 1])
npt.assert_array_almost_equal(mean_path_lengths, desired)
3
Example 67
def testMeasure(self):
particles = self.model.create_initial_estimate(1)
(zl, Pl) = self.model.get_states(particles)
y = 1.0
# https://en.wikipedia.org/wiki/Kalman_filter
S = self.C * self.P0 * self.C + self.R
K = self.P0 * self.C / S
xn = zl[0] + K * (y - self.C * zl[0])
Pn = Pl[0] - K * self.C * Pl[0]
partn = numpy.copy(particles)
_ = self.model.measure(partn, numpy.asarray(y).reshape((-1, 1)), None)
(nzl, nPl) = self.model.get_states(partn)
npt.assert_array_almost_equal(xn[0].ravel(), nzl[0].ravel(), 10)
npt.assert_array_almost_equal(Pn[0].ravel(), nPl[0].ravel(), 10)
3
Example 68
Project: openpathsampling Source File: test_shooting_point_analysis.py
def test_committor_histogram_2d(self):
rehash = lambda snap : (snap.xyz[0][0], 2 * snap.xyz[0][0])
input_bins = [-0.05, 0.05, 0.15, 0.25, 0.35, 0.45]
hist, b_x, b_y = self.analyzer.committor_histogram(rehash, self.left,
input_bins)
assert_equal(hist.shape, (5,5))
for i in range(5):
for j in range(5):
if (i,j) in [(0, 0), (1, 2)]:
pass
assert_true(hist[(i,j)] > 0)
else:
assert_true(np.isnan(hist[(i,j)]))
# this may change later to bins[0]==bins[1]==input_bins
assert_array_almost_equal(input_bins, b_x)
assert_array_almost_equal(input_bins, b_y)
3
Example 69
def test_count(self):
n_samples = 100
n_partitions = 10
mat = [np.array([1]) for i in range(n_samples)]
data = block_rdd(self.sc.parallelize(mat, n_partitions))
assert_array_almost_equal(n_samples, count(data))
3
Example 70
Project: numdifftools Source File: test_extrapolation.py
def test_order_step_combinations(self):
for num_terms in [1, 2, 3]:
for step in [1, 2]:
for order in range(1, 7):
r_extrap = Richardson(step_ratio=2.0, step=step,
num_terms=num_terms, order=order)
rule = r_extrap.rule()
# print((num_terms, step, order), rule.tolist())
assert_array_almost_equal(rule,
self.true_vals[(num_terms, step,
order)])
3
Example 71
Project: fireant Source File: test_postprocessors.py
def test_single_dim_both_metrics(self):
df = mock_df.cont_dim_multi_metric_df
result_df = self.manager.post_process(df, [{'key': self.op_key, 'metric': 'one'},
{'key': self.op_key, 'metric': 'two'}])
# original DF unchanged
self.assertListEqual(['one', 'two'], list(df.columns))
operation1_key = 'one_%s' % self.op_key
operation2_key = 'two_%s' % self.op_key
self.assertListEqual(['one', 'two', operation1_key, operation2_key], list(result_df.columns))
np.testing.assert_array_almost_equal(self.operation(df['one']), list(result_df[operation1_key]))
np.testing.assert_array_almost_equal(self.operation(df['two']), list(result_df[operation2_key]))
3
Example 72
def test_hmm():
n_features = X.shape[1]
clf = MultinomialHMM()
clf.fit(X, y, lengths)
assert_array_equal(clf.classes_, ["Adj", "DT", "IN", "N", "V"])
assert_array_equal(clf.predict(X), y)
clf.set_params(decode="bestfirst")
assert_array_equal(clf.predict(X), y)
n_classes = len(clf.classes_)
assert_array_almost_equal(np.ones(n_features),
np.exp(clf.coef_).sum(axis=0))
assert_array_almost_equal(np.ones(n_classes),
np.exp(clf.intercept_trans_).sum(axis=0))
assert_array_almost_equal(1., np.exp(clf.intercept_final_).sum())
assert_array_almost_equal(1., np.exp(clf.intercept_init_).sum())
3
Example 73
Project: SpiceyPy Source File: test_support_types.py
def test_SpicePlane():
norm = [0.0, 0.0, 1.0]
orig = [0.0, 0.0, 0.0]
plane = spice.nvp2pl(norm, orig)
npt.assert_array_almost_equal(plane.normal, norm)
assert plane.constant == 0.0
assert str(plane).startswith("<SpicePlane")
3
Example 74
Project: PyGeM Source File: test_ffdparams.py
def test_read_parameters_position_vertex_0_origin(self):
params = ffdp.FFDParameters(n_control_points=[3, 2, 2])
params.read_parameters('tests/test_datasets/parameters_sphere.prm')
np.testing.assert_array_almost_equal(
params.position_vertex_0, params.origin_box
)
3
Example 75
def test_readwrite(self):
r = LoadCaseReader()
r.case_files = glob.glob('data/extreme_loads0*')
r.execute()
w = LoadCaseWriter()
w.load_cases = r.load_cases
w.file_base = 'test_lc'
w.execute()
rr = LoadCaseReader()
rr.case_files = glob.glob('test_lc0*.dat')
rr.execute()
for i, case in enumerate(r.load_cases.cases):
c0 = case._toarray()
l1 = rr.load_cases.cases[i]
c1 = l1._toarray()
self.assertEqual(np.testing.assert_array_almost_equal(c0, c1, decimal=6), None)
3
Example 76
Project: python-acoustic-similarity Source File: test_rep_gammatone.py
def test_gammatone(base_filenames):
for f in base_filenames:
wavpath = f+'.wav'
matpath = f+'_gammatone_env.mat'
if not os.path.exists(matpath):
continue
m = loadmat(matpath)
bm, env = to_gammatone(wavpath, num_bands = 4, freq_lims = (80,7800))
assert_array_almost_equal(m['bm'],bm)
assert_array_almost_equal(m['env'],env)
break # takes forever!
3
Example 77
Project: PySnpTools Source File: test.py
def test_npz(self):
logging.info("in test_npz")
snpreader = Bed(self.currentFolder + "/../examples/toydata",count_A1=False)
kerneldata1 = snpreader.read_kernel(standardizer=stdizer.Unit())
s = str(kerneldata1)
output = "tempdir/kernelreader/toydata.kernel.npz"
create_directory_if_necessary(output)
KernelNpz.write(output,kerneldata1)
kernelreader2 = KernelNpz(output)
kerneldata2 = kernelreader2.read()
np.testing.assert_array_almost_equal(kerneldata1.val, kerneldata2.val, decimal=10)
logging.info("done with test")
3
Example 78
Project: healpy Source File: test_pixelfunc.py
def test_ang2pix_ring(self):
# ensure nside = 1 << 23 is correctly calculated
# by comparing the original theta phi are restored.
# NOTE: nside needs to be sufficiently large!
id = ang2pix(1048576 * 8, self.theta0, self.phi0, nest=False)
theta1, phi1 = pix2ang(1048576 * 8, id, nest=False)
np.testing.assert_array_almost_equal(theta1, self.theta0)
np.testing.assert_array_almost_equal(phi1, self.phi0)
3
Example 79
Project: lda Source File: test_lda_transform.py
def test_lda_transform_basic(self):
"""Basic checks on transform"""
model = self.model
dtm = self.dtm
n_docs = 3
n_topics = len(model.components_)
dtm_test = dtm[0:n_docs]
doc_topic_test = model.transform(dtm_test)
self.assertEqual(doc_topic_test.shape, (n_docs, n_topics))
np.testing.assert_array_almost_equal(doc_topic_test.sum(axis=1), 1)
# one docuement
dtm_test = dtm[0]
doc_topic_test = model.transform(dtm_test)
self.assertEqual(doc_topic_test.shape, (1, n_topics))
np.testing.assert_array_almost_equal(doc_topic_test.sum(axis=1), 1)
3
Example 80
Project: scimath Source File: has_units_test_case.py
def test_v_feet(self):
z = vec_bar_with_units( self.feet_array, self.second_array)
self.assertTrue(isinstance(z, UnitArray))
self.assertEquals(z.units, meters)
assert_array_almost_equal(z, numpy.array([ 0.0, 0.0 , 3.6576]))
z = vec_bar_with_units( self.feet_scalar, self.second_scalar)
self.assertTrue(isinstance(z, UnitScalar))
self.assertEquals(z.units, meters)
assert_array_almost_equal(z, 0.0)
3
Example 81
Project: msmbuilder-legacy Source File: test_gpurmsd.py
def test_gpurmsd():
traj = Trajectory.load_trajectory_file(trj_path)
gpurmsd = GPURMSD()
ptraj = gpurmsd.prepare_trajectory(traj)
gpurmsd._gpurmsd.print_params()
gpu_distances = gpurmsd.one_to_all(ptraj, ptraj, 0)
cpurmsd = RMSD()
ptraj = cpurmsd.prepare_trajectory(traj)
cpu_distances = cpurmsd.one_to_all(ptraj, ptraj, 0)
npt.assert_array_almost_equal(cpu_distances, gpu_distances, decimal=4)
3
Example 82
Project: ssp Source File: test.py
def testLSP(self):
order = 4
ac = ssp.Autocorrelation(self.seq)
ar, g = ssp.ARLevinson(ac, order)
print "ar:", ar
ls = ssp.ARLineSpectra(ar)
print "ls:", ls
ar2 = ssp.ARLineSpectraToPoly(ls)
print "ar:", ar2
npt.assert_array_almost_equal(ar, ar2)
3
Example 83
Project: moss Source File: test_glm.py
def test_design_matrix_demeaned():
"""Make sure the design matrix is de-meaned."""
hrf = glm.GammaDifferenceHRF(temporal_deriv=True)
design = pd.DataFrame(dict(condition=["one", "two"],
onset=[5, 10]))
artifacts = np.zeros(15, int)
artifacts[10] = 1
X = glm.DesignMatrix(design, hrf, 15,
regressors=rs.randn(15, 3) + 2,
confounds=(rs.randn(15, 3) +
rs.rand(3)),
artifacts=artifacts)
npt.assert_array_almost_equal(X.design_matrix.mean().values,
np.zeros(11))
3
Example 84
Project: pyDNase Source File: __init__.py
def test_footprinting(self):
"""Test footprinting"""
#Load test data
reads = pyDNase.BAMHandler(pyDNase.example_reads())
regions = pyDNase.GenomicIntervalSet(pyDNase.example_regions())
footprinter = wellington(regions[0],reads)
#Note - we only check the accuracy of the footprinting to 3 decimal places to allow for differences in floating point numbers
numpy.testing.assert_array_almost_equal(footprinter.scores,[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.8505197962574915, -0.7522459055434079, -0.6405956238609599, -0.35029217770692905, -0.19445213824845226, -0.04510918998207078, -0.013127544708030047, -0.019434755711449096, -0.017813062409838532, -0.4899192539679181, -0.7366170062412767, -1.160234291218491, -1.4932241116142613, -2.528451574312211, -2.9873463332686545, -4.0789439624702215, -4.608073840135845, -4.6080738401358445, -5.46591166889954, -6.317058518040485, -7.846849141309235, -8.70970430615968, -7.84684914298093, -10.57133857477595, -9.524456623200592, -8.450720744685238, -7.351088844276472, -6.227879918162327, -5.085807684913266, -1.412414402021511, -3.461932293846784, -3.6968244901998126, -3.6968244901997713, -3.9374380500569046, -3.9374380500569046, -3.502106381128687, -3.968687434788506, -3.968687434788506, -3.9686874347885044, -4.210084222760481, -4.708248147109799, -4.481083945460659, -4.614616491048433, -6.331304868565458, -6.7188196319447515, -7.805240790859276, -10.096125803164037, -10.096125904865069, -9.804317009970552, -10.942957174739428, -10.831197056706369, -9.451636014876547, -9.271803479479166, -10.547425524609011, -11.356756808330887, -10.173763450595242, -17.266997956146163, -24.135650052599853, -26.79974412054261, -24.068532700189742, -20.83033463447785, -17.442306072203564, -3.3271869067645095, -1.552524387513255, -1.2303389949451933, -1.116146321342096, -0.7241346073398854, -0.8217741198401821, -0.5077397193727583, -0.4619110913457732, -0.22648726483418524, -0.08368942693734599, -0.04662652321248819, -0.10740322088702083, -0.1600382576388667, -0.09849358892510252, -0.2996877100052051, -0.4956516466712493, -0.8286771565689258, -0.7441816651207845, -0.5312102440124086, -6.089145200199429, -54.524611990632465, -55.11290166247622, -53.73358776712574, -56.37380673644542, -59.597668457279916, -63.142121596069494, -69.8245790871056, -76.97479986221292, -83.6326531975367, -88.05928977864403, -87.62205344847811, -90.7846299628178, -94.85120273316905, -90.09506169785546, -85.09363194018195, -90.25622681870428, -80.40916250197246, -84.41195387381595, -96.25001089840575, -105.99203665518576, -109.60076099775432, -116.04973655820825, -124.40507207962382, -120.71820677125163, -121.99289957155713, -121.7696295849731, -128.86709184814546, -130.00197395916774, -138.7286574562139, -150.07398897152254, -141.58993458465335, -134.33745073269844, -134.76596995468543, -106.6912682602024, -96.02214212537493, -85.8950778423277, -73.04392809450209, -54.85091731066348, -44.010732916962205, -31.573437293391223, -23.59371038683095, -18.62378346291484, -3.2863459020700057, -1.8733702431391752, -0.492074167081423, -0.27948577530733343, -0.27948577530733343, -0.07138091975833981, -0.09972653646891905, -0.05418579937724513, -0.024132554170139438, -0.021842812415429565, -0.9566534364564785, -6.932360951667957, -11.187077720714367, -13.553355643835602, -14.21631406001477, -14.983929833667665, -15.422758574896921, -18.32278174888965, -18.2834926735795, -17.265359820713286, -16.13035610465361, -14.086076680349992, -13.521427957090859, -12.515293283803214, -11.480271740126698, -9.92078604101271, -8.797191973771438, -6.985510255611701, -5.426767915467293, -5.183152081566609, -3.7475983370968295, -1.9153547972282414, -0.0006083021245538324, -13.64272847695586, -10.286808471857325, -15.63569341874549, -20.86940117070692, -22.928591109686124, -30.496433497261098, -26.10052633266505, -29.221144392666716, -24.0276270737085, -21.301001754269702, -20.97154340860586, -15.798224427435104, -17.780912132981612, -24.823354886252613, -24.604927499889286, -24.955334454941635, -38.74241644973382, -43.782982787325366, -46.80273522972689, -46.08571305295883, -47.92277577875605, -41.4868217475951, -37.915322367616675, -34.16174895135005, -33.58267055798403, -32.06130865601216, -34.094574908150825, -39.695727106225405, -40.120719852615196, -41.05121481573844, -42.01796136083251, -39.75209693618059, -35.73339613779332, -34.731089314533676, -32.694583271242884, -29.577625993685, -28.026659577292953, -25.215089099008644, -25.174202473704753, -21.952113990014446, -17.028869764873075, -15.578727453806595, -16.1579750791396, -12.974390056172448, -8.418484753962995, -5.7847304546785905, -2.2267773783077134, -1.4570520375724902, -1.543691534890984, -1.575957362444019, -0.7176800307627448, -0.7968619556272615, -4.841045489929452, -5.248527604937139, -1.0472142687516643, -1.0630763089203221, -2.185755905394793, -3.8307492546267254, -4.993169872339857, -7.2764872801107385, -6.792829090234741, -6.452991771598523, -6.952945781664499, -8.215168486202954, -6.613961853070211, -22.150574756810474, -28.514525290020345, -27.33821547951633, -29.034538366843996, -33.82258103970177, -41.26481032907057, -40.912839794048644, -48.684226156049405, -49.44508720397513, -61.863467137712874, -70.11156862148243, -82.93974699146762, -91.62613467860213, -91.54466150389183, -73.5404690802315, -75.77506886003911, -78.05398228595476, -84.42906672420139, -93.01020782082938, -89.65901048860756, -109.20614016921928, -121.0826042903611, -120.2996268556599, -117.38782641714545, -128.50467987996305, -128.9595101418021, -133.14841986541902, -136.82233726671367, -133.94746637928725, -154.5649504690748, -164.11983575086742, -159.85307484109336, -151.89784688535133, -153.56557629402886, -146.72984757341305, -135.04501822595842, -127.92055598311715, -126.08111294376953, -120.03403862241993, -99.25696665821185, -71.19178328684012, -64.94518489350295, -59.98207339614661, -54.12991577221696, -43.206052468123545, -29.456860663206527, -6.411526985333728, -6.44709453786988, -6.215828945120546, -5.762898291384889, -4.3769156224166315, -3.2727915503830047, -2.616087927600661, -2.313254659995694, -1.8641066899878078, -1.8186414374916933, -0.8008712043775049, -0.6426129783652371, -0.5224073311989104, -0.2710345166975603, -0.43819657644966853, -1.2626459311104576, -1.9408301832235342, -3.9812039032702886, -3.9812039032702886, -2.861605777578473, -3.2137507785013066, -3.2137507785013066, -2.9669916392942004, -3.2617340566815645, -3.9686874347885044, -3.54350638697767, -3.54350638697767, -3.1070679887817896, -2.8384054421005627, -2.2611557931086583, -2.9566374983191013, -2.2617270920463315, -2.5370237970085574, -3.2091208219605813, -3.0532448758817448, -1.6966894030794892, -2.2744775410764126, -2.729866824495538, -3.080565957210189, -2.808261821233711, -3.251159821714309, -2.1636899060453407, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],decimal=3)
numpy.testing.assert_array_equal(footprinter.lengths,[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 11, 15, 13, 11, 15, 13, 25, 25, 11, 13, 15, 17, 19, 21, 23, 25, 25, 11, 13, 15, 17, 15, 21, 19, 17, 15, 13, 11, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 23, 25, 15, 17, 19, 19, 17, 15, 13, 19, 25, 25, 23, 25, 11, 11, 13, 15, 13, 11, 11, 25, 25, 15, 15, 19, 17, 15, 13, 11, 25, 25, 25, 11, 15, 17, 19, 15, 23, 11, 25, 25, 25, 25, 25, 25, 21, 23, 25, 25, 25, 25, 25, 23, 25, 25, 25, 21, 23, 25, 25, 23, 25, 25, 21, 19, 19, 21, 25, 25, 25, 23, 25, 23, 21, 19, 19, 15, 15, 11, 11, 11, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 11, 11, 13, 15, 11, 11, 21, 17, 15, 13, 15, 13, 25, 25, 23, 21, 19, 19, 13, 13, 13, 11, 25, 11, 13, 15, 17, 11, 13, 15, 17, 15, 13, 11, 25, 15, 17, 19, 19, 23, 25, 25, 21, 23, 21, 19, 17, 13, 25, 25, 25, 25, 25, 25, 25, 23, 21, 19, 25, 25, 23, 11, 11, 15, 15, 13, 15, 13, 11, 19, 15, 13, 11, 11, 11, 11, 11, 15, 15, 19, 21, 23, 25, 25, 23, 25, 25, 15, 11, 13, 15, 17, 19, 21, 23, 25, 25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 21, 23, 25, 25, 25, 25, 25, 25, 21, 23, 25, 25, 25, 25, 23, 25, 25, 25, 25, 23, 21, 19, 15, 15, 13, 11, 13, 25, 25, 25, 25, 25, 25, 25, 23, 25, 25, 25, 25, 11, 11, 11, 13, 11, 11, 15, 17, 17, 21, 23, 25, 25, 25, 25, 23, 17, 19, 17, 15, 13, 11, 19, 11, 13, 15, 15, 13, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
3
Example 85
Project: modl Source File: test_dict_fact.py
@pytest.mark.parametrize("backend", backends)
def test_dict_mf_reconstruction(backend):
X, Q = generate_synthetic()
dict_mf = DictMF(n_components=4, alpha=1e-4,
max_n_iter=300, l1_ratio=0,
backend=backend,
random_state=rng_global, reduction=1)
dict_mf.fit(X)
P = dict_mf.transform(X)
Y = P.T.dot(dict_mf.components_)
assert_array_almost_equal(X, Y, decimal=1)
3
Example 86
Project: neupy Source File: test_sofm.py
def test_sofm(self):
sn = algorithms.SOFM(
n_inputs=2,
n_outputs=3,
weight=self.weight,
learning_radius=0,
features_grid=(3, 1),
verbose=False
)
sn.train(input_data, epochs=100)
np.testing.assert_array_almost_equal(
sn.predict(input_data),
answers
)
3
Example 87
Project: brainx Source File: test_metrics.py
def test_nodal_pathlengths_disconn(self):
self.g.remove_edge(2, 3)
# Now all nodes still have at least one edge, but not all nodes are
# reachable from all others.
path_lengths = metrics.nodal_pathlengths(self.g)
# Distances for all node pairs:
# 0-1: 1 1-2: 1 2-3: Inf 3-4: 1
# 0-2: 1 1-3: Inf 2-4: Inf
# 0-3: Inf 1-4: Inf
# 0-4: Inf
desired = (1.0 / (self.n_nodes - 1) *
np.array([1 + 1 + np.inf + np.inf,
1 + 1 + np.inf + np.inf,
1 + 1 + np.inf + np.inf,
np.inf + np.inf + np.inf + 1,
np.inf + np.inf + np.inf + 1]))
npt.assert_array_almost_equal(path_lengths, desired)
3
Example 88
Project: chaco Source File: discrete_colormapper_test_case.py
def test_map_uint8(self):
self.colormap.color_depth = 'rgb'
a = array([0, 2, 3])
b = self.colormap.map_uint8(a)
self.assertEqual(b.shape, (3, 3))
self.assertEqual(b.dtype, uint8)
for i in range(3):
assert_array_almost_equal(b[:, i], array([0, 128, 192]))
3
Example 89
Project: big_O Source File: test_big_o.py
def test_measure_execution_time(self):
def f(n):
time.sleep(0.1 * n)
return n
ns, t = big_o.measure_execution_time(f, datagen.n_,
min_n=1, max_n=5, n_measures=5,
n_repeats=1)
assert_array_equal(ns, np.arange(1, 6))
assert_array_almost_equal(t*10., np.arange(1, 6), 1)
3
Example 90
Project: fatiando Source File: test_tesseroid.py
def test_overwrite_density():
"gravmag.tesseroid uses given density instead of tesseroid property"
model = [Tesseroid(0, 1, 0, 1, 1000, -20000, {'density': 2670})]
density = -1000
other = [Tesseroid(0, 1, 0, 1, 1000, -20000, {'density': density})]
area = [-2, 2, -2, 2]
shape = (51, 51)
lon, lat, h = gridder.regular(area, shape, z=250000)
funcs = ['potential', 'gx', 'gy', 'gz', 'gxx', 'gxy', 'gxz', 'gyy', 'gyz',
'gzz']
for f in funcs:
correct = getattr(tesseroid, f)(lon, lat, h, other)
effect = getattr(tesseroid, f)(lon, lat, h, model, dens=density)
assert_array_almost_equal(correct, effect, 9, 'Failed %s' % (f))
3
Example 91
Project: metric-learn Source File: test_fit_transform.py
def test_lsml_supervised(self):
seed = np.random.RandomState(1234)
lsml = LSML_Supervised(num_constraints=200)
lsml.fit(self.X, self.y, random_state=seed)
res_1 = lsml.transform()
seed = np.random.RandomState(1234)
lsml = LSML_Supervised(num_constraints=200)
res_2 = lsml.fit_transform(self.X, self.y, random_state=seed)
assert_array_almost_equal(res_1, res_2)
3
Example 92
@pytest.mark.parametrize("func", func_list, ids=lambda x: getattr(x, '__name__', x))
def test_cmp(aggregate_cmp, func, decimal=14):
a = aggregate_cmp.nana if 'nan' in getattr(func, '__name__', func) else aggregate_cmp.a
res = aggregate_cmp.func(aggregate_cmp.group_idx, a, func=func)
ref = aggregate_cmp.func_ref(aggregate_cmp.group_idx, a, func=func)
np.testing.assert_array_almost_equal(res, ref, decimal=decimal)
0
Example 93
Project: pystruct Source File: test_latent_node_crf.py
def test_edge_feature_latent_node_crf_no_latent():
# no latent nodes
# Test inference with different weights in different directions
X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1, size_x=8)
x, y = X[0], Y[0]
n_states = x.shape[-1]
edge_list = make_grid_edges(x, 4, return_lists=True)
edges = np.vstack(edge_list)
pw_horz = -1 * np.eye(n_states + 5)
xx, yy = np.indices(pw_horz.shape)
# linear ordering constraint horizontally
pw_horz[xx > yy] = 1
# high cost for unequal labels vertically
pw_vert = -1 * np.eye(n_states + 5)
pw_vert[xx != yy] = 1
pw_vert *= 10
# generate edge weights
edge_weights_horizontal = np.repeat(pw_horz[np.newaxis, :, :],
edge_list[0].shape[0], axis=0)
edge_weights_vertical = np.repeat(pw_vert[np.newaxis, :, :],
edge_list[1].shape[0], axis=0)
edge_weights = np.vstack([edge_weights_horizontal, edge_weights_vertical])
# do inference
# pad x for hidden states...
x_padded = -100 * np.ones((x.shape[0], x.shape[1], x.shape[2] + 5))
x_padded[:, :, :x.shape[2]] = x
res = lp_general_graph(-x_padded.reshape(-1, n_states + 5), edges,
edge_weights)
edge_features = edge_list_to_features(edge_list)
x = (x.reshape(-1, n_states), edges, edge_features, 0)
y = y.ravel()
for inference_method in get_installed(["lp"]):
# same inference through CRF inferface
crf = EdgeFeatureLatentNodeCRF(n_labels=3,
inference_method=inference_method,
n_edge_features=2, n_hidden_states=5)
w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])
y_pred = crf.inference(x, w, relaxed=True)
assert_array_almost_equal(res[0], y_pred[0].reshape(-1, n_states + 5),
4)
assert_array_almost_equal(res[1], y_pred[1], 4)
assert_array_equal(y, np.argmax(y_pred[0], axis=-1))
for inference_method in get_installed(["qpbo", "ad3", "lp"])[:2]:
# again, this time discrete predictions only
crf = EdgeFeatureLatentNodeCRF(n_labels=3,
inference_method=inference_method,
n_edge_features=2, n_hidden_states=5)
w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])
y_pred = crf.inference(x, w, relaxed=False)
assert_array_equal(y, y_pred)
0
Example 94
Project: root_numpy Source File: tests.py
def test_rec2array():
# scalar fields
a = np.array([
(12345, 2., 2.1, True),
(3, 4., 4.2, False),],
dtype=[
('x', np.int32),
('y', np.float32),
('z', np.float64),
('w', np.bool)])
arr = rnp.rec2array(a)
assert_array_equal(arr,
np.array([
[12345, 2, 2.1, 1],
[3, 4, 4.2, 0]]))
arr = rnp.rec2array(a, fields=['x', 'y'])
assert_array_equal(arr,
np.array([
[12345, 2],
[3, 4]]))
# single scalar field
arr = rnp.rec2array(a, fields=['x'])
assert_array_equal(arr, np.array([[12345], [3]], dtype=np.int32))
# single scalar field simplified
arr = rnp.rec2array(a, fields='x')
assert_array_equal(arr, np.array([12345, 3], dtype=np.int32))
# case where array has single record
assert_equal(rnp.rec2array(a[:1]).shape, (1, 4))
assert_equal(rnp.rec2array(a[:1], fields=['x']).shape, (1, 1))
assert_equal(rnp.rec2array(a[:1], fields='x').shape, (1,))
# array fields
a = np.array([
([1, 2, 3], [4.5, 6, 9.5],),
([4, 5, 6], [3.3, 7.5, 8.4],),],
dtype=[
('x', np.int32, (3,)),
('y', np.float32, (3,))])
arr = rnp.rec2array(a)
assert_array_almost_equal(arr,
np.array([[[1, 4.5],
[2, 6],
[3, 9.5]],
[[4, 3.3],
[5, 7.5],
[6, 8.4]]]))
# lengths mismatch
a = np.array([
([1, 2], [4.5, 6, 9.5],),
([4, 5], [3.3, 7.5, 8.4],),],
dtype=[
('x', np.int32, (2,)),
('y', np.float32, (3,))])
assert_raises(ValueError, rnp.rec2array, a)
# single array field
arr = rnp.rec2array(a, fields=['y'])
assert_array_almost_equal(arr,
np.array([[[4.5], [6], [9.5]],
[[3.3], [7.5], [8.4]]]))
# single array field simplified
arr = rnp.rec2array(a, fields='y')
assert_array_almost_equal(arr,
np.array([[4.5, 6, 9.5],
[3.3, 7.5, 8.4]]))
# case where array has single record
assert_equal(rnp.rec2array(a[:1], fields=['y']).shape, (1, 3, 1))
assert_equal(rnp.rec2array(a[:1], fields='y').shape, (1, 3))
0
Example 95
Project: pyqtgraph Source File: test_functions.py
def test_interpolateArray():
def interpolateArray(data, x):
result = pg.interpolateArray(data, x)
assert result.shape == x.shape[:-1] + data.shape[x.shape[-1]:]
return result
data = np.array([[ 1., 2., 4. ],
[ 10., 20., 40. ],
[ 100., 200., 400.]])
# test various x shapes
interpolateArray(data, np.ones((1,)))
interpolateArray(data, np.ones((2,)))
interpolateArray(data, np.ones((1, 1)))
interpolateArray(data, np.ones((1, 2)))
interpolateArray(data, np.ones((5, 1)))
interpolateArray(data, np.ones((5, 2)))
interpolateArray(data, np.ones((5, 5, 1)))
interpolateArray(data, np.ones((5, 5, 2)))
with pytest.raises(TypeError):
interpolateArray(data, np.ones((3,)))
with pytest.raises(TypeError):
interpolateArray(data, np.ones((1, 3,)))
with pytest.raises(TypeError):
interpolateArray(data, np.ones((5, 5, 3,)))
x = np.array([[ 0.3, 0.6],
[ 1. , 1. ],
[ 0.5, 1. ],
[ 0.5, 2.5],
[ 10. , 10. ]])
result = interpolateArray(data, x)
#import scipy.ndimage
#spresult = scipy.ndimage.map_coordinates(data, x.T, order=1)
spresult = np.array([ 5.92, 20. , 11. , 0. , 0. ]) # generated with the above line
assert_array_almost_equal(result, spresult)
# test mapping when x.shape[-1] < data.ndim
x = np.array([[ 0.3, 0],
[ 0.3, 1],
[ 0.3, 2]])
r1 = interpolateArray(data, x)
x = np.array([0.3]) # should broadcast across axis 1
r2 = interpolateArray(data, x)
assert_array_almost_equal(r1, r2)
# test mapping 2D array of locations
x = np.array([[[0.5, 0.5], [0.5, 1.0], [0.5, 1.5]],
[[1.5, 0.5], [1.5, 1.0], [1.5, 1.5]]])
r1 = interpolateArray(data, x)
#r2 = scipy.ndimage.map_coordinates(data, x.transpose(2,0,1), order=1)
r2 = np.array([[ 8.25, 11. , 16.5 ], # generated with the above line
[ 82.5 , 110. , 165. ]])
assert_array_almost_equal(r1, r2)
# test interpolate where data.ndim > x.shape[1]
data = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) # 2x2x3
x = np.array([[1, 1], [0, 0.5], [5, 5]])
r1 = interpolateArray(data, x)
assert np.all(r1[0] == data[1, 1])
assert np.all(r1[1] == 0.5 * (data[0, 0] + data[0, 1]))
assert np.all(r1[2] == 0)
0
Example 96
Project: python-control Source File: test_control_matlab.py
@unittest.skip("skipping test_check_convert_shape, need to update test")
def test_check_convert_shape(self):
#TODO: check if shape is correct everywhere.
#Correct input ---------------------------------------------
#Recognize correct shape
#Input is array, shape (3,), single legal shape
arr = _check_convert_array(array([1., 2, 3]), [(3,)], 'Test: ')
assert isinstance(arr, np.ndarray)
assert not isinstance(arr, matrix)
#Input is array, shape (3,), two legal shapes
arr = _check_convert_array(array([1., 2, 3]), [(3,), (1,3)], 'Test: ')
assert isinstance(arr, np.ndarray)
assert not isinstance(arr, matrix)
#Input is array, 2D, shape (1,3)
arr = _check_convert_array(array([[1., 2, 3]]), [(3,), (1,3)], 'Test: ')
assert isinstance(arr, np.ndarray)
assert not isinstance(arr, matrix)
#Test special value any
#Input is array, 2D, shape (1,3)
arr = _check_convert_array(array([[1., 2, 3]]), [(4,), (1,"any")], 'Test: ')
assert isinstance(arr, np.ndarray)
assert not isinstance(arr, matrix)
#Input is array, 2D, shape (3,1)
arr = _check_convert_array(array([[1.], [2], [3]]), [(4,), ("any", 1)],
'Test: ')
assert isinstance(arr, np.ndarray)
assert not isinstance(arr, matrix)
#Convert array-like objects to arrays
#Input is matrix, shape (1,3), must convert to array
arr = _check_convert_array(matrix("1. 2 3"), [(3,), (1,3)], 'Test: ')
assert isinstance(arr, np.ndarray)
assert not isinstance(arr, matrix)
#Input is list, shape (1,3), must convert to array
arr = _check_convert_array([[1., 2, 3]], [(3,), (1,3)], 'Test: ')
assert isinstance(arr, np.ndarray)
assert not isinstance(arr, matrix)
#Special treatment of scalars and zero dimensional arrays:
#They are converted to an array of a legal shape, filled with the scalar
#value
arr = _check_convert_array(5, [(3,), (1,3)], 'Test: ')
assert isinstance(arr, np.ndarray)
assert arr.shape == (3,)
assert_array_almost_equal(arr, [5, 5, 5])
#Squeeze shape
#Input is array, 2D, shape (1,3)
arr = _check_convert_array(array([[1., 2, 3]]), [(3,), (1,3)],
'Test: ', squeeze=True)
assert isinstance(arr, np.ndarray)
assert not isinstance(arr, matrix)
assert arr.shape == (3,) #Shape must be squeezed. (1,3) -> (3,)
#Erroneous input -----------------------------------------------------
#test wrong element data types
#Input is array of functions, 2D, shape (1,3)
self.assertRaises(TypeError, _check_convert_array(array([[min, max, all]]),
[(3,), (1,3)], 'Test: ', squeeze=True))
#Test wrong shapes
#Input has shape (4,) but (3,) or (1,3) are legal shapes
self.assertRaises(ValueError, _check_convert_array(array([1., 2, 3, 4]),
[(3,), (1,3)], 'Test: '))
0
Example 97
def test_euclidean_distances():
"""Check that the pairwise euclidian distances computation"""
#Idepontent Test
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
D = euclidean_distances(X, X)
assert_array_almost_equal(D, [[0.]])
X = [[3.0, -2.0]]
D = euclidean_distances(X, X, inverse=True)
assert_array_almost_equal(D, [[1.]])
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
D = euclidean_distances(X, X, inverse=False)
assert_array_almost_equal(D, [[0.]])
#Inverse Test
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
D = euclidean_distances(X, X, inverse=True)
assert_array_almost_equal(D, [[1.]])
#Vector x Non Vector
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[]]
assert_raises(ValueError, euclidean_distances, X, Y)
#Vector A x Vector B
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[3.0, 3.5, 1.5, 5.0, 3.5, 3.0]]
D = euclidean_distances(X, Y)
assert_array_almost_equal(D, [[2.39791576]])
#Inverse vector (mahout check)
X = [[3.0, -2.0]]
Y = [[-3.0, 2.0]]
D = euclidean_distances(X, Y, inverse=True)
assert_array_almost_equal(D, [[0.13736056]])
#Inverse vector (oreilly check)
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[3.0, 3.5, 1.5, 5.0, 3.5, 3.0]]
D = euclidean_distances(X, Y, inverse=True, squared=True)
assert_array_almost_equal(D, [[0.14814815]])
#Vector N x 1
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0], [2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[3.0, 3.5, 1.5, 5.0, 3.5, 3.0]]
D = euclidean_distances(X, Y)
assert_array_almost_equal(D, [[2.39791576], [2.39791576]])
#N-Dimmensional Vectors
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0], [2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[3.0, 3.5, 1.5, 5.0, 3.5, 3.0], [2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
D = euclidean_distances(X, Y)
assert_array_almost_equal(D, [[2.39791576, 0.], [2.39791576, 0.]])
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0], [3.0, 3.5, 1.5, 5.0, 3.5, 3.0]]
D = euclidean_distances(X, X)
assert_array_almost_equal(D, [[0., 2.39791576], [2.39791576, 0.]])
X = [[1.0, 0.0], [1.0, 1.0]]
Y = [[0.0, 0.0]]
D = euclidean_distances(X, Y)
assert_array_almost_equal(D, [[1.], [1.41421356]])
#Test Sparse Matrices
X = csr_matrix(X)
Y = csr_matrix(Y)
D = euclidean_distances(X, Y)
assert_array_almost_equal(D, [[1.], [1.41421356]])
0
Example 98
Project: pykalman Source File: test_standard.py
def test_kalman_filter_update(self):
kf = self.KF(
self.data.transition_matrix,
self.data.observation_matrix,
self.data.transition_covariance,
self.data.observation_covariance,
self.data.transition_offsets,
self.data.observation_offset,
self.data.initial_state_mean,
self.data.initial_state_covariance)
# use Kalman Filter
(x_filt, V_filt) = kf.filter(X=self.data.observations)
# use online Kalman Filter
n_timesteps = self.data.observations.shape[0]
n_dim_obs, n_dim_state = self.data.observation_matrix.shape
kf2 = self.KF(n_dim_state=n_dim_state, n_dim_obs=n_dim_obs)
x_filt2 = np.zeros((n_timesteps, n_dim_state))
V_filt2 = np.zeros((n_timesteps, n_dim_state, n_dim_state))
for t in range(n_timesteps - 1):
if t == 0:
x_filt2[0] = self.data.initial_state_mean
V_filt2[0] = self.data.initial_state_covariance
(x_filt2[t + 1], V_filt2[t + 1]) = kf2.filter_update(
x_filt2[t], V_filt2[t],
observation=self.data.observations[t + 1],
transition_matrix=self.data.transition_matrix,
transition_offset=self.data.transition_offsets[t],
transition_covariance=self.data.transition_covariance,
observation_matrix=self.data.observation_matrix,
observation_offset=self.data.observation_offset,
observation_covariance=self.data.observation_covariance
)
assert_array_almost_equal(x_filt, x_filt2)
assert_array_almost_equal(V_filt, V_filt2)
0
Example 99
Project: pystruct Source File: test_edge_feature_graph_crf.py
def test_inference():
# Test inference with different weights in different directions
X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1)
x, y = X[0], Y[0]
n_states = x.shape[-1]
edge_list = make_grid_edges(x, 4, return_lists=True)
edges = np.vstack(edge_list)
pw_horz = -1 * np.eye(n_states)
xx, yy = np.indices(pw_horz.shape)
# linear ordering constraint horizontally
pw_horz[xx > yy] = 1
# high cost for unequal labels vertically
pw_vert = -1 * np.eye(n_states)
pw_vert[xx != yy] = 1
pw_vert *= 10
# generate edge weights
edge_weights_horizontal = np.repeat(pw_horz[np.newaxis, :, :],
edge_list[0].shape[0], axis=0)
edge_weights_vertical = np.repeat(pw_vert[np.newaxis, :, :],
edge_list[1].shape[0], axis=0)
edge_weights = np.vstack([edge_weights_horizontal, edge_weights_vertical])
# do inference
res = lp_general_graph(-x.reshape(-1, n_states), edges, edge_weights)
edge_features = edge_list_to_features(edge_list)
x = (x.reshape(-1, n_states), edges, edge_features)
y = y.ravel()
for inference_method in get_installed(["lp", "ad3"]):
# same inference through CRF inferface
crf = EdgeFeatureGraphCRF(inference_method=inference_method)
crf.initialize([x], [y])
w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])
y_pred = crf.inference(x, w, relaxed=True)
if isinstance(y_pred, tuple):
# ad3 produces an integer result if it found the exact solution
assert_array_almost_equal(res[1], y_pred[1])
assert_array_almost_equal(res[0], y_pred[0].reshape(-1, n_states))
assert_array_equal(y, np.argmax(y_pred[0], axis=-1))
for inference_method in get_installed(["lp", "ad3", "qpbo"]):
# again, this time discrete predictions only
crf = EdgeFeatureGraphCRF(n_states=3,
inference_method=inference_method,
n_edge_features=2)
crf.initialize([x], [y])
w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()])
y_pred = crf.inference(x, w, relaxed=False)
assert_array_equal(y, y_pred)
0
Example 100
Project: crab Source File: test_pairwise.py
def test_adjusted_cosine():
""" Check that the pairwise Pearson distances computation"""
#Idepontent Test
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
EFV = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
D = adjusted_cosine(X, X, EFV)
assert_array_almost_equal(D, [[1.]])
#Vector x Non Vector
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[]]
EFV = [[]]
assert_raises(ValueError, adjusted_cosine, X, Y, EFV)
#Vector A x Vector B
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[3.0, 3.5, 1.5, 5.0, 3.5, 3.0]]
EFV = [[2.0, 2.0, 2.0, 2.0, 2.0, 2.0]]
D = adjusted_cosine(X, Y, EFV)
assert_array_almost_equal(D, [[0.80952381]])
#Vector N x 1
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0], [2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[3.0, 3.5, 1.5, 5.0, 3.5, 3.0]]
EFV = [[2.0, 2.0, 2.0, 2.0, 2.0, 2.0]]
D = adjusted_cosine(X, Y, EFV)
assert_array_almost_equal(D, [[0.80952381], [0.80952381]])
#N-Dimmensional Vectors
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0], [2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
Y = [[3.0, 3.5, 1.5, 5.0, 3.5, 3.0], [2.5, 3.5, 3.0, 3.5, 2.5, 3.0]]
EFV = [[2.0, 2.0, 2.0, 2.0, 2.0, 2.0]]
D = adjusted_cosine(X, Y, EFV)
assert_array_almost_equal(D, [[0.80952381, 1.], [0.80952381, 1.]])
X = [[2.5, 3.5, 3.0, 3.5, 2.5, 3.0], [3.0, 3.5, 1.5, 5.0, 3.5, 3.0]]
EFV = [[2.0, 2.0, 2.0, 2.0, 2.0, 2.0]]
D = adjusted_cosine(X, X, EFV)
assert_array_almost_equal(D, [[1., 0.80952381], [0.80952381, 1.]])
X = [[1.0, 0.0], [1.0, 1.0]]
Y = [[0.0, 0.0]]
EFV = [[0.0, 0.0]]
D = adjusted_cosine(X, Y, EFV)
assert_array_almost_equal(D, [[np.nan], [np.nan]])
#Test Sparse Matrices
X = csr_matrix(X)
Y = csr_matrix(Y)
EFV = csr_matrix(EFV)
assert_raises(ValueError, adjusted_cosine, X, Y, EFV)