GVKun编程网logo

Python numpy 模块-logaddexp() 实例源码(python中numpy模块)

4

本文将介绍Pythonnumpy模块-logaddexp()实例源码的详细情况,特别是关于python中numpy模块的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同

本文将介绍Python numpy 模块-logaddexp() 实例源码的详细情况,特别是关于python中numpy模块的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的知识。

本文目录一览:

Python numpy 模块-logaddexp() 实例源码(python中numpy模块)

Python numpy 模块-logaddexp() 实例源码(python中numpy模块)

Python numpy 模块,logaddexp() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.logaddexp()

项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, np.add, np.subtract, np.multiply, np.divide,
  6. np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
  7. np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
  8. np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
  9. np.logical_and, np.logical_or, np.logical_xor, np.maximum,
  10. np.minimum, np.mod
  11. ]
  12.  
  13. # These functions still return NotImplemented. Will be fixed in
  14. # future.
  15. # bad = [np.greater,np.greater_equal,np.less,np.less_equal,np.not_equal]
  16.  
  17. a = np.array(''1'')
  18. b = 1
  19. for f in binary_funcs:
  20. assert_raises(TypeError, f, a, b)
项目:multiagent-particle-envs    作者:openai    | 项目源码 | 文件源码
  1. def get_collision_force(self, entity_a, entity_b):
  2. if (not entity_a.collide) or (not entity_b.collide):
  3. return [None, None] # not a collider
  4. if (entity_a is entity_b):
  5. return [None, None] # don''t collide against itself
  6. # compute actual distance between entities
  7. delta_pos = entity_a.state.p_pos - entity_b.state.p_pos
  8. dist = np.sqrt(np.sum(np.square(delta_pos)))
  9. # minimum allowable distance
  10. dist_min = entity_a.size + entity_b.size
  11. # softmax penetration
  12. k = self.contact_margin
  13. penetration = np.logaddexp(0, -(dist - dist_min)/k)*k
  14. force = self.contact_force * delta_pos / dist * penetration
  15. force_a = +force if entity_a.movable else None
  16. force_b = -force if entity_b.movable else None
  17. return [force_a, force_b]
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:cpnest    作者:johnveitch    | 项目源码 | 文件源码
  1. def increment(self,logL,nlive=None):
  2. """
  3. Increment the state of the evidence integrator
  4. Simply uses rectangle rule for initial estimate
  5. """
  6. if(logL<=self.logLs[-1]):
  7. print(''WARNING: NS integrator received non-monotonic logL. {0:.3f} -> {1:.3f}''.format(self.logLs[-1],logL))
  8. if nlive is None:
  9. nlive = self.nlive
  10. oldZ = self.logZ
  11. logt=-1.0/nlive
  12. Wt = self.logw + logL + logsubexp(0,logt)
  13. self.logZ = logaddexp(self.logZ,Wt)
  14. # Update information estimate
  15. if np.isfinite(oldZ) and np.isfinite(self.logZ):
  16. self.info = exp(Wt - self.logZ)*logL + exp(oldZ - self.logZ)*(self.info + oldZ) - self.logZ
  17.  
  18. # Update history
  19. self.logw += logt
  20. self.iteration += 1
  21. self.logLs.append(logL)
  22. self.log_vols.append(self.logw)
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:siHMM    作者:Ardavans    | 项目源码 | 文件源码
  1. def _expected_durations(self,
  2. dur_potentials,cumulative_obs_potentials,
  3. alphastarl,betal,normalizer):
  4. if self.trunc is not None:
  5. raise NotImplementedError, "_expected_durations can''t handle trunc"
  6. T = self.T
  7. logpmfs = -np.inf*np.ones_like(alphastarl)
  8. errs = np.seterr(invalid=''ignore'')
  9. for t in xrange(T):
  10. cB, offset = cumulative_obs_potentials(t)
  11. np.logaddexp(dur_potentials(t) + alphastarl[t] + betal[t:] +
  12. cB - (normalizer + offset),
  13. logpmfs[:T-t], out=logpmfs[:T-t])
  14. np.seterr(**errs)
  15. expected_durations = np.exp(logpmfs.T)
  16.  
  17. return expected_durations
  18.  
  19.  
  20. # Todo call this ''time homog''
项目:siHMM    作者:Ardavans    | 项目源码 | 文件源码
  1. def messages_backwards(self):
  2. # NOTE: np.maximum calls are because the C++ code doesn''t do
  3. # np.logaddexp(-inf,-inf) = -inf,it likes nans instead
  4. from hsmm_messages_interface import messages_backwards_log
  5. betal, betastarl = messages_backwards_log(
  6. np.maximum(self.trans_matrix,1e-50),self.aBl,np.maximum(self.aDl,-1000000),
  7. self.aDsl,np.empty_like(self.aBl),
  8. self.right_censoring,self.trunc if self.trunc is not None else self.T)
  9. assert not np.isnan(betal).any()
  10. assert not np.isnan(betastarl).any()
  11.  
  12. if not self.left_censoring:
  13. self._normalizer = np.logaddexp.reduce(np.log(self.pi_0) + betastarl[0])
  14. else:
  15. raise NotImplementedError
  16.  
  17. return betal, betastarl
项目:siHMM    作者:Ardavans    | 项目源码 | 文件源码
  1. def _expected_durations(self,normalizer):
  2. logpmfs = -np.inf*np.ones((self.Tfull,alphastarl.shape[1]))
  3. errs = np.seterr(invalid=''ignore'') # logaddexp(-inf,-inf)
  4. # Todo censoring not handled correctly here
  5. for tblock in xrange(self.Tblock):
  6. possible_durations = self.segmentlens[tblock:].cumsum()[:self.trunc]
  7. cB, offset = cumulative_obs_potentials(tblock)
  8. logpmfs[possible_durations -1] = np.logaddexp(
  9. dur_potentials(tblock) + alphastarl[tblock]
  10. + betal[tblock:tblock+self.trunc if self.trunc is not None else None]
  11. + cB - (offset + normalizer),
  12. logpmfs[possible_durations -1])
  13. np.seterr(**errs)
  14. return np.exp(logpmfs.T)
  15.  
  16.  
  17. ###################
  18. # sparate trans #
  19. ###################
项目:siHMM    作者:Ardavans    | 项目源码 | 文件源码
  1. def aBl_einsum(self):
  2. if self._aBBl is None:
  3. sigmas = np.array([[c.sigmas for c in d.components] for d in self.obs_distns])
  4. Js = -1./(2*sigmas)
  5. mus = np.array([[c.mu for c in d.components] for d in self.obs_distns])
  6.  
  7. # all_likes is T x Nstates x Ncomponents
  8. all_likes = \\
  9. (np.einsum(''td,td,nkd->tnk'',self.data,Js)
  10. - np.einsum(''td,nkd,2*mus,Js))
  11. all_likes += (mus**2*Js - 1./2*np.log(2*np.pi*sigmas)).sum(2)
  12.  
  13. # weights is Nstates x Ncomponents
  14. weights = np.log(np.array([d.weights.weights for d in self.obs_distns]))
  15. all_likes += weights[na,...]
  16.  
  17. # aBl is T x Nstates
  18. aBl = self._aBl = np.logaddexp.reduce(all_likes, axis=2)
  19. aBl[np.isnan(aBl).any(1)] = 0.
  20.  
  21. aBBl = self._aBBl = np.empty((self.Tblock,self.num_states))
  22. for idx, (start,stop) in enumerate(self.changepoints):
  23. aBBl[idx] = aBl[start:stop].sum(0)
  24.  
  25. return self._aBBl
项目:siHMM    作者:Ardavans    | 项目源码 | 文件源码
  1. def _expected_statistics_from_messages_slow(trans_potential,likelihood_log_potential,alphal,betal):
  2. expected_states = alphal + betal
  3. expected_states -= expected_states.max(1)[:,na]
  4. np.exp(expected_states,out=expected_states)
  5. expected_states /= expected_states.sum(1)[:,na]
  6.  
  7. Al = np.log(trans_potential)
  8. log_joints = alphal[:-1,:,na] + (betal[1:,na,:] + likelihood_log_potential[1:,:]) + Al[na,...]
  9. log_joints -= log_joints.max((1,2))[:,na]
  10. joints = np.exp(log_joints)
  11. joints /= joints.sum((1,na] # NOTE: renormalizing each isnt really necessary
  12. expected_transcounts = joints.sum(0)
  13.  
  14. normalizer = np.logaddexp.reduce(alphal[0] + betal[0])
  15.  
  16. return expected_states, expected_transcounts, normalizer
  17.  
  18. ### EM
项目:siHMM    作者:Ardavans    | 项目源码 | 文件源码
  1. def _messages_backwards_log_slow(trans_potential, init_potential, likelihood_log_potential,
  2. feature_weights, window_data):
  3. errs = np.seterr(over=''ignore'')
  4. Al = np.log(trans_potential)
  5. pil = np.log(init_potential)
  6. aBl = likelihood_log_potential
  7. nhs = trans_potential.shape[0]
  8. sequence_length = aBl.shape[0]
  9. betal = np.zeros((sequence_length, nhs * 2))
  10. giant_Al_pil = np.tile(np.vstack((np.tile(pil, (nhs,1)), Al )), (1,2))
  11. for t in xrange(betal.shape[0]-2,-1,-1):
  12. temp_constant = np.sum(feature_weights[:-nhs-1] * window_data[t+1,:]) + feature_weights[-1]
  13. temp_exp = temp_constant + feature_weights[-nhs-1:-1]
  14. temp_logaddexp = np.logaddexp(0, temp_exp)
  15. temp_log_linear = np.tile(temp_exp, 2) * np.repeat([0,1], nhs) - np.tile(temp_logaddexp, 2)
  16.  
  17. np.logaddexp.reduce( giant_Al_pil + betal[t+1] +
  18. np.hstack((aBl[t+1], aBl[t+1])) +
  19. temp_log_linear
  20. ,axis=1 ,out=(betal[t]))
  21.  
  22.  
  23. np.seterr(**errs)
  24. return betal
项目:siHMM    作者:Ardavans    | 项目源码 | 文件源码
  1. def _messages_backwards_log_fast(trans_potential, likelihood_log_potential_llt):
  2. errs = np.seterr(over=''ignore'')
  3. Al = np.log(trans_potential)
  4. pil = np.log(init_potential)
  5. aBl = likelihood_log_potential_llt
  6. nhs = trans_potential.shape[0]
  7. sequence_length = aBl.shape[0]
  8. betal = np.zeros((sequence_length,2))
  9.  
  10.  
  11. for t in xrange(betal.shape[0]-2,-1):
  12. np.logaddexp.reduce( giant_Al_pil + betal[t+1] + aBl[t+1], axis=1, out=(betal[t]))
  13.  
  14. np.seterr(**errs)
  15. return betal
  16.  
  17.  
  18. ### Gibbs sampling
项目:siHMM    作者:Ardavans    | 项目源码 | 文件源码
  1. def _expected_segmentation_states(init_potential, expected_states, trans_potential, expected_joints,
  2. feature_weights, window_data):
  3.  
  4. #log_q(s_t) for s_t = 1
  5. data_length = window_data.shape[0]
  6. mega_mat = np.hstack((window_data[:data_length - 1,:], expected_states[:data_length - 1,:]))
  7. temp_1 = np.sum(feature_weights * mega_mat, axis=1)
  8. with np.errstate(invalid=''ignore''):
  9. temp_2 = np.sum(np.sum(expected_joints[:data_length - 1,:] * np.log(trans_potential), axis = 1), axis = 1)
  10. log_s_t_1 = temp_1 + temp_2
  11. log_s_t_1 = np.append(log_s_t_1, -float("inf")) #the last state is always zero so the probability of s_t = 1 is zero
  12.  
  13. #log q(s_t) for s_t = 0
  14. log_s_t_0 = np.sum(expected_states[1:, :] * np.log(init_potential), axis = 1)
  15. log_s_t_0 = np.append(log_s_t_0, 0)
  16.  
  17. temp_stack = np.hstack((log_s_t_1[:, na], log_s_t_0[:, na])) #number of rows is the length of the sequence
  18. expected_states = np.exp(temp_stack - np.logaddexp.reduce(temp_stack[:,na], axis = 1))
  19. return expected_states
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
  1. def _parallel_predict_log_proba(estimators, estimators_features, X, n_classes):
  2. """Private function used to compute log probabilities within a job."""
  3. n_samples = X.shape[0]
  4. log_proba = np.empty((n_samples, n_classes))
  5. log_proba.fill(-np.inf)
  6. all_classes = np.arange(n_classes, dtype=np.int)
  7.  
  8. for estimator, features in zip(estimators, estimators_features):
  9. log_proba_estimator = estimator.predict_log_proba(X[:, features])
  10.  
  11. if n_classes == len(estimator.classes_):
  12. log_proba = np.logaddexp(log_proba, log_proba_estimator)
  13.  
  14. else:
  15. log_proba[:, estimator.classes_] = np.logaddexp(
  16. log_proba[:, estimator.classes_],
  17. log_proba_estimator[:, range(len(estimator.classes_))])
  18.  
  19. missing = np.setdiff1d(all_classes, estimator.classes_)
  20. log_proba[:, missing] = np.logaddexp(log_proba[:, missing],
  21. -np.inf)
  22.  
  23. return log_proba
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
  1. def _free_energy(self, v):
  2. """Computes the free energy F(v) = - log sum_h exp(-E(v,h)).
  3.  
  4. Parameters
  5. ----------
  6. v : array-like,shape (n_samples,n_features)
  7. Values of the visible layer.
  8.  
  9. Returns
  10. -------
  11. free_energy : array-like,)
  12. The value of the free energy.
  13. """
  14. return (- safe_sparse_dot(v, self.intercept_visible_)
  15. - np.logaddexp(0, safe_sparse_dot(v, self.components_.T)
  16. + self.intercept_hidden_).sum(axis=1))
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_NotImplemented_not_returned(self):
  2. # See gh-5964 and gh-2091. Some of these functions are not operator
  3. # related and were fixed for other reasons in the past.
  4. binary_funcs = [
  5. np.power, b)
项目:cellranger    作者:10XGenomics    | 项目源码 | 文件源码
  1. def logaddexp(arr):
  2. """Computes log(exp(arr[0]) + exp(arr[1]) + ...). """
  3. assert(len(arr) >= 2)
  4. res = np.logaddexp(arr[0], arr[1])
  5. for i in arr[2:]:
  6. res = np.logaddexp(res, i)
  7. return res
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_logaddexp_values(self):
  2. x = [1, 2, 3, 4, 5]
  3. y = [5, 1]
  4. z = [6, 6, 6]
  5. for dt, dec_ in zip([''f'', ''d'', ''g''], [6, 15, 15]):
  6. xf = np.log(np.array(x, dtype=dt))
  7. yf = np.log(np.array(y, dtype=dt))
  8. zf = np.log(np.array(z, dtype=dt))
  9. assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec_)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_logaddexp_range(self):
  2. x = [1000000, -1000000, 1000200, -1000200]
  3. y = [1000200, -1000200, 1000000, -1000000]
  4. z = [1000200, -1000000]
  5. for dt in [''f'', ''g'']:
  6. logxf = np.array(x, dtype=dt)
  7. logyf = np.array(y, dtype=dt)
  8. logzf = np.array(z, dtype=dt)
  9. assert_almost_equal(np.logaddexp(logxf, logyf), logzf)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_inf(self):
  2. inf = np.inf
  3. x = [inf, -inf, inf, inf, 1, -inf, 1]
  4. y = [inf, inf, -inf]
  5. z = [inf, 1]
  6. with np.errstate(invalid=''raise''):
  7. for dt in [''f'', ''g'']:
  8. logxf = np.array(x, dtype=dt)
  9. logyf = np.array(y, dtype=dt)
  10. logzf = np.array(z, dtype=dt)
  11. assert_equal(np.logaddexp(logxf, logzf)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_nan(self):
  2. assert_(np.isnan(np.logaddexp(np.nan, np.inf)))
  3. assert_(np.isnan(np.logaddexp(np.inf, np.nan)))
  4. assert_(np.isnan(np.logaddexp(np.nan, 0)))
  5. assert_(np.isnan(np.logaddexp(0, np.nan)))
项目:char-rbm    作者:colinmorris    | 项目源码 | 文件源码
  1. def _free_energy(self,h)).
  2.  
  3. v : array-like, self.components_.T)
  4. + self.intercept_hidden_).sum(axis=1))
项目:tbp-next-basket    作者:GiulioRossetti    | 项目源码 | 文件源码
  1. def sigmoid(x):
  2. if x >= 0:
  3. return math.exp(-np.logaddexp(0, -x))
  4. else:
  5. return math.exp(x - np.logaddexp(x, 0))
项目:tbp-next-basket    作者:GiulioRossetti    | 项目源码 | 文件源码
  1. def sigmoid(x):
  2. return math.exp(-np.logaddexp(0, -x))
项目:chainer-segnet    作者:pfnet-research    | 项目源码 | 文件源码
  1. def check_forward(self, x_data, t_data, class_weight, use_cudnn=True):
  2. x = chainer.Variable(x_data)
  3. t = chainer.Variable(t_data)
  4. loss = softmax_cross_entropy.softmax_cross_entropy(
  5. x, t, use_cudnn=use_cudnn, normalize=self.normalize,
  6. cache_score=self.cache_score, class_weight=class_weight)
  7. self.assertEqual(loss.data.shape, ())
  8. self.assertEqual(loss.data.dtype, self.dtype)
  9. self.assertEqual(hasattr(loss.creator, ''y''), self.cache_score)
  10. loss_value = float(cuda.to_cpu(loss.data))
  11.  
  12. # Compute expected value
  13. loss_expect = 0.0
  14. count = 0
  15. x = numpy.rollaxis(self.x, self.x.ndim).reshape(
  16. (self.t.size, self.x.shape[1]))
  17. t = self.t.ravel()
  18. for xi, ti in six.moves.zip(x, t):
  19. if ti == -1:
  20. continue
  21. log_z = numpy.ufunc.reduce(numpy.logaddexp, xi)
  22. if class_weight is None:
  23. loss_expect -= (xi - log_z)[ti]
  24. else:
  25. loss_expect -= (xi - log_z)[ti] * class_weight[ti]
  26. count += 1
  27.  
  28. if self.normalize:
  29. if count == 0:
  30. loss_expect = 0.0
  31. else:
  32. loss_expect /= count
  33. else:
  34. loss_expect /= len(t_data)
  35.  
  36. testing.assert_allclose(
  37. loss_expect, loss_value, **self.check_forward_options)
项目:massivedatans    作者:JohannesBuchner    | 项目源码 | 文件源码
  1. def integrate_remainder(sampler, logwidth, logVolremaining, logZ, H, globalLmax):
  2. # logwidth remains the same Now for each sample
  3. remainder = list(sampler.remainder())
  4. logV = logwidth
  5. L0 = remainder[-1][2]
  6. L0 = globalLmax
  7. logLs = [Li - L0 for ui, xi, Li in remainder]
  8. Ls = numpy.exp(logLs)
  9. LsMax = Ls.copy()
  10. LsMax[-1] = numpy.exp(globalLmax - L0)
  11. Lmax = LsMax[1:].sum(axis=0) + LsMax[-1]
  12. #Lmax = Ls[1:].sum(axis=0) + Ls[-1]
  13. Lmin = Ls[:-1].sum(axis=0) + Ls[0]
  14. logLmid = log(Ls.sum(axis=0)) + L0
  15. logZmid = logaddexp(logZ, logV + logLmid)
  16. logZup = logaddexp(logZ, logV + log(Lmax) + L0)
  17. logZlo = logaddexp(logZ, logV + log(Lmin) + L0)
  18. logZerr = logZup - logZlo
  19. assert numpy.isfinite(H).all()
  20. assert numpy.isfinite(logZerr).all(), logZerr
  21.  
  22. for i in range(len(remainder)):
  23. ui, Li = remainder[i]
  24. wi = logwidth + Li
  25. logZnew = logaddexp(logZ, wi)
  26. #Hprev = H
  27. H = exp(wi - logZnew) * Li + exp(logZ - logZnew) * (H + logZ) - logZnew
  28. H[H < 0] = 0
  29. #assert (H>0).all(),(H,Hprev,wi,Li,logZ,logZnew)
  30. logZ = logZnew
  31.  
  32. #assert numpy.isfinite(logZerr + (H / sampler.nlive_points)**0.5),sampler.nlive_points,logZerr)
  33.  
  34. return logV + logLmid, logZerr, logZmid, logZerr + (H / sampler.nlive_points)**0.5, logZerr + (H / sampler.nlive_points)**0.5
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_logaddexp_values(self):
  2. x = [1, decimal=dec_)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_logaddexp_range(self):
  2. x = [1000000, logzf)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_inf(self):
  2. inf = np.inf
  3. x = [inf, logzf)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_nan(self):
  2. assert_(np.isnan(np.logaddexp(np.nan, np.nan)))
项目:GPflow    作者:GPflow    | 项目源码 | 文件源码
  1. def forward(self, x):
  2. """
  3. Implementation of softplus. Overflow avoided by use of the logaddexp function.
  4. self._lower is added before returning.
  5. """
  6. return np.logaddexp(0, x) + self._lower
项目:deepspeech.mxnet    作者:samsungsds-rnd    | 项目源码 | 文件源码
  1. def ctc_loss(label, prob, remainder, seq_length, batch_size, num_gpu=1, big_num=1e10):
  2. label_ = [0, 0]
  3. prob[prob < 1 / big_num] = 1 / big_num
  4. log_prob = np.log(prob)
  5.  
  6. l = len(label)
  7. for i in range(l):
  8. label_.append(int(label[i]))
  9. label_.append(0)
  10.  
  11. l_ = 2 * l + 1
  12. a = np.full((seq_length, l_ + 1), -big_num)
  13. a[0][1] = log_prob[remainder][0]
  14. a[0][2] = log_prob[remainder][label_[2]]
  15. for i in range(1, seq_length):
  16. row = i * int(batch_size / num_gpu) + remainder
  17. a[i][1] = a[i - 1][1] + log_prob[row][0]
  18. a[i][2] = np.logaddexp(a[i - 1][2], a[i - 1][1]) + log_prob[row][label_[2]]
  19. for j in range(3, l_ + 1):
  20. a[i][j] = np.logaddexp(a[i - 1][j], a[i - 1][j - 1])
  21. if label_[j] != 0 and label_[j] != label_[j - 2]:
  22. a[i][j] = np.logaddexp(a[i][j], a[i - 1][j - 2])
  23. a[i][j] += log_prob[row][label_[j]]
  24.  
  25. return -np.logaddexp(a[seq_length - 1][l_], a[seq_length - 1][l_ - 1])
  26.  
  27.  
  28. # label is done with remove_blank
  29. # pred is got from pred_best
项目:chainer-deconv    作者:germanRos    | 项目源码 | 文件源码
  1. def _forward_cpu_one(self, x, W):
  2. begin = self.begins[t]
  3. end = self.begins[t + 1]
  4.  
  5. w = W[self.paths[begin:end]]
  6. wxy = w.dot(x) * self.codes[begin:end]
  7. loss = numpy.logaddexp(0.0, -wxy) # == log(1 + exp(-wxy))
  8. return numpy.sum(loss)
项目:chainer-deconv    作者:germanRos    | 项目源码 | 文件源码
  1. def check_forward(self, use_cudnn=True):
  2. x = chainer.Variable(x_data)
  3. t = chainer.Variable(t_data)
  4. loss = functions.softmax_cross_entropy(
  5. x,
  6. cache_score=self.cache_score)
  7. self.assertEqual(loss.data.shape, xi)
  8. loss_expect -= (xi - log_z)[ti]
  9. count += 1
  10.  
  11. if self.normalize:
  12. if count == 0:
  13. loss_expect = 0.0
  14. else:
  15. loss_expect /= count
  16. else:
  17. loss_expect /= len(t_data)
  18.  
  19. gradient_check.assert_allclose(
  20. loss_expect, **self.check_forward_options)
项目:chainer-deconv    作者:germanRos    | 项目源码 | 文件源码
  1. def check_forward(self, use_cudnn=True):
  2. x = chainer.Variable(x_data)
  3. y = functions.log_softmax(x, use_cudnn)
  4. self.assertEqual(y.data.dtype, self.dtype)
  5.  
  6. log_z = numpy.ufunc.reduce(
  7. numpy.logaddexp, self.x, keepdims=True)
  8. y_expect = self.x - log_z
  9.  
  10. gradient_check.assert_allclose(
  11. y_expect, y.data, **self.check_forward_options)
项目:improved_wgan_training    作者:YuguangTong    | 项目源码 | 文件源码
  1. def js_with(self, p):
  2. log_p = np.array([p.log_likelihood(ngram) for ngram in p.unique_ngrams()])
  3. log_q = np.array([self.log_likelihood(ngram) for ngram in p.unique_ngrams()])
  4. log_m = np.logaddexp(log_p - np.log(2), log_q - np.log(2))
  5. kl_p_m = np.sum(np.exp(log_p) * (log_p - log_m))
  6.  
  7. log_p = np.array([p.log_likelihood(ngram) for ngram in self.unique_ngrams()])
  8. log_q = np.array([self.log_likelihood(ngram) for ngram in self.unique_ngrams()])
  9. log_m = np.logaddexp(log_p - np.log(2), log_q - np.log(2))
  10. kl_q_m = np.sum(np.exp(log_q) * (log_q - log_m))
  11.  
  12. return 0.5*(kl_p_m + kl_q_m) / np.log(2)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_logaddexp_values(self):
  2. x = [1, decimal=dec_)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_logaddexp_range(self):
  2. x = [1000000, logzf)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_inf(self):
  2. inf = np.inf
  3. x = [inf, logzf)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_nan(self):
  2. assert_(np.isnan(np.logaddexp(np.nan, np.nan)))
项目:rnn.wgan    作者:amirbar    | 项目源码 | 文件源码
  1. def js_with(self, log_q - np.log(2))
  2. kl_q_m = np.sum(np.exp(log_q) * (log_q - log_m))
  3.  
  4. return 0.5 * (kl_p_m + kl_q_m) / np.log(2)
项目:improved_wgan_training    作者:igul222    | 项目源码 | 文件源码
  1. def js_with(self, log_q - np.log(2))
  2. kl_q_m = np.sum(np.exp(log_q) * (log_q - log_m))
  3.  
  4. return 0.5*(kl_p_m + kl_q_m) / np.log(2)
项目:pyurgent    作者:tiendung    | 项目源码 | 文件源码
  1. def evalObjectiveFunction(clean_biascount,Pword_plus,Pword_minus,ratio,removing_words):
  2. mlog(evalObjectiveFunction.__name__,"call")
  3. import numpy as np
  4. import math
  5. #Obj = np.log(1)
  6. Obj = 0
  7. for doc in clean_biascount:
  8. Pdoc = calcProbabilityDocument(Pword_plus,doc[1],removing_words)
  9. i = clean_biascount.index(doc)
  10. if i == 0:
  11. mlog(evalObjectiveFunction.__name__,''Pdoc 0 '' + str(Pdoc) + '' type '' + str(type(Pdoc)))
  12. t00 = np.exp(np.float64(Pdoc[0]))
  13. t01 = np.exp(np.float64(Pdoc[1]))
  14. t1 = t00 - t01
  15. #print str(t1)
  16. t2 = abs(t1)
  17. Obj = np.log(t2)
  18. #print str(Obj)
  19. if i % 100 == 0:
  20. mlog(evalObjectiveFunction.__name__,"Pdoc + " + str(i) + "= " + str(Pdoc))
  21. if doc[0] == True:
  22. Obj = np.logaddexp(Obj,Pdoc[0])
  23. if i % 100 == 1:
  24. mlog(evalObjectiveFunction.__name__,"Obj+ " + str(i) + " after += " + str(Obj))
  25. Obj = np.log(np.exp(Obj) - np.exp(Pdoc[1]))
  26. elif doc[0] == False:
  27. Obj = np.log(np.exp(np.float64(Obj)) + np.exp(np.float64(Pdoc[1])))
  28. if i % 100 == 2:
  29. mlog(evalObjectiveFunction.__name__,"Obj- " + str(i) + " after += " + str(Obj))
  30. Obj = np.log(np.exp(Obj) - np.exp(Pdoc[0]))
  31. if Obj == 0.0:
  32. mlog(evalObjectiveFunction.__name__, "Obj=0 fuck " + str(i) + "")
  33. mlog(evalObjectiveFunction.__name__,"Obj = " + str(np.exp(Obj)))
  34. if math.isnan(np.exp(Obj))==False:
  35. print ''J = '' + str(np.exp(Obj))
  36. return Obj #type np.log
项目:e2end    作者:oplatek    | 项目源码 | 文件源码
  1. def sigmoid(x):
  2. x = np.array(x)
  3. return np.exp(-np.logaddexp(0, -x))
项目:nonce2vec    作者:minimalparts    | 项目源码 | 文件源码
  1. def update_phi(self, doc_number, time):
  2. """
  3. Update variational multinomial parameters,based on a document and a time-slice.
  4. This is done based on the original Blei-LDA paper,where:
  5. log_phi := beta * exp(?(gamma)),over every topic for every word.
  6.  
  7. Todo: incorporate lee-sueng trick used in **Lee,Seung: Algorithms for non-negative matrix factorization,NIPS 2001**.
  8. """
  9. num_topics = self.lda.num_topics
  10. # digamma values
  11. dig = np.zeros(num_topics)
  12.  
  13. for k in range(0, num_topics):
  14. dig[k] = digamma(self.gamma[k])
  15.  
  16. n = 0 # keep track of iterations for phi,log_phi
  17. for word_id, count in self.doc:
  18. for k in range(0, num_topics):
  19. self.log_phi[n][k] = dig[k] + self.lda.topics[word_id][k]
  20.  
  21. log_phi_row = self.log_phi[n]
  22. phi_row = self.phi[n]
  23.  
  24. # log normalize
  25. v = log_phi_row[0]
  26. for i in range(1, len(log_phi_row)):
  27. v = np.logaddexp(v, log_phi_row[i])
  28.  
  29. # subtract every element by v
  30. log_phi_row = log_phi_row - v
  31. phi_row = np.exp(log_phi_row)
  32. self.log_phi[n] = log_phi_row
  33. self.phi[n] = phi_row
  34. n +=1 # increase iteration
  35.  
  36. return self.phi, self.log_phi
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_logaddexp_values(self):
  2. x = [1, decimal=dec_)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_logaddexp_range(self):
  2. x = [1000000, logzf)

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable

如何解决Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: ''numpy.ndarray'' object is not callable?

晚安, 尝试打印以下内容时,我在 jupyter 中遇到了 numpy 问题,并且得到了一个 错误: 需要注意的是python版本是3.8.8。 我先用 spyder 测试它,它运行正确,它给了我预期的结果

使用 Spyder:

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
Results
0.6604903457995978
0.8236300859753154
0.16067650689842816
0.6967868357083673
0.4231597934445466

现在有了 jupyter

import numpy as np
    for i in range (5):
        n = np.random.rand ()
    print (n)
-------------------------------------------------- ------
TypeError Traceback (most recent call last)
<ipython-input-78-0c6a801b3ea9> in <module>
       2 for i in range (5):
       3 n = np.random.rand ()
---->  4 print (n)

       TypeError: ''numpy.ndarray'' object is not callable

感谢您对我如何在 Jupyter 中解决此问题的帮助。

非常感谢您抽出宝贵时间。

阿特,约翰”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

numpy.random.random & numpy.ndarray.astype & numpy.arange

numpy.random.random & numpy.ndarray.astype & numpy.arange

今天看到这样一句代码:

xb = np.random.random((nb, d)).astype(''float32'') #创建一个二维随机数矩阵(nb行d列)
xb[:, 0] += np.arange(nb) / 1000. #将矩阵第一列的每个数加上一个值

要理解这两句代码需要理解三个函数

1、生成随机数

numpy.random.random(size=None) 

size为None时,返回float。

size不为None时,返回numpy.ndarray。例如numpy.random.random((1,2)),返回1行2列的numpy数组

 

2、对numpy数组中每一个元素进行类型转换

numpy.ndarray.astype(dtype)

返回numpy.ndarray。例如 numpy.array([1, 2, 2.5]).astype(int),返回numpy数组 [1, 2, 2]

 

3、获取等差数列

numpy.arange([start,]stop,[step,]dtype=None)

功能类似python中自带的range()和numpy中的numpy.linspace

返回numpy数组。例如numpy.arange(3),返回numpy数组[0, 1, 2]

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel()/numpy.flatten()/numpy.squeeze()

numpy.ravel(a, order=''C'')

  Return a flattened array

numpy.chararray.flatten(order=''C'')

  Return a copy of the array collapsed into one dimension

numpy.squeeze(a, axis=None)

  Remove single-dimensional entries from the shape of an array.

 

相同点: 将多维数组 降为 一维数组

不同点:

  ravel() 返回的是视图(view),意味着改变元素的值会影响原始数组元素的值;

  flatten() 返回的是拷贝,意味着改变元素的值不会影响原始数组;

  squeeze()返回的是视图(view),仅仅是将shape中dimension为1的维度去掉;

 

ravel()示例:

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.ravel()
16 print("a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 
20 print(a)
21 log_type(''a'',a)

 

flatten()示例

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.flatten()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

squeeze()示例:

1. 没有single-dimensional entries的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10     
11 a = np.floor(10*np.random.random((3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

从结果中可以看到,当没有single-dimensional entries时,squeeze()返回额数组对象是一个view,而不是copy。

 

2. 有single-dimentional entries 的情况

 1 import matplotlib.pyplot as plt
 2 import numpy as np
 3 
 4 def log_type(name,arr):
 5     print("数组{}的大小:{}".format(name,arr.size))
 6     print("数组{}的维度:{}".format(name,arr.shape))
 7     print("数组{}的维度:{}".format(name,arr.ndim))
 8     print("数组{}元素的数据类型:{}".format(name,arr.dtype))
 9     #print("数组:{}".format(arr.data))
10 
11 a = np.floor(10*np.random.random((1,3,4)))
12 print(a)
13 log_type(''a'',a)
14 
15 a1 = a.squeeze()
16 print("修改前a1:{}".format(a1))
17 log_type(''a1'',a1)
18 a1[2] = 100
19 print("修改后a1:{}".format(a1))
20 
21 print("a:{}".format(a))
22 log_type(''a'',a)

 

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性

一、Numpy数组创建

 part 1:np.linspace(起始值,终止值,元素总个数

 

import numpy as np
''''''
numpy中的ndarray数组
''''''

ary = np.array([1, 2, 3, 4, 5])
print(ary)
ary = ary * 10
print(ary)

''''''
ndarray对象的创建
''''''
# 创建二维数组
# np.array([[],[],...])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(a)

# np.arange(起始值, 结束值, 步长(默认1))
b = np.arange(1, 10, 1)
print(b)

print("-------------np.zeros(数组元素个数, dtype=''数组元素类型'')-----")
# 创建一维数组:
c = np.zeros(10)
print(c, ''; c.dtype:'', c.dtype)

# 创建二维数组:
print(np.zeros ((3,4)))

print("----------np.ones(数组元素个数, dtype=''数组元素类型'')--------")
# 创建一维数组:
d = np.ones(10, dtype=''int64'')
print(d, ''; d.dtype:'', d.dtype)

# 创建三维数组:
print(np.ones( (2,3,4), dtype=np.int32 ))
# 打印维度
print(np.ones( (2,3,4), dtype=np.int32 ).ndim)  # 返回:3(维)

 

结果图:

 

part 2 :np.linspace ( 起始值,终止值,元素总个数)

 

import numpy as np
a = np.arange( 10, 30, 5 )

b = np.arange( 0, 2, 0.3 )

c = np.arange(12).reshape(4,3)

d = np.random.random((2,3))  # 取-1到1之间的随机数,要求设置为诶2行3列的结构

print(a)
print(b)
print(c)
print(d)

print("-----------------")
from numpy import pi
print(np.linspace( 0, 2*pi, 100 ))

print("-------------np.linspace(起始值,终止值,元素总个数)------------------")
print(np.sin(np.linspace( 0, 2*pi, 100 )))

 

结果图:

 

 

 

 

二、Numpy的ndarray对象属性:

数组的结构:array.shape

数组的维度:array.ndim

元素的类型:array.dtype

数组元素的个数:array.size

数组的索引(下标):array[0]

 

''''''
数组的基本属性
''''''
import numpy as np

print("--------------------案例1:------------------------------")
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)     # 打印数组结构
print(len(a))      # 打印有多少行
print(a.ndim)     # 打印维度
print(a.dtype)    # 打印a数组内的元素的数据类型
# print(a.dtype.name)
print(a.size)    # 打印数组的总元素个数


print("-------------------案例2:---------------------------")
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a)

# 测试数组的基本属性
print(''a.shape:'', a.shape)
print(''a.size:'', a.size)
print(''len(a):'', len(a))
# a.shape = (6, )  # 此格式可将原数组结构变成1行6列的数据结构
# print(a, ''a.shape:'', a.shape)

# 数组元素的索引
ary = np.arange(1, 28)
ary.shape = (3, 3, 3)   # 创建三维数组
print("ary.shape:",ary.shape,"\n",ary )

print("-----------------")
print(''ary[0]:'', ary[0])
print(''ary[0][0]:'', ary[0][0])
print(''ary[0][0][0]:'', ary[0][0][0])
print(''ary[0,0,0]:'', ary[0, 0, 0])

print("-----------------")


# 遍历三维数组:遍历出数组里的每个元素
for i in range(ary.shape[0]):
    for j in range(ary.shape[1]):
        for k in range(ary.shape[2]):
            print(ary[i, j, k], end='' '')
            

 

结果图:

 

今天的关于Python numpy 模块-logaddexp() 实例源码python中numpy模块的分享已经结束,谢谢您的关注,如果想了解更多关于Jupyter 中的 Numpy 在打印时出错(Python 版本 3.8.8):TypeError: 'numpy.ndarray' object is not callable、numpy.random.random & numpy.ndarray.astype & numpy.arange、numpy.ravel()/numpy.flatten()/numpy.squeeze()、Numpy:数组创建 numpy.arrray() , numpy.arange()、np.linspace ()、数组基本属性的相关知识,请在本站进行查询。

本文标签: