本文整理汇总了Python中numpy.insert方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.insert方法的具体用法?Python numpy.insert怎么用?Python numpy.insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.insert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: predict_seq_mul
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def predict_seq_mul(model, data, win_size, pred_len):
"""
Predicts multiple sequences
Input: keras model, testing data, window size, prediction length
Output: Predicted sequence
Note: Run from timeSeriesPredict.py
"""
pred_seq = []
for i in range(len(data)//pred_len):
current = data[i * pred_len]
predicted = []
for j in range(pred_len):
predicted.append(model.predict(current[None, :, :])[0, 0])
current = current[1:]
current = np.insert(current, [win_size - 1], predicted[-1], axis=0)
pred_seq.append(predicted)
return pred_seq
示例2: predict_all
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def predict_all(X, all_theta):
rows = X.shape[0]
params = X.shape[1]
num_labels = all_theta.shape[0]
# same as before, insert ones to match the shape
X = np.insert(X, 0, values=np.ones(rows), axis=1)
# convert to matrices
X = np.matrix(X)
all_theta = np.matrix(all_theta)
# compute the class probability for each class on each training instance
h = sigmoid(X * all_theta.T)
# create array of the index with the maximum probability
h_argmax = np.argmax(h, axis=1)
# because our array was zero-indexed we need to add one for the true label prediction
h_argmax = h_argmax + 1
return h_argmax
示例3: prepare_poly_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def prepare_poly_data(*args, power):
"""
args: keep feeding in X, Xval, or Xtest
will return in the same order
"""
def prepare(x):
# expand feature
df = poly_features(x, power=power)
# normalization
ndarr = normalize_feature(df).as_matrix()
# add intercept term
return np.insert(ndarr, 0, np.ones(ndarr.shape[0]), axis=1)
return [prepare(x) for x in args]
示例4: collect
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def collect(self, index, dataDict, check=True):
"""
Collect atom given its index.
:Parameters:
#. index (int): The atom index to collect.
#. dataDict (dict): The atom data dict to collect.
#. check (boolean): Whether to check dataDict keys before
collecting. If set to False, user promises that collected
data is a dictionary and contains the needed keys.
"""
assert not self.is_collected(index), LOGGER.error("attempting to collect and already collected atom of index '%i'"%index)
# add data
if check:
assert isinstance(dataDict, dict), LOGGER.error("dataDict must be a dictionary of data where keys are dataKeys")
assert tuple(sorted(dataDict)) == self.__dataKeys, LOGGER.error("dataDict keys don't match promised dataKeys")
self.__collectedData[index] = dataDict
# set indexes sorted array
idx = np.searchsorted(a=self.__indexesSortedArray, v=index, side='left')
self.__indexesSortedArray = np.insert(self.__indexesSortedArray, idx, index)
# set state
self.__state = str(uuid.uuid1())
示例5: release
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def release(self, index):
"""
Release atom from list of collected atoms and return its
collected data.
:Parameters:
#. index (int): The atom index to release.
:Returns:
#. dataDict (dict): The released atom collected data.
"""
if not self.is_collected(index):
LOGGER.warn("Attempting to release atom %i that is not collected."%index)
return
index = self.__collectedData.pop(index)
# set indexes sorted array
idx = np.searchsorted(a=self.__indexesSortedArray, v=index, side='left')
self.__indexesSortedArray = np.insert(self.__indexesSortedArray, idx, index)
# set state
self.__state = str(uuid.uuid1())
# return
return index
示例6: regression_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def regression_data():
f = open(path + "regression_data1.txt")
data = np.loadtxt(f, delimiter=",")
x1 = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
y1 = data[:, 1]
f = open(path + "regression_data2.txt")
data = np.loadtxt(f, delimiter=",")
x2 = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
y2 = data[:, 1]
x1 = np.vstack((x1, x2))
y1 = np.hstack((y1, y2))
f = open(path + "regression_data_test1.txt")
data = np.loadtxt(f, delimiter=",")
x1_test = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
y1_test = data[:, 1]
f = open(path + "regression_data_test2.txt")
data = np.loadtxt(f, delimiter=",")
x2_test = np.insert(data[:, 0].reshape(len(data), 1), 0, np.ones(len(data)), axis=1)
y2_test = data[:, 1]
x1_test = np.vstack((x1_test, x2_test))
y1_test = np.hstack((y1_test, y2_test))
return x1, y1, x1_test, y1_test
示例7: ex3
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def ex3(replication=2):
f = open(path + "ex3.txt")
train_data = np.loadtxt(f, delimiter=",")
f = open(path + "ex3_test.txt")
test_data = np.loadtxt(f, delimiter=",")
x_train = np.insert(train_data[:, (0, 1)], 0, np.ones(len(train_data)), axis=1)
y_train = train_data[:, 2]
x_test = np.insert(test_data[:, (0, 1)], 0, np.ones(len(test_data)), axis=1)
y_test = test_data[:, 2]
for i in range(replication - 1):
x_train = np.vstack((x_train, np.insert(train_data[:, (0, 1)], 0, np.ones(len(train_data)), axis=1)))
y_train = np.hstack((y_train, train_data[:, 2]))
x_test = np.vstack((x_test, np.insert(test_data[:, (0, 1)], 0, np.ones(len(test_data)), axis=1)))
y_test = np.hstack((y_test, test_data[:, 2]))
return x_train, y_train, x_test, y_test
示例8: _correct_missed
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def _correct_missed(missed_idcs, peaks):
corrected_peaks = peaks.copy()
missed_idcs = np.array(missed_idcs)
# Calculate the position(s) of new beat(s). Make sure to not generate
# negative indices. prev_peaks and next_peaks must have the same
# number of elements.
valid_idcs = np.logical_and(missed_idcs > 1, missed_idcs < len(corrected_peaks)) # pylint: disable=E1111
missed_idcs = missed_idcs[valid_idcs]
prev_peaks = corrected_peaks[[i - 1 for i in missed_idcs]]
next_peaks = corrected_peaks[missed_idcs]
added_peaks = prev_peaks + (next_peaks - prev_peaks) / 2
# Add the new peaks before the missed indices (see numpy docs).
corrected_peaks = np.insert(corrected_peaks, missed_idcs, added_peaks)
return corrected_peaks
示例9: _interpolate_missing
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def _interpolate_missing(peaks, interval, interval_max, sampling_rate):
outliers = interval > interval_max
outliers_loc = np.where(outliers)[0]
if np.sum(outliers) == 0:
return peaks, False
# Delete large interval and replace by two unknown intervals
interval[outliers] = np.nan
interval = np.insert(interval, outliers_loc, np.nan)
# new_peaks_location = np.where(np.isnan(interval))[0]
# Interpolate values
interval = pd.Series(interval).interpolate().values
peaks_corrected = _period_to_location(interval, sampling_rate, first_location=peaks[0])
peaks = np.insert(peaks, outliers_loc, peaks_corrected[outliers_loc + np.arange(len(outliers_loc))])
return peaks, True
示例10: _RLFindRoots
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def _RLFindRoots(nump, denp, kvect):
"""Find the roots for the root locus."""
# Convert numerator and denominator to polynomials if they aren't
roots = []
for k in kvect:
curpoly = denp + k * nump
curroots = curpoly.r
if len(curroots) < denp.order:
# if I have fewer poles than open loop, it is because i have
# one at infinity
curroots = np.insert(curroots, len(curroots), np.inf)
curroots.sort()
roots.append(curroots)
mymat = row_stack(roots)
return mymat
示例11: SetDistribution
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def SetDistribution(self, distinct_values):
"""This is all the values this column will ever see."""
assert self.all_distinct_values is None
# pd.isnull returns true for both np.nan and np.datetime64('NaT').
is_nan = pd.isnull(distinct_values)
contains_nan = np.any(is_nan)
dv_no_nan = distinct_values[~is_nan]
# NOTE: np.sort puts NaT values at beginning, and NaN values at end.
# For our purposes we always add any null value to the beginning.
vs = np.sort(np.unique(dv_no_nan))
if contains_nan and np.issubdtype(distinct_values.dtype, np.datetime64):
vs = np.insert(vs, 0, np.datetime64('NaT'))
elif contains_nan:
vs = np.insert(vs, 0, np.nan)
if self.distribution_size is not None:
assert len(vs) == self.distribution_size
self.all_distinct_values = vs
self.distribution_size = len(vs)
return self
示例12: estimate_norm
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def estimate_norm(lmk, image_size = 112, mode='arcface'):
assert lmk.shape==(5,2)
tform = trans.SimilarityTransform()
lmk_tran = np.insert(lmk, 2, values=np.ones(5), axis=1)
min_M = []
min_index = []
min_error = float('inf')
if mode=='arcface':
assert image_size==112
src = arcface_src
else:
src = src_map[image_size]
for i in np.arange(src.shape[0]):
tform.estimate(lmk, src[i])
M = tform.params[0:2,:]
results = np.dot(M, lmk_tran.T)
results = results.T
error = np.sum(np.sqrt(np.sum((results - src[i]) ** 2,axis=1)))
# print(error)
if error< min_error:
min_error = error
min_M = M
min_index = i
return min_M, min_index
示例13: _build_paramvec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def _build_paramvec(self):
""" Resizes self._paramvec and updates gpindices & parent members as needed,
and will initialize new elements of _paramvec, but does NOT change
existing elements of _paramvec (use _update_paramvec for this)"""
v = _np.empty(0, 'd'); off = 0
# Step 2: add parameters that don't exist yet
for obj in self.values():
if obj.gpindices is None or obj.parent is not self:
#Assume all parameters of obj are new independent parameters
v = _np.insert(v, off, obj.to_vector())
num_new_params = obj.allocate_gpindices(off, self)
off += num_new_params
else:
inds = obj.gpindices_as_array()
M = max(inds) if len(inds) > 0 else -1; L = len(v)
if M >= L:
#Some indices specified by obj are absent, and must be created.
w = obj.to_vector()
v = _np.concatenate((v, _np.empty(M + 1 - L, 'd')), axis=0) # [v.resize(M+1) doesn't work]
for ii, i in enumerate(inds):
if i >= L: v[i] = w[ii]
off = M + 1
return v
示例14: calc_axon_contribution
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def calc_axon_contribution(self, axons):
xyret = np.column_stack((self.grid.xret.ravel(),
self.grid.yret.ravel()))
# Only include axon segments that are < `max_d2` from the soma. These
# axon segments will have `sensitivity` > `self.min_ax_sensitivity`:
max_d2 = -2.0 * self.axlambda ** 2 * np.log(self.min_ax_sensitivity)
axon_contrib = []
for xy, bundle in zip(xyret, axons):
idx = np.argmin((bundle[:, 0] - xy[0]) ** 2 +
(bundle[:, 1] - xy[1]) ** 2)
# Cut off the part of the fiber that goes beyond the soma:
axon = np.flipud(bundle[0: idx + 1, :])
# Add the exact location of the soma:
axon = np.insert(axon, 0, xy, axis=0)
# For every axon segment, calculate distance from soma by
# summing up the individual distances between neighboring axon
# segments (by "walking along the axon"):
d2 = np.cumsum(np.diff(axon[:, 0], axis=0) ** 2 +
np.diff(axon[:, 1], axis=0) ** 2)
idx_d2 = d2 < max_d2
sensitivity = np.exp(-d2[idx_d2] / (2.0 * self.axlambda ** 2))
idx_d2 = np.insert(idx_d2, 0, False)
contrib = np.column_stack((axon[idx_d2, :], sensitivity))
axon_contrib.append(contrib)
return axon_contrib
示例15: test_AxonMapModel_calc_axon_contribution
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import insert [as 别名]
def test_AxonMapModel_calc_axon_contribution(engine):
model = AxonMapModel(xystep=2, engine=engine, n_axons=10,
xrange=(-20, 20), yrange=(-15, 15),
axons_range=(-30, 30))
model.build()
xyret = np.column_stack((model.spatial.grid.xret.ravel(),
model.spatial.grid.yret.ravel()))
bundles = model.spatial.grow_axon_bundles()
axons = model.spatial.find_closest_axon(bundles)
contrib = model.spatial.calc_axon_contribution(axons)
# Check lambda math:
for ax, xy in zip(contrib, xyret):
axon = np.insert(ax, 0, list(xy) + [0], axis=0)
d2 = np.cumsum(np.diff(axon[:, 0], axis=0) ** 2 +
np.diff(axon[:, 1], axis=0) ** 2)
sensitivity = np.exp(-d2 / (2.0 * model.spatial.axlambda ** 2))
npt.assert_almost_equal(sensitivity, ax[:, 2])