def test_shape_and_dtype(self):
sizes = (4, 5, 3, 2)
# Test both lists and arrays
for func in (range, np.arange):
arrays = np.ix_(*[func(sz) for sz in sizes])
for k, (a, sz) in enumerate(zip(arrays, sizes)):
assert_equal(a.shape[k], sz)
assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k))
assert_(np.issubdtype(a.dtype, int))
python类ix_()的实例源码
def test_bool(self):
bool_a = [True, False, True, True]
int_a, = np.nonzero(bool_a)
assert_equal(np.ix_(bool_a)[0], int_a)
def test_1d_only(self):
idx2d = [[1, 2, 3], [4, 5, 6]]
assert_raises(ValueError, np.ix_, idx2d)
def _compute_log_likelihood(self, X):
seq_len = X.shape[0]
n_states = self.n_components
n_dim = X.shape[1]
p = np.zeros((seq_len,n_states))
for i in range(seq_len):
miss = np.isnan(X[i])
p[i] = np.sum(miss * np.log(self.miss_probs_) + (1-miss) * np.log(1-self.miss_probs_), axis=1)
if not np.all(miss):
for state in range(n_states):
mean = self.means_[state][miss==0]
cov = self.covars_[state][np.ix_(miss==0,miss==0)]
p[i][state] = p[i][state] + np.log(multivariate_normal.pdf(X[i][miss==0],mean=mean,cov=cov))
return p
def split_data(self, X, y, i):
sub_dict = {}
unique_val = np.unique(X[:, i])
c = range(i) + range(i + 1, X.shape[1])
for val in unique_val:
indice = np.where(X[:, i] == val)[0]
# print indice.shape
sub_dict[val] = (X[np.ix_(indice, c)], y[indice])
return sub_dict # sub_data, sub_target
def _extract_pairwise(self, X, y, n, is_train=True):
if self.cache is not None and (n, True, is_train) in self.cache:
return self.cache[n, True, is_train]
if not hasattr(X, "shape"):
raise ValueError("Precomputed kernels or affinity matrices have "
"to be passed as arrays or sparse matrices.")
if X.shape[0] != X.shape[1]:
raise ValueError("X should be a square kernel matrix")
train, test = self.splits[n]
result = X[np.ix_(train if is_train else test, train)]
if self.cache is not None:
self.cache[n, True, is_train] = result
return result
def compute_new_medoid(self,cluster, distances):
mask = np.ones(distances.shape)
mask[np.ix_(cluster,cluster)] = 0.
cluster_distances = np.ma.masked_array(data=distances, mask=mask, fill_value=10e9)
costs = cluster_distances.sum(axis=1)
return costs.argmin(axis=0, fill_value=10e9)
def get_global_stiffness(self,msz):
pass
#~ ni, nj = self.get_nodes()
#~ self.keg = np.zeros((msz,msz))
#~ idx = np.ix_([ni.label, nj.label],[ni.label, nj.label])
#~ row = np.array([ni.label, ni.label, nj.label, nj.label])
#~ col = np.array([ni.label, nj.label, ni.label, nj.label])
#~ data = self.get_element_stiffness().reshape(-1)
#~ print data, row, col
#~ self.keg = csr_matrix((data, (row, col)), shape=(msz,msz)).toarray()
#~ return self.keg
def generate_permutation_matrix():
P = np.zeros((2**15,2**15),dtype=np.uint8)
for a in range(2):
for b in range(2):
for c in range(2):
for d in range(2):
for e in range(2):
for f in range(2):
for g in range(2):
for h in range(2):
for i in range(2):
for j in range(2):
for k in range(2):
for l in range(2):
for m in range(2):
for n in range(2):
for o in range(2):
A = np.array([[0,a,b,c,d,e],[a,0,f,g,h,i],[b,f,0,j,k,l],[c,g,j,0,m,n],[d,h,k,m,0,o],[e,i,l,n,o,0]])
perms = multiset_permutations(np.array(range(6),dtype=np.uint8))
Per = np.zeros((factorial(6),6),dtype=np.uint8)
ind = 0
for permutation in perms:
Per[ind,:] = permutation
ind += 1
for p in range(factorial(6)):
A_per = A[np.ix_(Per[p,:],Per[p,:])]
P[graphlet_type(A), graphlet_type(A_per)] = 1
return P
def MakeEquationSystem_mechLoading_sameFP(w_LoadedElts, EltCrack, EltLoaded, C):
C_Crack = C[np.ix_(EltCrack, EltCrack)]
A = np.hstack((C_Crack, -np.ones((EltCrack.size, 1), dtype=np.float64)))
A = np.vstack((A, np.zeros((1, EltCrack.size + 1), dtype=np.float64)))
A[-1, np.where(EltCrack == EltLoaded)[0]] = 1
S = np.zeros((EltCrack.size + 1), dtype=np.float64)
S[-1] = w_LoadedElts
return A, S
#-----------------------------------------------------------------------------------------------------------------------
def MakeEquationSystem_mechLoading_extendedFP(wTip, EltChannel, EltTip, C, EltLoaded, w_loaded):
Ccc = C[np.ix_(EltChannel, EltChannel)]
Cct = C[np.ix_(EltChannel, EltTip)]
A = np.hstack((Ccc, -np.ones((EltChannel.size, 1),dtype=np.float64)))
A = np.vstack((A,np.zeros((1,EltChannel.size+1),dtype=np.float64)))
A[-1, np.where(EltChannel == EltLoaded)[0]] = 1
S = - np.dot(Cct, wTip)
S = np.append(S, w_loaded)
return A, S
#-----------------------------------------------------------------------------------------------------------------------
def MakeEquationSystem_volumeControl_sameFP(w, EltCrack, C, dt, Q, ElemArea):
C_Crack = C[np.ix_(EltCrack, EltCrack)]
A = np.hstack((C_Crack,-np.ones((EltCrack.size,1),dtype=np.float64)))
A = np.vstack((A,np.ones((1,EltCrack.size+1),dtype=np.float64)))
A[-1,-1] = 0
S = -np.dot(C_Crack,w[EltCrack])
S = np.append(S,Q * dt / ElemArea)
return A, S
#-----------------------------------------------------------------------------------------------------------------------
indexing.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
def maybe_convert_ix(*args):
"""
We likely want to take the cross-product
"""
ixify = True
for arg in args:
if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)):
ixify = False
if ixify:
return np.ix_(*args)
else:
return args
def fit(self, X):
"""Sample a training set.
Parameters
----------
X: array-like
training set to sample observations from.
Returns
----------
self: obj
fitted instance with stored sample.
"""
self.train_shape = X.shape
sample_idx = {}
for i in range(2):
dim_size = min(X.shape[i], self.size)
sample_idx[i] = permutation(X.shape[i])[:dim_size]
sample = X[ix_(sample_idx[0], sample_idx[1])]
self.sample_idx_ = sample_idx
self.sample_ = sample
return self
def is_train(self, X):
"""Check if an array is the training set.
Parameters
----------
X: array-like
training set to sample observations from.
Returns
----------
self: obj
fitted instance with stored sample.
"""
if not hasattr(self, "train_shape"):
raise NotFittedError("This IdTrain instance is not fitted yet.")
if not self._check_shape(X):
return False
idx = self.sample_idx_
try:
# Grab sample from `X`
sample = X[ix_(idx[0], idx[1])]
return array_equal(sample, self.sample_)
except IndexError:
# If index is out of bounds, X.shape < training_set.shape
# -> X is not the training set
return False
def _M2_sparse(Xvar, mask_X, Yvar, mask_Y, weights=None):
""" 2nd moment matrix exploiting zero input columns """
C = np.zeros((len(mask_X), len(mask_Y)))
C[np.ix_(mask_X, mask_Y)] = _M2_dense(Xvar, Yvar, weights=weights)
return C
def cartesian_product(arrays):
""" Returns Cartesian product of given arrays (x and y): cartesian_product([x,y]) """
broadcastable = np.ix_(*arrays)
broadcasted = np.broadcast_arrays(*broadcastable)
rows, cols = reduce(np.multiply, broadcasted[0].shape), len(broadcasted)
out = np.empty(rows * cols, dtype=broadcasted[0].dtype)
start, end = 0, rows
for a in broadcasted:
out[start:end] = a.reshape(-1)
start, end = end, end + rows
# Return value(s)
return out.reshape(cols, rows).T
def test_regression_1(self):
# Test empty inputs create ouputs of indexing type, gh-5804
# Test both lists and arrays
for func in (range, np.arange):
a, = np.ix_(func(0))
assert_equal(a.dtype, np.intp)
def test_shape_and_dtype(self):
sizes = (4, 5, 3, 2)
# Test both lists and arrays
for func in (range, np.arange):
arrays = np.ix_(*[func(sz) for sz in sizes])
for k, (a, sz) in enumerate(zip(arrays, sizes)):
assert_equal(a.shape[k], sz)
assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k))
assert_(np.issubdtype(a.dtype, int))
def test_bool(self):
bool_a = [True, False, True, True]
int_a, = np.nonzero(bool_a)
assert_equal(np.ix_(bool_a)[0], int_a)