pythonabs_Python numpy.abs() 使用实例

这是一个关于如何使用Python的numpy.abs()函数的代码示例集合。示例包括各种数学操作,如傅立叶变换、概率分布量化、数据处理等。通过这些例子,可以了解到该函数在不同场景下的应用。
摘要由CSDN通过智能技术生成

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def roll_zeropad(a, shift, axis=None):

a = np.asanyarray(a)

if shift == 0: return a

if axis is None:

n = a.size

reshape = True

else:

n = a.shape[axis]

reshape = False

if np.abs(shift) > n:

res = np.zeros_like(a)

elif shift < 0:

shift += n

zeros = np.zeros_like(a.take(np.arange(n-shift), axis))

res = np.concatenate((a.take(np.arange(n-shift,n), axis), zeros), axis)

else:

zeros = np.zeros_like(a.take(np.arange(n-shift,n), axis))

res = np.concatenate((zeros, a.take(np.arange(n-shift), axis)), axis)

if reshape:

return res.reshape(a.shape)

else:

return res

Example 2

def mypsd(Rates,time_range,bin_w = 5., nmax = 4000):

bins = np.arange(0,len(time_range),1)

#print bins

a,b = np.histogram(Rates, bins)

ff = (1./len(bins))*abs(np.fft.fft(Rates- np.mean(Rates)))**2

Fs = 1./(1*0.001)

freq2 = np.fft.fftfreq(len(bins))[0:len(bins/2)+1] # d= dt

freq = np.fft.fftfreq(len(bins))[:len(ff)/2+1]

px = ff[0:len(ff)/2+1]

max_px = np.max(px[1:])

idx = px == max_px

corr_freq = freq[pl.find(idx)]

new_px = px

max_pow = new_px[pl.find(idx)]

return new_px,freq,corr_freq[0],freq2, max_pow

Example 3

def test_quantize_from_probs2(size, resolution):

set_random_seed(make_seed(size, resolution))

probs = np.exp(np.random.random(size)).astype(np.float32)

probs2 = probs.reshape((1, size))

quantized = quantize_from_probs2(probs2, resolution)

assert quantized.shape == probs2.shape

assert quantized.dtype == np.int8

assert np.all(quantized.sum(axis=1) == resolution)

# Check that quantized result is closer to target than any other value.

quantized = quantized.reshape((size, ))

target = resolution * probs / probs.sum()

distance = np.abs(quantized - target).sum()

for combo in itertools.combinations(range(size), resolution):

other = np.zeros(size, np.int8)

for i in combo:

other[i] += 1

assert other.sum() == resolution

other_distance = np.abs(other - target).sum()

assert distance <= other_distance

Example 4

def contest(self, b, g, r):

""" Search for biased BGR values

Finds closest neuron (min dist) and updates self.freq

finds best neuron (min dist-self.bias) and returns position

for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative

self.bias[i] = self.GAMMA*((1/self.NETSIZE)-self.freq[i])"""

i, j = self.SPECIALS, self.NETSIZE

dists = abs(self.network[i:j] - np.array([b,g,r])).sum(1)

bestpos = i + np.argmin(dists)

biasdists = dists - self.bias[i:j]

bestbiaspos = i + np.argmin(biasdists)

self.freq[i:j] *= (1-self.BETA)

self.bias[i:j] += self.BETAGAMMA * self.freq[i:j]

self.freq[bestpos] += self.BETA

self.bias[bestpos] -= self.BETAGAMMA

return bestbiaspos

Example 5

def Kdim(self, kdimParams):

if (self.prevKdimParams is not None and np.max(np.abs(kdimParams-self.prevKdimParams)) < self.epsilon): return self.cache['Kdim']

K = np.zeros((self.n, self.n, len(self.kernels)))

params_ind = 0

for k_i, k in enumerate(self.kernels):

numHyp = k.getNumParams()

kernelParams_range = np.array(xrange(params_ind, params_ind+numHyp), dtype=np.int)

kernel_params = kdimParams[kernelParams_range]

if ((numHyp == 0 and 'Kdim' in self.cache) or (numHyp>0 and self.prevKdimParams is not None and np.max(np.abs(kernel_params-self.prevKdimParams[kernelParams_range])) < self.epsilon)):

K[:,:,k_i] = self.cache['Kdim'][:,:,k_i]

else:

K[:,:,k_i] = k.getTrainKernel(kernel_params)

params_ind += numHyp

self.prevKdimParams = kdimParams.copy()

self.cache['Kdim'] = K

return K

Example 6

def draw(self, layout='circular', figsize=None):

"""Draw all graphs that describe the DGM in a common figure

Parameters

----------

layout : str

possible are 'circular', 'shell', 'spring'

figsize : tuple(int)

tuple of two integers denoting the mpl figsize

Returns

-------

fig : figure

"""

layouts = {

'circular': nx.circular_layout,

'shell': nx.shell_layout,

'spring': nx.spring_layout

}

figsize = (10, 10) if figsize is None else figsize

fig = plt.figure(figsize=figsize)

rocls = np.ceil(np.sqrt(len(self.graphs)))

for i, graph in enumerate(self.graphs):

ax = fig.add_subplot(rocls, rocls, i+1)

ax.set_title('Graph ' + str(i+1))

ax.axis('off')

ax.set_frame_on(False)

g = graph.nxGraph

weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]

nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),

width=2, edge_color=weights)

return fig

Example 7

def draw(self, layout='circular', figsize=None):

"""Draw graph in a matplotlib environment

Parameters

----------

layout : str

possible are 'circular', 'shell', 'spring'

figsize : tuple(int)

tuple of two integers denoting the mpl figsize

Returns

-------

fig : figure

"""

layouts = {

'circular': nx.circular_layout,

'shell': nx.shell_layout,

'spring': nx.spring_layout

}

figsize = (10, 10) if figsize is None else figsize

fig = plt.figure(figsize=figsize)

ax = fig.add_subplot(1, 1, 1)

ax.axis('off')

ax.set_frame_on(False)

g = self.nxGraph

weights = [abs(g.edge[i][j]['weight']) * 5 for i, j in g.edges()]

nx.draw_networkx(g, pos=layouts[layout](g), ax=ax, edge_cmap=plt.get_cmap('Reds'),

width=2, edge_color=weights)

return fig

Example 8

def scale_variance(Theta, eps):

"""Allows to scale a Precision Matrix such that its

corresponding covariance has unit variance

Parameters

----------

Theta: ndarray

Precision Matrix

eps: float

values to threshold to zero

Returns

-------

Theta: ndarray

Precision of rescaled Sigma

Sigma: ndarray

Sigma with ones on diagonal

"""

Sigma = np.linalg.inv(Theta)

V = np.diag(np.sqrt(np.diag(Sigma) ** -1))

Sigma = V.dot(Sigma).dot(V.T) # = VSV

Theta = np.linalg.inv(Sigma)

Theta[np.abs(Theta) <= eps] = 0.

return Theta, Sigma

Example 9

def idamax(a):

""" Returns the index of maximum absolute value (positive or negative)

in the input array a.

Note: Loose

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值