本文整理汇总了Python中numpy.convolve方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.convolve方法的具体用法?Python numpy.convolve怎么用?Python numpy.convolve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.convolve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compute_fitness
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def compute_fitness(genome, net, episodes, min_reward, max_reward):
m = int(round(np.log(0.01) / np.log(genome.discount)))
discount_function = [genome.discount ** (m - i) for i in range(m + 1)]
reward_error = []
for score, data in episodes:
# Compute normalized discounted reward.
dr = np.convolve(data[:,-1], discount_function)[m:]
dr = 2 * (dr - min_reward) / (max_reward - min_reward) - 1.0
dr = np.clip(dr, -1.0, 1.0)
for row, dr in zip(data, dr):
observation = row[:8]
action = int(row[8])
output = net.activate(observation)
reward_error.append(float((output[action] - dr) ** 2))
return reward_error
示例2: test_conv
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def test_conv(mode, method):
reload(convolution)
# time vector for stimulus (long)
stim_dur = 0.5 # seconds
tsample = 0.001 / 1000
t = np.arange(0, stim_dur, tsample)
# stimulus (10 Hz anondic and cathodic pulse train)
stim = np.zeros_like(t)
stim[::1000] = 1
stim[100::1000] = -1
# kernel
_, gg = gamma(1, 0.005, tsample)
# make sure conv returns the same result as np.convolve for all modes:
npconv = np.convolve(stim, gg, mode=mode)
conv = convolution.conv(stim, gg, mode=mode, method=method)
npt.assert_equal(conv.shape, npconv.shape)
npt.assert_almost_equal(conv, npconv)
with pytest.raises(ValueError):
convolution.conv(gg, stim, mode="invalid")
with pytest.raises(ValueError):
convolution.conv(gg, stim, method="invalid")
示例3: testCausalConv
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def testCausalConv(self):
"""Tests that the op is equivalent to a numpy implementation."""
x1 = np.arange(1, 21, dtype=np.float32)
x = np.append(x1, x1)
x = np.reshape(x, [2, 20, 1])
f = np.reshape(np.array([1, 1], dtype=np.float32), [2, 1, 1])
out = causal_conv(x, f, 4)
with self.test_session() as sess:
result = sess.run(out)
# Causal convolution using numpy
ref = np.convolve(x1, [1, 0, 0, 0, 1], mode='valid')
ref = np.append(ref, ref)
ref = np.reshape(ref, [2, 16, 1])
self.assertAllEqual(result, ref)
示例4: __box_filter_convolve
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def __box_filter_convolve(self, path, window_size):
"""
An internal method that applies *normalized linear box filter* to path w.r.t averaging window
Parameters:
* path (numpy.ndarray): a cumulative sum of transformations
* window_size (int): averaging window size
"""
# pad path to size of averaging window
path_padded = np.pad(path, (window_size, window_size), "median")
# apply linear box filter to path
path_smoothed = np.convolve(path_padded, self.__box_filter, mode="same")
# crop the smoothed path to original path
path_smoothed = path_smoothed[window_size:-window_size]
# assert if cropping is completed
assert path.shape == path_smoothed.shape
# return smoothed path
return path_smoothed
示例5: _zseries_mul
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def _zseries_mul(z1, z2):
"""Multiply two z-series.
Multiply two z-series to produce a z-series.
Parameters
----------
z1, z2 : 1-D ndarray
The arrays must be 1-D but this is not checked.
Returns
-------
product : 1-D ndarray
The product z-series.
Notes
-----
This is simply convolution. If symmetric/anti-symmetric z-series are
denoted by S/A then the following rules apply:
S*S, A*A -> S
S*A, A*S -> A
"""
return np.convolve(z1, z2)
示例6: convolve_beam
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def convolve_beam(self, current, wake):
"""
convolve wake with beam current
:param current: current[:, 0] - s in [m], current[:, 1] - current in [A]
:param wake: wake function in form: wake(s, b, t, period)
:return:
"""
s_shift = current[0, 0]
current[:, 0] -= s_shift
s = current[:, 0]
step = (s[-1] - s[0]) / (len(s) - 1)
q = current[:, 1] / speed_of_light
w = np.array(
[wake(si, b=self.b, t=self.t, period=self.period) for si in s]) * 377 * speed_of_light / (
4 * np.pi)
wake = np.convolve(q, w) * step
s_new = np.cumsum(np.ones(len(wake))) * step
wake_kick = np.vstack((s_new, wake))
return wake_kick.T
示例7: forecast3
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def forecast3(self, step_ahead=1, start=None): #, end=None):
'''another try for h-step ahead forecasting
'''
from .arima_process import arma2ma, ArmaProcess
p,q = self.nar, self.nma
k=0
ar = self.params[k:k+p]
ma = self.params[k+p:k+p+q]
marep = arma2ma(ar,ma, start)[step_ahead+1:] #truncated ma representation
errors = self.error_estimate
forecasts = np.convolve(errors, marep)
return forecasts#[-(errors.shape[0] - start-5):] #get 5 overlapping for testing
#copied from arima.ARIMA
#TODO: is this needed as a method at all?
#JP: not needed in this form, but can be replace with using the parameters
示例8: create_harmonic_mask
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def create_harmonic_mask(self, melody_signal):
"""
Creates a harmonic mask from the melody signal. The mask is smoothed to reduce
the effects of discontinuities in the melody synthesizer.
"""
stft = np.abs(melody_signal.stft())
# Need to threshold the melody stft since the synthesized
# F0 sequence overtones are at different weights.
stft = stft ** self.compression
stft /= np.maximum(np.max(stft, axis=1, keepdims=True), 1e-7)
mask = np.empty(self.stft.shape)
# Smoothing the mask row-wise using a low-pass filter to
# get rid of discontuinities in the mask.
kernel = np.full((1, self.smooth_length), 1 / self.smooth_length)
for ch in range(self.audio_signal.num_channels):
mask[..., ch] = convolve(stft[..., ch], kernel)
return mask
示例9: smooth_curve
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def smooth_curve(x):
"""用于使损失函数的图形变圆滑
参考:http://glowingpython.blogspot.jp/2012/02/convolution-with-numpy.html
"""
window_len = 11
s = np.r_[x[window_len-1:0:-1], x, x[-1:-window_len:-1]]
w = np.kaiser(window_len, 2)
y = np.convolve(w/w.sum(), s, mode='valid')
return y[5:len(y)-5]
示例10: preproc_file
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def preproc_file(deriv_dir, sub_metadata, deriv_bold_fname=deriv_bold_fname):
deriv_bold = deriv_dir.ensure(deriv_bold_fname)
with open(str(sub_metadata), 'r') as md:
bold_metadata = json.load(md)
tr = bold_metadata["RepetitionTime"]
# time_points
tp = 200
ix = np.arange(tp)
# create voxel timeseries
task_onsets = np.zeros(tp)
# add activations at every 40 time points
# waffles
task_onsets[0::40] = 1
# fries
task_onsets[3::40] = 1.5
# milkshakes
task_onsets[6::40] = 2
signal = np.convolve(task_onsets, spm_hrf(tr))[0:len(task_onsets)]
# csf
csf = np.cos(2*np.pi*ix*(50/tp)) * 0.1
# white matter
wm = np.sin(2*np.pi*ix*(22/tp)) * 0.1
# voxel time series (signal and noise)
voxel_ts = signal + csf + wm
# a 4d matrix with 2 identical timeseries
img_data = np.array([[[voxel_ts, voxel_ts]]])
# make a nifti image
img = nib.Nifti1Image(img_data, np.eye(4))
# save the nifti image
img.to_filename(str(deriv_bold))
return deriv_bold
示例11: smooth
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def smooth(data, winLen=11, window='hanning', check=False):
"""
Smooth 1D data using window function and length.
:Parameters:
#. data (numpy.ndarray): the 1D numpy data.
#. winLen (integer): the smoothing window length.
#. window (str): The smoothing window type. Can be anything among
'flat', 'hanning', 'hamming', 'bartlett' and 'blackman'.
#. check (boolean): whether to check arguments before smoothing data.
:Returns:
#. smoothed (numpy.ndarray): the smoothed 1D data array.
"""
if check:
assert isinstance(data, np.ndarray), Logger.error("data must be numpy.ndarray instance")
assert len(data.shape)==1, Logger.error("data must be of 1 dimensions")
assert is_integer(winLen), LOGGER.error("winLen must be an integer")
winLen = int(bin)
assert winLen>=3, LOGGER.error("winLen must be bigger than 3")
assert data.size < winLen, LOGGER.error("data needs to be bigger than window size.")
assert window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman'], LOGGER.error("window must be any of ('flat', 'hanning', 'hamming', 'bartlett', 'blackman')")
# compute smoothed data
s=np.r_[data[winLen-1:0:-1],data,data[-1:-winLen:-1]]
if window == 'flat': #moving average
w=np.ones(winLen,'d')
else:
w=eval('np.'+window+'(winLen)')
S=np.convolve(w/w.sum(),s, mode='valid')
# get data and return
f = winLen/2
t = f-winLen+1
return S[f:t]
示例12: smooth_reward_curve
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def smooth_reward_curve(x, y):
halfwidth = int(np.ceil(len(x) / 60)) # Halfwidth of our smoothing convolution
k = halfwidth
xsmoo = x
ysmoo = np.convolve(y, np.ones(2 * k + 1), mode='same') / np.convolve(np.ones_like(y), np.ones(2 * k + 1),
mode='same')
return xsmoo, ysmoo
示例13: nSMA
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def nSMA(values, window):
weigths = np.repeat(1.0, window)/window
smas = np.convolve(values, weigths, 'valid')
return smas # as a numpy array
########EMA CALC ADDED############
示例14: ExpMovingAverage
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def ExpMovingAverage(values, window):
weights = np.exp(np.linspace(-1., 0., window))
weights /= weights.sum()
a = np.convolve(values, weights, mode='full')[:len(values)]
a[:window] = a[window]
return a
示例15: _ecg_findpeaks_promac_convolve
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import convolve [as 别名]
def _ecg_findpeaks_promac_convolve(signal, peaks, sampling_rate=1000):
x = np.zeros(len(signal))
x[peaks] = 1
# Because a typical QRS is roughly defined within about 100ms
sd = sampling_rate / 10
shape = scipy.stats.norm.pdf(np.linspace(-sd * 4, sd * 4, num=int(sd * 8)), loc=0, scale=sd)
return np.convolve(x, shape, "same") # Return convolved
# =============================================================================
# NeuroKit
# =============================================================================