GVKun编程网logo

Python numpy 模块-arctanh() 实例源码(python numpy argmax)

3

此处将为大家介绍关于Pythonnumpy模块-arctanh()实例源码的详细内容,并且为您解答有关pythonnumpyargmax的相关问题,此外,我们还将为您介绍关于Jupyter中的Nump

此处将为大家介绍关于Python numpy 模块-arctanh() 实例源码的详细内容,并且为您解答有关python numpy argmax的相关问题,此外,我们还将为您介绍关于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 模块-arctanh() 实例源码(python numpy argmax)

Python numpy 模块-arctanh() 实例源码(python numpy argmax)

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

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

项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_branch_cuts(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True
  4. yield _check_branch_cut, np.log2, -0.5, np.log10, -0.5, np.log1p, -1.5, np.sqrt, True
  5.  
  6. yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, 1j], np.arccos, np.arctan, [0-2j, 2j], [1, 1], np.arcsinh, 2j], [1, 1], np.arccosh, [ -1, 0.5], [1j, 1j], np.arctanh, 2], True
  7.  
  8. # check against bogus branch cuts: assert continuity between quadrants
  9. yield _check_branch_cut, [ 1, 1
  10. yield _check_branch_cut, 2], 1
  11.  
  12. yield _check_branch_cut, 2, 0], 1], 2j, 1, 1
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_branch_cuts_complex64(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, True, np.complex64
  4. yield _check_branch_cut, np.complex64
  5.  
  6. yield _check_branch_cut, np.complex64
  7.  
  8. # check against bogus branch cuts: assert continuity between quadrants
  9. yield _check_branch_cut, False, np.complex64
项目:radar    作者:amoose136    | 项目源码 | 文件源码
  1. def test_against_cmath(self):
  2. import cmath
  3.  
  4. points = [-1-1j, -1+1j, +1-1j, +1+1j]
  5. name_map = {''arcsin'': ''asin'', ''arccos'': ''acos'', ''arctan'': ''atan'',
  6. ''arcsinh'': ''asinh'', ''arccosh'': ''acosh'', ''arctanh'': ''atanh''}
  7. atol = 4*np.finfo(np.complex).eps
  8. for func in self.funcs:
  9. fname = func.__name__.split(''.'')[-1]
  10. cname = name_map.get(fname, fname)
  11. try:
  12. cfunc = getattr(cmath, cname)
  13. except AttributeError:
  14. continue
  15. for p in points:
  16. a = complex(func(np.complex_(p)))
  17. b = cfunc(p)
  18. assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
项目:wendy    作者:jobovy    | 项目源码 | 文件源码
  1. def test_energy_conservation_sech2disk_manyparticles():
  2. # Test that energy is conserved for a self-gravitating disk
  3. N= 101
  4. totmass= 1.
  5. sigma= 1.
  6. zh= 2.*sigma**2./totmass
  7. x= numpy.arctanh(2.*numpy.random.uniform(size=N)-1)*zh
  8. v= numpy.random.normal(size=N)*sigma
  9. v-= numpy.mean(v) # stabilize
  10. m= numpy.ones_like(x)/N*(1.+0.1*(2.*numpy.random.uniform(size=N)-1))
  11. g= wendy.nbody(x,v,m,0.05)
  12. E= wendy.energy(x,m)
  13. cnt= 0
  14. while cnt < 100:
  15. tx,tv= next(g)
  16. assert numpy.fabs(wendy.energy(tx,tv,m)-E) < 10.**-10., "Energy not conserved during simple N-body integration"
  17. cnt+= 1
  18. return None
项目:wendy    作者:jobovy    | 项目源码 | 文件源码
  1. def test_energy_conservation_sech2disk_manyparticles():
  2. # Test that energy is conserved for a self-gravitating disk
  3. N= 101
  4. totmass= 1.
  5. sigma= 1.
  6. zh= 2.*sigma**2./totmass
  7. x= numpy.arctanh(2.*numpy.random.uniform(size=N)-1)*zh
  8. v= numpy.random.normal(size=N)*sigma
  9. v-= numpy.mean(v) # stabilize
  10. m= numpy.ones_like(x)/N*(1.+0.1*(2.*numpy.random.uniform(size=N)-1))
  11. omega= 1.1
  12. g= wendy.nbody(x,0.05,omega=omega)
  13. E= wendy.energy(x,omega=omega)
  14. cnt= 0
  15. while cnt < 100:
  16. tx,omega=omega)-E) < 10.**-10., "Energy not conserved during simple N-body integration with external harmonic potential"
  17. cnt+= 1
  18. return None
项目:wendy    作者:jobovy    | 项目源码 | 文件源码
  1. def test_energy_conservation_sech2disk_manyparticles():
  2. # Test that energy is conserved for a self-gravitating disk
  3. N= 101
  4. totmass= 1.
  5. sigma= 1.
  6. zh= 2.*sigma**2./totmass
  7. x= numpy.arctanh(2.*numpy.random.uniform(size=N)-1)*zh
  8. v= numpy.random.normal(size=N)*sigma
  9. v-= numpy.mean(v) # stabilize
  10. m= numpy.ones_like(x)/N*(1.+0.1*(2.*numpy.random.uniform(size=N)-1))
  11. g= wendy.nbody(x,approx=True,nleap=1000)
  12. E= wendy.energy(x,m)-E)/E < 10.**-6., "Energy not conserved during approximate N-body integration"
  13. cnt+= 1
  14. return None
项目:wendy    作者:jobovy    | 项目源码 | 文件源码
  1. def test_notracermasses():
  2. # approx should work with tracer sheets
  3. # Test that energy is conserved for a self-gravitating disk
  4. N= 101
  5. totmass= 1.
  6. sigma= 1.
  7. zh= 2.*sigma**2./totmass
  8. x= numpy.arctanh(2.*numpy.random.uniform(size=N)-1)*zh
  9. v= numpy.random.normal(size=N)*sigma
  10. v-= numpy.mean(v) # stabilize
  11. m= numpy.ones_like(x)/N*(1.+0.1*(2.*numpy.random.uniform(size=N)-1))
  12. m[N//2:]= 0.
  13. m*= 2.
  14. g= wendy.nbody(x, "Energy not conserved during approximate N-body integration with some tracer particles"
  15. cnt+= 1
  16. return None
项目:wendy    作者:jobovy    | 项目源码 | 文件源码
  1. def test_energy_conservation_sech2disk_manyparticles():
  2. # Test that energy is conserved for a self-gravitating disk
  3. N= 101
  4. totmass= 1.
  5. sigma= 1.
  6. zh= 2.*sigma**2./totmass
  7. x= numpy.arctanh(2.*numpy.random.uniform(size=N)-1)*zh
  8. v= numpy.random.normal(size=N)*sigma
  9. v-= numpy.mean(v) # stabilize
  10. m= numpy.ones_like(x)/N*(1.+0.1*(2.*numpy.random.uniform(size=N)-1))
  11. omega= 1.1
  12. g= wendy.nbody(x,omega=omega,omega=omega)-E)/E < 10.**-6., "Energy not conserved during approximate N-body integration with external harmonic potential"
  13. cnt+= 1
  14. return None
项目:wendy    作者:jobovy    | 项目源码 | 文件源码
  1. def test_againstexact_sech2disk_manyparticles():
  2. # Test that the exact N-body and the approximate N-body agree
  3. N= 101
  4. totmass= 1.
  5. sigma= 1.
  6. zh= 2.*sigma**2./totmass
  7. x= numpy.arctanh(2.*numpy.random.uniform(size=N)-1)*zh
  8. v= numpy.random.normal(size=N)*sigma
  9. v-= numpy.mean(v) # stabilize
  10. m= numpy.ones_like(x)/N*(1.+0.1*(2.*numpy.random.uniform(size=N)-1))
  11. omega= 1.1
  12. g= wendy.nbody(x,nleap=2000,omega=omega)
  13. ge= wendy.nbody(x,tv= next(g)
  14. txe,tve= next(ge)
  15. assert numpy.all(numpy.fabs(tx-txe) < 10.**-5.), "Exact and approximate N-body give different positions"
  16. assert numpy.all(numpy.fabs(tv-tve) < 10.**-5.), "Exact and approximate N-body give different positions"
  17. cnt+= 1
  18. return None
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_branch_cuts(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, 1
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_branch_cuts_complex64(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, np.complex64
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
  1. def test_against_cmath(self):
  2. import cmath
  3.  
  4. points = [-1-1j, b))
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_branch_cuts(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, 1
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_branch_cuts_complex64(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, np.complex64
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_against_cmath(self):
  2. import cmath
  3.  
  4. points = [-1-1j, b))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_branch_cuts(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, 1
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_branch_cuts_complex64(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, np.complex64
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
  1. def test_against_cmath(self):
  2. import cmath
  3.  
  4. points = [-1-1j, b))
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_branch_cuts(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, 1
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_branch_cuts_complex64(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, np.complex64
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
  1. def test_against_cmath(self):
  2. import cmath
  3.  
  4. points = [-1-1j, b))
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_branch_cuts(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, 1
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_branch_cuts_complex64(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, np.complex64
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
  1. def test_against_cmath(self):
  2. import cmath
  3.  
  4. points = [-1-1j, b))
项目:gcn_metric_learning    作者:sk1712    | 项目源码 | 文件源码
  1. def get_net_vectors(subject_list, kind, atlas_name="aal"):
  2. """
  3. subject_list : the subject short IDs list
  4. kind : the kind of connectivity to be used,e.g. lasso,partial correlation,correlation
  5. atlas_name : name of the atlas used
  6.  
  7. returns:
  8. matrix : matrix of connectivity vectors (num_subjects x num_connections)
  9. """
  10.  
  11. # This is an alternative implementation
  12. networks = load_all_networks(subject_list, atlas_name=atlas_name)
  13. # Get Fisher transformed matrices
  14. norm_networks = [np.arctanh(mat) for mat in networks]
  15. # Get upper diagonal indices
  16. idx = np.triu_indices_from(norm_networks[0], 1)
  17. # Get vectorised matrices
  18. vec_networks = [mat[idx] for mat in norm_networks]
  19. # Each subject should be a row of the matrix
  20. matrix = np.vstack(vec_networks)
  21.  
  22. return matrix
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_branch_cuts(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, 1
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_branch_cuts_complex64(self):
  2. # check branch cuts and continuity on them
  3. yield _check_branch_cut, np.complex64
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
  1. def test_against_cmath(self):
  2. import cmath
  3.  
  4. points = [-1-1j, b))
项目:bayestsa    作者:thalesians    | 项目源码 | 文件源码
  1. def transformparameterndarray(parameterndarray, includejumps):
  2. parameterndarray = npu.tondim1(parameterndarray)
  3. res = [
  4. parameterndarray[0], # meanlogvar
  5. 2. * np.arctanh(parameterndarray[1]), # persistence
  6. np.log(parameterndarray[2] * parameterndarray[2]), # voloflogvar
  7. 2. * np.arctanh(parameterndarray[3]) # cor
  8. ]
  9. if includejumps:
  10. res.append(np.arctanh(2*parameterndarray[4] - 1)) # jumpintensity
  11. res.append(np.log(parameterndarray[5] * parameterndarray[5])) # jumpvol
  12. return np.array(res)
项目:LinearCorex    作者:gregversteeg    | 项目源码 | 文件源码
  1. def g_inv(x, t=4):
  2. """Inverse of g transform."""
  3. xp = np.clip(x, -t, t)
  4. diff = np.arctanh(np.clip(x - xp, -1 + 1e-10, 1 - 1e-10))
  5. return xp + diff
项目:iGAN    作者:junyanz    | 项目源码 | 文件源码
  1. def initialize(self, z0):
  2. z = self.opt_model[2]
  3. z.set_value(floatX(np.arctanh(z0)))
项目:iGAN    作者:junyanz    | 项目源码 | 文件源码
  1. def invert_bfgs(gen_model, invert_model, ftr_model, im, z_predict=None, npx=64):
  2. _f, z = invert_model
  3. nz = gen_model.nz
  4. if z_predict is None:
  5. z_predict = np_rng.uniform(-1., 1., size=(1, nz))
  6. else:
  7. z_predict = floatX(z_predict)
  8. z_predict = np.arctanh(z_predict)
  9. im_t = gen_model.transform(im)
  10. ftr = ftr_model(im_t)
  11.  
  12. prob = optimize.minimize(f_bfgs, z_predict, args=(_f, im_t, ftr),
  13. tol=1e-6, jac=True, method=''L-BFGS-B'', options={''maxiter'':200})
  14. print(''n_iters = %3d,f = %.3f'' % (prob.nit, prob.fun))
  15. z_opt = prob.x
  16. z_opt_n = floatX(z_opt[np.newaxis, :])
  17. [f_opt, g, gx] = _f(z_opt_n, ftr)
  18. gx = gen_model.inverse_transform(gx, npx=npx)
  19. z_opt = np.tanh(z_opt)
  20. return gx, z_opt,f_opt
项目:wendy    作者:jobovy    | 项目源码 | 文件源码
  1. def test_time():
  2. # Just run the timer...
  3. N= 101
  4. totmass= 1.
  5. sigma= 1.
  6. zh= 2.*sigma**2./totmass
  7. x= numpy.arctanh(2.*numpy.random.uniform(size=N)-1)*zh
  8. v= numpy.random.normal(size=N)*sigma
  9. v-= numpy.mean(v) # stabilize
  10. m= numpy.ones_like(x)/N*(1.+0.1*(2.*numpy.random.uniform(size=N)-1))
  11. g= wendy.nbody(x,nleap=1000,full_output=True)
  12. tx, time_elapsed= next(g)
  13. assert time_elapsed < 1., ''More than 1 second elapsed for simple problem''
  14. return None
项目:pyflux    作者:RJT1990    | 项目源码 | 文件源码
  1. def itransform_define(transform):
  2. """
  3. This function links the user''s choice of transformation with its inverse
  4. """
  5. if transform == ''tanh'':
  6. return np.arctanh
  7. elif transform == ''exp'':
  8. return np.log
  9. elif transform == ''logit'':
  10. return Family.logit
  11. elif transform is None:
  12. return np.array
  13. else:
  14. return None
项目:pyflux    作者:RJT1990    | 项目源码 | 文件源码
  1. def itransform_name_define(transform):
  2. """
  3. This function is used for model results table,displaying any transformations performed
  4. """
  5. if transform == ''tanh'':
  6. return ''arctanh''
  7. elif transform == ''exp'':
  8. return ''log''
  9. elif transform == ''logit'':
  10. return ''ilogit''
  11. elif transform is None:
  12. return ''''
  13. else:
  14. return None
项目:PyGLM    作者:Zuzu-Typ    | 项目源码 | 文件源码
  1. def atanh(v):
  2. return v.__class__(numpy.arctanh(v))
项目:cuicuilco    作者:AlbertoEsc    | 项目源码 | 文件源码
  1. def inv_clipping_sigma(x, max_in):
  2. xx = x.clip(-0.99*max_in, 0.99*max_in)
  3. return (max_in * numpy.arctanh(xx / max_in)).clip(-max_in, max_in)
项目:dyfunconn    作者:makism    | 项目源码 | 文件源码
  1. def fisher_z(data):
  2. """ Fisher''s z-transformation
  3.  
  4. For a given dataset :math:`p` bound to :math:`[0.0,1.0]`,we can use Fisher''s z-transformation to normalize it
  5. in an approximately Gaussian distribution.
  6.  
  7. This transformation is computed as follows:
  8.  
  9. .. math::
  10. z_p := \\\\frac{1}{2} \\\\text{ln} \\\\left ( \\\\frac{1+p}{1-p} \\\\right ) = \\\\text{arctanh}(p)
  11.  
  12. """
  13. return np.arctanh(data)
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def test_numpy_method():
  2. # This type of code is used frequently by PyMC3 users
  3. x = tt.dmatrix(''x'')
  4. data = np.random.rand(5, 5)
  5. x.tag.test_value = data
  6. for fct in [np.arccos,
  7. np.arctan, np.ceil, np.cos, np.cosh, np.deg2rad,
  8. np.exp, np.exp2, np.expm1, np.floor,
  9. np.log10, np.rad2deg,
  10. np.sin, np.sinh, np.tan, np.tanh, np.trunc]:
  11. y = fct(x)
  12. f = theano.function([x], y)
  13. utt.assert_allclose(np.nan_to_num(f(data)),
  14. np.nan_to_num(fct(data)))
项目:Theano-Deep-learning    作者:GeekLiB    | 项目源码 | 文件源码
  1. def impl(self, x):
  2. # If x is an int8 or uint8,numpy.arctanh will compute the result in
  3. # half-precision (float16),where we want float32.
  4. x_dtype = str(getattr(x, ''dtype'', ''''))
  5. if x_dtype in (''int8'', ''uint8''):
  6. return numpy.arctanh(x, sig=''f'')
  7. return numpy.arctanh(x)
项目:SOAR    作者:araujolma    | 项目源码 | 文件源码
  1. def calcAdimCtrl(self,alfa,beta):
  2. #u = numpy.empty((self.N,self.m))
  3. Nu = len(alfa)
  4. u = numpy.empty((Nu,2))
  5.  
  6. restrictions = self.restrictions
  7. alpha_min = restrictions[''alpha_min'']
  8. alpha_max = restrictions[''alpha_max'']
  9. beta_min = restrictions[''beta_min'']
  10. beta_max = restrictions[''beta_max'']
  11.  
  12. a1 = .5*(alpha_max + alpha_min)
  13. a2 = .5*(alpha_max - alpha_min)
  14. b1 = .5*(beta_max + beta_min)
  15. b2 = .5*(beta_max - beta_min)
  16.  
  17. alfa -= a1
  18. alfa *= 1.0/a2
  19.  
  20. beta -= b1
  21. beta *= 1.0/b2
  22.  
  23. u[:,0] = alfa.copy()
  24. u[:,1] = beta.copy()
  25.  
  26. # Basic saturation
  27. for j in range(2):
  28. for k in range(Nu):
  29. if u[k,j] > 0.99999:
  30. u[k,j] = 0.99999
  31. if u[k,j] < -0.99999:
  32. u[k,j] = -0.99999
  33.  
  34. u = numpy.arctanh(u)
  35. return u
项目:pyomo    作者:Pyomo    | 项目源码 | 文件源码
  1. def arctanh(inp):
  2. if isinstance(inp, ooarray) and inp.dtype == object:
  3. return ooarray([arctanh(elem) for elem in inp])
  4. if not isinstance(inp, oofun):
  5. return np.arctanh(inp)
  6. # Todo: move it outside of arctanh deFinition
  7. def interval(arg_inf, arg_sup):
  8. raise ''interval for arctanh is unimplemented yet''
  9. r = oofun(np.arctanh, inp, d = lambda x: FDmisc.Diag(1.0/(1 - x**2)), vectorized = True, interval = interval)
  10. return r
项目:conceptnet5    作者:ymmah    | 项目源码 | 文件源码
  1. def confidence_interval(rho, N):
  2. """
  3. Give a 95% confidence interval for a Spearman correlation score,given
  4. the correlation and the number of cases.
  5. """
  6. z = np.arctanh(rho)
  7. interval = 1.96 / np.sqrt(N - 3)
  8. low = z - interval
  9. high = z + interval
  10. return pd.Series(
  11. [rho, np.tanh(low), np.tanh(high)],
  12. index=[''acc'', ''low'', ''high'']
  13. )
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def test_numpy_ufuncs(self):
  2. # test ufuncs of numpy 1.9.2. see:
  3. # http://docs.scipy.org/doc/numpy/reference/ufuncs.html
  4.  
  5. # some functions are skipped because it may return different result
  6. # for unicode input depending on numpy version
  7.  
  8. for name, idx in compat.iteritems(self.indices):
  9. for func in [np.exp,
  10. np.log1p, np.sin,
  11. np.arccos,
  12. np.arcsinh,
  13. np.rad2deg]:
  14. if isinstance(idx, pd.tseries.base.DatetimeIndexOpsMixin):
  15. # raise TypeError or ValueError (Periodindex)
  16. # Periodindex behavior should be changed in future version
  17. with tm.assertRaises(Exception):
  18. func(idx)
  19. elif isinstance(idx, (Float64Index, Int64Index)):
  20. # coerces to float (e.g. np.sin)
  21. result = func(idx)
  22. exp = Index(func(idx.values), name=idx.name)
  23. self.assert_index_equal(result, exp)
  24. self.assertisinstance(result, pd.Float64Index)
  25. else:
  26. # raise AttributeError or TypeError
  27. if len(idx) == 0:
  28. continue
  29. else:
  30. with tm.assertRaises(Exception):
  31. func(idx)
  32.  
  33. for func in [np.isfinite, np.isinf, np.isnan, np.signbit]:
  34. if isinstance(idx, pd.tseries.base.DatetimeIndexOpsMixin):
  35. # raise TypeError or ValueError (Periodindex)
  36. with tm.assertRaises(Exception):
  37. func(idx)
  38. elif isinstance(idx, Int64Index)):
  39. # results in bool array
  40. result = func(idx)
  41. exp = func(idx.values)
  42. self.assertisinstance(result, np.ndarray)
  43. tm.assertNotisinstance(result, Index)
  44. else:
  45. if len(idx) == 0:
  46. continue
  47. else:
  48. with tm.assertRaises(Exception):
  49. func(idx)

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 模块-arctanh() 实例源码python numpy argmax的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于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 ()、数组基本属性的相关知识,请在本站寻找。

本文标签: