Python numpy.c_() Examples
The following are 30
code examples of numpy.c_().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: 1logistic_regression.py From Fundamentals-of-Machine-Learning-with-scikit-learn with MIT License | 7 votes |
def show_classification_areas(X, Y, lr): x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02)) Z = lr.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.figure(1, figsize=(30, 25)) plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Pastel1) # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=np.abs(Y - 1), edgecolors='k', cmap=plt.cm.coolwarm) plt.xlabel('X') plt.ylabel('Y') plt.xlim(xx.min(), xx.max()) plt.ylim(yy.min(), yy.max()) plt.xticks(()) plt.yticks(()) plt.show()
Example #2
Source File: test_representation.py From vnpy_crypto with MIT License | 6 votes |
def setup_class(cls, dtype=float, nforecast=100, conserve_memory=0): super(Clark1989Forecast, cls).setup_class( dtype=dtype, conserve_memory=conserve_memory ) cls.nforecast = nforecast # Add missing observations to the end (to forecast) cls.model.endog = np.array( np.c_[ cls.model.endog, np.r_[[np.nan, np.nan]*nforecast].reshape(2, nforecast) ], ndmin=2, dtype=dtype, order="F" ) cls.model.nobs = cls.model.endog.shape[1] cls.results = cls.run_filter()
Example #3
Source File: twf.py From sprocket with MIT License | 6 votes |
def align_data(org_data, tar_data, twf): """Get aligned joint feature vector Paramters --------- orgdata : array, shape (`T_org`, `dim_org`) Acoustic feature vector of original speaker tardata : array, shape (`T_tar`, `dim_tar`) Acoustic feature vector of target speaker twf : array, shape (`2`, `T`) Time warping function between original and target Returns ------- jdata : array, shape (`T_new` `dim_org + dim_tar`) Joint feature vector between source and target """ jdata = np.c_[org_data[twf[0]], tar_data[twf[1]]] return jdata
Example #4
Source File: delta.py From sprocket with MIT License | 6 votes |
def static_delta(data, win=[-1.0, 1.0, 0]): """Calculate static and delta component Parameters ---------- data : array, shape (`T`, `dim`) Array of static matrix sequence. win: array, optional, shape (`3`) The shape of window matrix. Default set to [-1.0, 1.0, 0]. Returns ------- sddata: array, shape (`T`, `dim*2`) Array static and delta matrix sequence. """ sddata = np.c_[data, delta(data, win)] return sddata
Example #5
Source File: test_diagGMM.py From sprocket with MIT License | 6 votes |
def test_blockdiag_GMM_train_and_convert(self): jnt = np.random.rand(100, 20) gmm_tr = GMMTrainer(n_mix=4, n_iter=100, covtype='block_diag') gmm_tr.train(jnt) gmm_cv = GMMConvertor( n_mix=4, covtype='block_diag', gmmmode=None) gmm_cv.open_from_param(gmm_tr.param) data = np.random.rand(200, 5) sddata = np.c_[data, delta(data)] odata = gmm_cv.convert(sddata, cvtype='mlpg') odata = gmm_cv.convert(sddata, cvtype='mmse') assert data.shape == odata.shape # test for singlepath Ajnt = np.random.rand(100, 120) Bjnt = np.random.rand(100, 140) gmm_tr.estimate_responsibility(jnt) Aparam = gmm_tr.train_singlepath(Ajnt) Bparam = gmm_tr.train_singlepath(Bjnt) assert np.allclose(Aparam.weights_, Bparam.weights_)
Example #6
Source File: test_GMM.py From sprocket with MIT License | 6 votes |
def test_GMM_train_and_convert(self): jnt = np.random.rand(100, 20) gmm_tr = GMMTrainer(n_mix=4, n_iter=100, covtype='full') gmm_tr.train(jnt) data = np.random.rand(200, 5) sddata = np.c_[data, delta(data)] gmm_cv = GMMConvertor( n_mix=4, covtype='full', gmmmode=None) gmm_cv.open_from_param(gmm_tr.param) odata = gmm_cv.convert(sddata, cvtype='mlpg') odata = gmm_cv.convert(sddata, cvtype='mmse') assert data.shape == odata.shape # test for singlepath Ajnt = np.random.rand(100, 120) Bjnt = np.random.rand(100, 140) gmm_tr.estimate_responsibility(jnt) Aparam = gmm_tr.train_singlepath(Ajnt) Bparam = gmm_tr.train_singlepath(Bjnt) assert np.allclose(Aparam.weights_, Bparam.weights_)
Example #7
Source File: astra2ocelot.py From ocelot with GNU General Public License v3.0 | 6 votes |
def exact_xxstg_2_xp_de(xxstg, gamref): # dE/E0 N = len(xxstg) / 6 xp = np.zeros((N, 6)) pref = m_e_eV * np.sqrt(gamref ** 2 - 1) gamma = gamref * (1 + xxstg[5::6]) beta = np.sqrt(1 - gamma ** -2) u = np.c_[xxstg[1::6], xxstg[3::6], np.ones(N)] if np.__version__ > "1.8": norm = np.linalg.norm(u, 2, 1).reshape((N, 1)) else: norm = np.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2 + u[:, 2] ** 2).reshape((N, 1)) u = u / norm xp[:, 0] = xxstg[0::6] - u[:, 0] * beta * xxstg[4::6] xp[:, 1] = xxstg[2::6] - u[:, 1] * beta * xxstg[4::6] xp[:, 2] = -u[:, 2] * beta * xxstg[4::6] xp[:, 3] = u[:, 0] * gamma * beta * m_e_eV xp[:, 4] = u[:, 1] * gamma * beta * m_e_eV xp[:, 5] = u[:, 2] * gamma * beta * m_e_eV - pref return xp
Example #8
Source File: test_index_tricks.py From mars with Apache License 2.0 | 6 votes |
def testC_(self): r = mt.c_[mt.array([1, 2, 3]), mt.array([4, 5, 6])] result = self.executor.execute_tensor(r, concat=True)[0] expected = np.c_[np.array([1, 2, 3]), np.array([4, 5, 6])] np.testing.assert_array_equal(result, expected) r = mt.c_[mt.array([[1, 2, 3]]), 0, 0, mt.array([[4, 5, 6]])] result = self.executor.execute_tensor(r, concat=True)[0] expected = np.c_[np.array([[1, 2, 3]]), 0, 0, np.array([[4, 5, 6]])] np.testing.assert_array_equal(result, expected) r = mt.c_[:3, 1:4] result = self.executor.execute_tensor(r, concat=True)[0] expected = np.c_[:3, 1:4] np.testing.assert_array_equal(result, expected)
Example #9
Source File: test_transformations.py From pybids with MIT License | 6 votes |
def test_orthogonalize_dense(collection): transform.Factor(collection, 'trial_type', sep=sep) sampling_rate = collection.sampling_rate # Store pre-orth variables needed for tests pg_pre = collection['trial_type/parametric gain'].to_dense(sampling_rate) rt = collection['RT'].to_dense(sampling_rate) # Orthogonalize and store result transform.Orthogonalize(collection, variables='trial_type/parametric gain', other='RT', dense=True, groupby=['run', 'subject']) pg_post = collection['trial_type/parametric gain'] # Verify that the to_dense() calls result in identical indexing ent_cols = ['subject', 'run'] assert pg_pre.to_df()[ent_cols].equals(rt.to_df()[ent_cols]) assert pg_post.to_df()[ent_cols].equals(rt.to_df()[ent_cols]) vals = np.c_[rt.values, pg_pre.values, pg_post.values] df = pd.DataFrame(vals, columns=['rt', 'pre', 'post']) groupby = rt.get_grouper(['run', 'subject']) pre_r = df.groupby(groupby).apply(lambda x: x.corr().iloc[0, 1]) post_r = df.groupby(groupby).apply(lambda x: x.corr().iloc[0, 2]) assert (pre_r > 0.2).any() assert (post_r < 0.0001).all()
Example #10
Source File: astra2ocelot.py From ocelot with GNU General Public License v3.0 | 6 votes |
def exact_xp_2_xxstg_de(xp, gamref): # dE/E0 N = xp.shape[0] xxstg = np.zeros((N, 6)) pref = m_e_eV * np.sqrt(gamref ** 2 - 1) u = np.c_[xp[:, 3], xp[:, 4], xp[:, 5] + pref] gamma = np.sqrt(1 + np.sum(u * u, 1) / m_e_eV ** 2) beta = np.sqrt(1 - gamma ** -2) if np.__version__ > "1.8": p0 = np.linalg.norm(u, 2, 1).reshape((N, 1)) else: p0 = np.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2 + u[:, 2] ** 2).reshape((N, 1)) u = u / p0 cdt = -xp[:, 2] / (beta * u[:, 2]) xxstg[:, 0] = xp[:, 0] + beta * u[:, 0] * cdt xxstg[:, 2] = xp[:, 1] + beta * u[:, 1] * cdt xxstg[:, 4] = cdt xxstg[:, 1] = u[:, 0] / u[:, 2] xxstg[:, 3] = u[:, 1] / u[:, 2] xxstg[:, 5] = gamma / gamref - 1 return xxstg
Example #11
Source File: DataModule.py From sgd-influence with MIT License | 6 votes |
def fetch(self, n_tr, n_val, n_test, seed=0): x, y = self.load() # split data x_tr, x_val, y_tr, y_val = train_test_split( x, y, train_size=n_tr, test_size=n_val+n_test, random_state=seed) x_val, x_test, y_val, y_test = train_test_split( x_val, y_val, train_size=n_val, test_size=n_test, random_state=seed+1) # process x if self.normalize: scaler = StandardScaler() scaler.fit(x_tr) x_tr = scaler.transform(x_tr) x_val = scaler.transform(x_val) x_test = scaler.transform(x_test) if self.append_one: x_tr = np.c_[x_tr, np.ones(n_tr)] x_val = np.c_[x_val, np.ones(n_val)] x_test = np.c_[x_test, np.ones(n_test)] return (x_tr, y_tr), (x_val, y_val), (x_test, y_test)
Example #12
Source File: astra2ocelot.py From ocelot with GNU General Public License v3.0 | 6 votes |
def exact_xp_2_xxstg_dp(xp, gamref): # dp/p0 N = xp.shape[0] xxstg = np.zeros((N, 6)) pref = m_e_eV * np.sqrt(gamref ** 2 - 1) u = np.c_[xp[:, 3], xp[:, 4], xp[:, 5] + pref] gamma = np.sqrt(1 + np.sum(u * u, 1) / m_e_eV ** 2) beta = np.sqrt(1 - gamma ** -2) if np.__version__ > "1.8": p0 = np.linalg.norm(u, 2, 1).reshape((N, 1)) else: p0 = np.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2 + u[:, 2] ** 2).reshape((N, 1)) u = u / p0 cdt = -xp[:, 2] / (beta * u[:, 2]) xxstg[:, 0] = xp[:, 0] + beta * u[:, 0] * cdt xxstg[:, 2] = xp[:, 1] + beta * u[:, 1] * cdt xxstg[:, 4] = cdt xxstg[:, 1] = u[:, 0] / u[:, 2] xxstg[:, 3] = u[:, 1] / u[:, 2] xxstg[:, 5] = p0.reshape(N) / pref - 1 return xxstg
Example #13
Source File: test_tools.py From vnpy_crypto with MIT License | 6 votes |
def test_cases(self): # Basic cases for series, diff, seasonal_diff, seasonal_periods, result in self.cases: # Test numpy array x = tools.diff(series, diff, seasonal_diff, seasonal_periods) assert_almost_equal(x, result) # Test as Pandas Series series = pd.Series(series) # Rewrite to test as n-dimensional array series = np.c_[series, series] result = np.c_[result, result] # Test Numpy array x = tools.diff(series, diff, seasonal_diff, seasonal_periods) assert_almost_equal(x, result) # Test as Pandas Dataframe series = pd.DataFrame(series) x = tools.diff(series, diff, seasonal_diff, seasonal_periods) assert_almost_equal(x, result)
Example #14
Source File: astra2ocelot.py From ocelot with GNU General Public License v3.0 | 6 votes |
def exact_xxstg_2_xp_mad(xxstg, gamref): # from mad format N = int(xxstg.size / 6) xp = np.zeros((N, 6)) pref = m_e_eV * np.sqrt(gamref ** 2 - 1) betaref = np.sqrt(1 - gamref ** -2) gamma = (betaref * xxstg[5] + 1) * gamref beta = np.sqrt(1 - gamma ** -2) pz2pref = np.sqrt(((gamma * beta) / (gamref * betaref)) ** 2 - xxstg[1] ** 2 - xxstg[3] ** 2) u = np.c_[xxstg[1] / pz2pref, xxstg[3] / pz2pref, np.ones(N)] if np.__version__ > "1.8": norm = np.linalg.norm(u, 2, 1).reshape((N, 1)) else: norm = np.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2 + u[:, 2] ** 2).reshape((N, 1)) u = u / norm xp[:, 0] = xxstg[0] - u[:, 0] * beta * xxstg[4] xp[:, 1] = xxstg[2] - u[:, 1] * beta * xxstg[4] xp[:, 2] = -u[:, 2] * beta * xxstg[4] xp[:, 3] = u[:, 0] * gamma * beta * m_e_eV xp[:, 4] = u[:, 1] * gamma * beta * m_e_eV xp[:, 5] = u[:, 2] * gamma * beta * m_e_eV - pref return xp
Example #15
Source File: test_kalman.py From vnpy_crypto with MIT License | 6 votes |
def setup_class(cls, dtype=float, nforecast=100, conserve_memory=0): super(Clark1989Forecast, cls).setup_class(dtype, conserve_memory) cls.nforecast = nforecast # Add missing observations to the end (to forecast) cls._obs = cls.obs cls.obs = np.array( np.c_[ cls._obs, np.r_[[np.nan, np.nan]*nforecast].reshape(2, nforecast) ], ndmin=2, dtype=dtype, order="F" ) cls.model, cls.filter = cls.init_filter() cls.result = cls.run_filter()
Example #16
Source File: astra2ocelot.py From ocelot with GNU General Public License v3.0 | 6 votes |
def exact_xp_2_xxstg_mad(xp, gamref): # to mad format N = xp.shape[0] xxstg = np.zeros((N, 6)) pref = m_e_eV * np.sqrt(gamref ** 2 - 1) u = np.c_[xp[:, 3], xp[:, 4], xp[:, 5] + pref] gamma = np.sqrt(1 + np.sum(u * u, 1) / m_e_eV ** 2) beta = np.sqrt(1 - gamma ** -2) betaref = np.sqrt(1 - gamref ** -2) if np.__version__ > "1.8": p0 = np.linalg.norm(u, 2, 1).reshape((N, 1)) else: p0 = np.sqrt(u[:, 0] ** 2 + u[:, 1] ** 2 + u[:, 2] ** 2).reshape((N, 1)) u = u / p0 cdt = -xp[:, 2] / (beta * u[:, 2]) xxstg[:, 0] = xp[:, 0] + beta * u[:, 0] * cdt xxstg[:, 2] = xp[:, 1] + beta * u[:, 1] * cdt xxstg[:, 4] = cdt xxstg[:, 1] = xp[:, 3] / pref xxstg[:, 3] = xp[:, 4] / pref xxstg[:, 5] = (gamma / gamref - 1) / betaref return xxstg
Example #17
Source File: elm.py From Python-ELM with MIT License | 6 votes |
def _add_bias(self, X): """add bias to list Args: x_vs [[float]] Array: vec to add bias Returns: [float]: added vec Examples: >>> e = ELM(10, 3) >>> e._add_bias(np.array([[1,2,3], [1,2,3]])) array([[1., 2., 3., 1.], [1., 2., 3., 1.]]) """ return np.c_[X, np.ones(X.shape[0])]
Example #18
Source File: estimate_pose.py From centerpose with MIT License | 6 votes |
def compute_similarity_transform(points_static, points_to_transform): # http://nghiaho.com/?page_id=671 p0 = np.copy(points_static).T p1 = np.copy(points_to_transform).T t0 = -np.mean(p0, axis=1).reshape(3, 1) t1 = -np.mean(p1, axis=1).reshape(3, 1) t_final = t1 - t0 p0c = p0 + t0 p1c = p1 + t1 covariance_matrix = p0c.dot(p1c.T) U, S, V = np.linalg.svd(covariance_matrix) R = U.dot(V) if np.linalg.det(R) < 0: R[:, 2] *= -1 rms_d0 = np.sqrt(np.mean(np.linalg.norm(p0c, axis=0) ** 2)) rms_d1 = np.sqrt(np.mean(np.linalg.norm(p1c, axis=0) ** 2)) s = (rms_d0 / rms_d1) P = np.c_[s * np.eye(3).dot(R), t_final] return P
Example #19
Source File: estimate_pose.py From LipReading with MIT License | 6 votes |
def compute_similarity_transform(points_static, points_to_transform): #http://nghiaho.com/?page_id=671 p0 = np.copy(points_static).T p1 = np.copy(points_to_transform).T t0 = -np.mean(p0, axis=1).reshape(3,1) t1 = -np.mean(p1, axis=1).reshape(3,1) t_final = t1 -t0 p0c = p0+t0 p1c = p1+t1 covariance_matrix = p0c.dot(p1c.T) U,S,V = np.linalg.svd(covariance_matrix) R = U.dot(V) if np.linalg.det(R) < 0: R[:,2] *= -1 rms_d0 = np.sqrt(np.mean(np.linalg.norm(p0c, axis=0)**2)) rms_d1 = np.sqrt(np.mean(np.linalg.norm(p1c, axis=0)**2)) s = (rms_d0/rms_d1) P = np.c_[s*np.eye(3).dot(R), t_final] return P
Example #20
Source File: test_dynamic_factor.py From vnpy_crypto with MIT License | 5 votes |
def test_predict(self): exog = np.c_[np.ones((16, 1)), (np.arange(75, 75+16) + 2)[:, np.newaxis]] super(TestSUR, self).test_predict(exog=exog)
Example #21
Source File: test_dynamic_factor.py From vnpy_crypto with MIT License | 5 votes |
def test_predict(self): exog = np.c_[np.ones((16, 1)), (np.arange(75, 75+16) + 2)[:, np.newaxis]] super(TestDynamicFactor_exog2, self).test_predict(exog=exog)
Example #22
Source File: test_dynamic_factor.py From vnpy_crypto with MIT License | 5 votes |
def setup_class(cls): true = results_dynamic_factor.lutkepohl_sur.copy() true['predict'] = output_results.iloc[1:][['predict_sur_1', 'predict_sur_2', 'predict_sur_3']] true['dynamic_predict'] = output_results.iloc[1:][['dyn_predict_sur_1', 'dyn_predict_sur_2', 'dyn_predict_sur_3']] exog = np.c_[np.ones((75,1)), (np.arange(75) + 2)[:, np.newaxis]] super(TestSUR, cls).setup_class(true, k_factors=0, factor_order=0, exog=exog, error_cov_type='unstructured')
Example #23
Source File: test_dynamic_factor.py From vnpy_crypto with MIT License | 5 votes |
def test_dynamic_predict(self): exog = np.c_[np.ones((16, 1)), (np.arange(75, 75+16) + 2)[:, np.newaxis]] super(TestDynamicFactor_exog2, self).test_dynamic_predict(exog=exog)
Example #24
Source File: test_data.py From vnpy_crypto with MIT License | 5 votes |
def setup_class(cls): super(TestArrays2dEndog, cls).setup_class() cls.endog = np.random.random((10,1)) cls.exog = np.c_[np.ones(10), np.random.random((10,2))] cls.data = sm_data.handle_data(cls.endog, cls.exog) #cls.endog = endog.squeeze()
Example #25
Source File: plot_robust_classification_toy.py From scikit-learn-extra with BSD 3-Clause "New" or "Revised" License | 5 votes |
def plot_classif(clf, X, y, ax): x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5 y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5 h = 0.02 # step size in the mesh xx, yy = np.meshgrid( np.arange(x_min, x_max, h), np.arange(y_min, y_max, h) ) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) ax.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired) ax.scatter(X[:, 0], X[:, 1], c=y)
Example #26
Source File: twod_mjc_env.py From imitation with MIT License | 5 votes |
def plot_maps(combined_list=None, *heatmaps): import matplotlib.pyplot as plt combined = np.c_[heatmaps] if combined_list is not None: combined_list.append(combined) combined = np.concatenate(combined_list) else: combined_list = [] plt.figure() plt.imshow(combined, cmap="afmhot", interpolation="none") plt.show() return combined_list
Example #27
Source File: wave.py From ocelot with GNU General Public License v3.0 | 5 votes |
def save_trf(trf, attr, flePath): if hasattr(trf, attr): filt = getattr(trf, attr) else: raise ValueError('no attribute', attr, 'in fransfer function') f = open(flePath, 'wb') header = 'Energy[eV] Filter_Abs Filter_Ang' np.savetxt(f, np.c_[trf.ev(), np.abs(trf.tr), np.angle(trf.tr)], header=header, fmt="%.8e", newline='\n', comments='') f.close()
Example #28
Source File: xfel_utils.py From ocelot with GNU General Public License v3.0 | 5 votes |
def save_xhrss_dump_proj(dump_proj, filePath): # saves the dfl_hxrss_filt radiation projections dump to text files (t_l_scale, _, t_l_int_a, t_l_pha_a), (f_l_scale, f_l_filt, _, f_l_int_a) = dump_proj f = open(filePath + '.t.txt', 'wb') header = 'Distance Power Phase' np.savetxt(f, np.c_[t_l_scale, t_l_int_a, t_l_pha_a], header=header, fmt="%e", newline='\n', comments='') f.close() f = open(filePath + '.f.txt', 'wb') header = 'Wavelength Spectrum Filter_Abs Filter_Ang' np.savetxt(f, np.c_[f_l_scale, f_l_int_a, np.abs(f_l_filt), np.unwrap(np.angle(f_l_filt))], header=header, fmt="%.8e", newline='\n', comments='') f.close()
Example #29
Source File: iou_matching.py From centerpose with MIT License | 5 votes |
def iou(bbox, candidates): """Computer intersection over union. Parameters ---------- bbox : ndarray A bounding box in format `(top left x, top left y, width, height)`. candidates : ndarray A matrix of candidate bounding boxes (one per row) in the same format as `bbox`. Returns ------- ndarray The intersection over union in [0, 1] between the `bbox` and each candidate. A higher score means a larger fraction of the `bbox` is occluded by the candidate. """ bbox_tl, bbox_br = bbox[:2], bbox[:2] + bbox[2:] candidates_tl = candidates[:, :2] candidates_br = candidates[:, :2] + candidates[:, 2:] tl = np.c_[np.maximum(bbox_tl[0], candidates_tl[:, 0])[:, np.newaxis], np.maximum(bbox_tl[1], candidates_tl[:, 1])[:, np.newaxis]] br = np.c_[np.minimum(bbox_br[0], candidates_br[:, 0])[:, np.newaxis], np.minimum(bbox_br[1], candidates_br[:, 1])[:, np.newaxis]] wh = np.maximum(0., br - tl) area_intersection = wh.prod(axis=1) area_bbox = bbox[2:].prod() area_candidates = candidates[:, 2:].prod(axis=1) return area_intersection / (area_bbox + area_candidates - area_intersection)
Example #30
Source File: test_index_tricks.py From auto-alt-text-lambda-api with MIT License | 5 votes |
def test_c_(): a = np.c_[np.array([[1, 2, 3]]), 0, 0, np.array([[4, 5, 6]])] assert_equal(a, [[1, 2, 3, 0, 0, 4, 5, 6]])