本文整理汇总了Python中numpy.array方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.array方法的具体用法?Python numpy.array怎么用?Python numpy.array使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.array方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def __init__(self, input_wave_file, output_wave_file, target_phrase):
self.pop_size = 100
self.elite_size = 10
self.mutation_p = 0.005
self.noise_stdev = 40
self.noise_threshold = 1
self.mu = 0.9
self.alpha = 0.001
self.max_iters = 3000
self.num_points_estimate = 100
self.delta_for_gradient = 100
self.delta_for_perturbation = 1e3
self.input_audio = load_wav(input_wave_file).astype(np.float32)
self.pop = np.expand_dims(self.input_audio, axis=0)
self.pop = np.tile(self.pop, (self.pop_size, 1))
self.output_wave_file = output_wave_file
self.target_phrase = target_phrase
self.funcs = self.setup_graph(self.pop, np.array([toks.index(x) for x in target_phrase]))
示例2: create_lines
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def create_lines(self, x, varieties):
"""
Draw just the data portion.
"""
lines = pd.DataFrame()
for i, var in enumerate(varieties):
self.legend.append(var)
data = varieties[var]["data"]
color = get_color(varieties[var], i)
x_array = np.array(x)
y_array = np.array(data)
line = pd.DataFrame({"x": x_array,
"y": y_array,
"color": color,
"var": var})
lines = lines.append(line, ignore_index=True, sort=False)
return lines
示例3: matrix_reduction
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def matrix_reduction(agent):
matrix, res = agent["strategy"]["data_collection"](agent)
col = len(matrix[0])
if col > len(matrix): # not enought for matrix reduction
return -1
i = 0
x = []
while i < len(matrix) and len(x) == 0:
A = numpy.array(matrix[i:i + col])
b = numpy.array(res[i:i + col])
try:
x = numpy.linalg.solve(A, b)
except numpy.linalg.LinAlgError:
i += 1
if len(x) == 0:
return -1
else:
for emoji in agent["emoji_experienced"]:
index = agent["emoji_experienced"][emoji]
agent["emoji_scores"][emoji] = round(x[index][0], 2)
agent["predicted_base_line"] = round(x[-1][0], 2)
return 0
示例4: setup
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def setup(self, bottom, top):
layer_params = yaml.load(self.param_str)
self._layer_params = layer_params
# default batch_size = 256
self._batch_size = int(layer_params.get('batch_size', 256))
self._resize = layer_params.get('resize', -1)
self._mean_file = layer_params.get('mean_file', None)
self._source_type = layer_params.get('source_type', 'CSV')
self._shuffle = layer_params.get('shuffle', False)
# read image_mean from file and preload all data into memory
# will read either file or array into self._mean
self.set_mean()
self.preload_db()
self._compressed = self._layer_params.get('compressed', True)
if not self._compressed:
self.decompress_data()
示例5: get_next_minibatch
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def get_next_minibatch(self):
if self._prefetch:
# get mini-batch from prefetcher
batch = self._conn.recv()
else:
# generate using in-thread functions
data = []
p_data = []
n_data = []
label = []
for i in range(self._batch_size):
datum_ = self.get_a_datum()
data.append(datum_[0])
p_data.append(datum_[1])
n_data.append(datum_[2])
if len(datum_) == 4:
# datum and label / margin
label.append(datum_[-1])
batch = [np.array(data),
np.array(p_data),
np.array(n_data)]
if len(label):
label = np.array(label).reshape(self._batch_size, 1, 1, 1)
batch.append(label)
return batch
示例6: load_predictions
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def load_predictions(env, nclasses):
path = os.path.join(env.stats_dir(), "predictions.csv")
if not os.path.exists(path):
raise FileExistsError(path)
with open(path, newline='') as csvfile:
y_score = []
y_test = []
csv_reader = csv.reader(csvfile, dialect="excel")
for row in csv_reader:
assert len(row) == nclasses * 2
y_score.append(list(map(float, row[:nclasses])))
y_test.append(list(map(float, row[nclasses:])))
y_score = np.array(y_score)
y_test = np.array(y_test)
return y_test, y_score
示例7: _scale
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def _scale(self, init_pos):
_min = -0.5
_max = 0.5
pos = dict()
max_x = max([init_pos[id][0] for id in init_pos])
min_x = min([init_pos[id][0] for id in init_pos])
max_y = max([init_pos[id][1] for id in init_pos])
min_y = min([init_pos[id][1] for id in init_pos])
for id in init_pos:
x = init_pos[id][0]
y = init_pos[id][1]
# standardize
x = (x - min_x) / (max_x - min_x)
y = (y - min_y) / (max_y - min_y)
# rescale
x = x * (_max - _min) + _min
y = y * (_max - _min) + _min
pos[id] = np.array([x, y])
return pos
示例8: make_train_test_sets
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def make_train_test_sets(pos_graphs, neg_graphs,
test_proportion=.3, random_state=2):
"""make_train_test_sets."""
random.seed(random_state)
random.shuffle(pos_graphs)
random.shuffle(neg_graphs)
pos_dim = len(pos_graphs)
neg_dim = len(neg_graphs)
tr_pos_graphs = pos_graphs[:-int(pos_dim * test_proportion)]
te_pos_graphs = pos_graphs[-int(pos_dim * test_proportion):]
tr_neg_graphs = neg_graphs[:-int(neg_dim * test_proportion)]
te_neg_graphs = neg_graphs[-int(neg_dim * test_proportion):]
tr_graphs = tr_pos_graphs + tr_neg_graphs
te_graphs = te_pos_graphs + te_neg_graphs
tr_targets = [1] * len(tr_pos_graphs) + [0] * len(tr_neg_graphs)
te_targets = [1] * len(te_pos_graphs) + [0] * len(te_neg_graphs)
tr_graphs, tr_targets = paired_shuffle(tr_graphs, tr_targets)
te_graphs, te_targets = paired_shuffle(te_graphs, te_targets)
return (tr_graphs, np.array(tr_targets)), (te_graphs, np.array(te_targets))
示例9: plot_stats
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def plot_stats(x=None, y=None, label=None, color='navy'):
"""plot_stats."""
y = np.array(y)
y0 = y[0]
y1 = y[1]
y2 = y[2]
y3 = y[3]
y4 = y[4]
plt.fill_between(x, y3, y4, color=color, alpha=0.08)
plt.fill_between(x, y1, y2, color=color, alpha=0.08)
plt.plot(x, y0, '-', lw=2, color=color, label=label)
plt.plot(x, y0,
linestyle='None',
markerfacecolor='white',
markeredgecolor=color,
marker='o',
markeredgewidth=2,
markersize=8)
示例10: make_data_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def make_data_matrix(positive_data_matrix=None,
negative_data_matrix=None,
target=None):
"""make_data_matrix."""
assert(positive_data_matrix is not None), 'ERROR: expecting non null\
positive_data_matrix'
if negative_data_matrix is None:
negative_data_matrix = positive_data_matrix.multiply(-1)
if target is None and negative_data_matrix is not None:
yp = [1] * positive_data_matrix.shape[0]
yn = [-1] * negative_data_matrix.shape[0]
y = np.array(yp + yn)
data_matrix = vstack(
[positive_data_matrix, negative_data_matrix], format="csr")
if target is not None:
data_matrix = positive_data_matrix
y = target
return data_matrix, y
示例11: _annotate_importance
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def _annotate_importance(self, seq, data_matrix):
# compute distance from hyperplane as proxy of vertex importance
if self.estimator is None:
# if we do not provide an estimator then consider default margin of
# 1 for all vertices
scores = np.array([1] * data_matrix.shape[0])
else:
if hasattr(self.estimator, 'decision_function'):
scores = self.estimator.decision_function(data_matrix)
elif hasattr(self.estimator, 'predict_proba'):
scores = self.estimator.predict_proba(data_matrix)
scores = scores[:, -1]
# compute the list of sparse vectors representation
vec = []
for i in range(data_matrix.shape[0]):
vec.append(data_matrix.getrow(i))
return scores, vec
示例12: lk
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def lk(E=1.):
"""element stiffness matrix"""
nu = 0.3
k = np.array([0.5 - nu / 6., 0.125 + nu / 8., -0.25 - nu / 12.,
-0.125 + 0.375 * nu, -0.25 + nu / 12., -0.125 - nu / 8., nu / 6.,
0.125 - 0.375 * nu])
KE = E / (1 - nu**2) * np.array([
[k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7]],
[k[1], k[0], k[7], k[6], k[5], k[4], k[3], k[2]],
[k[2], k[7], k[0], k[5], k[6], k[3], k[4], k[1]],
[k[3], k[6], k[5], k[0], k[7], k[2], k[1], k[4]],
[k[4], k[5], k[6], k[7], k[0], k[1], k[2], k[3]],
[k[5], k[4], k[3], k[2], k[1], k[0], k[7], k[6]],
[k[6], k[3], k[4], k[1], k[2], k[7], k[0], k[5]],
[k[7], k[2], k[1], k[4], k[3], k[6], k[5], k[0]]])
return KE
示例13: test_add_uniform_time_weights
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def test_add_uniform_time_weights():
time = np.array([15, 46, 74])
data = np.zeros((3))
ds = xr.DataArray(data,
coords=[time],
dims=[TIME_STR],
name='a').to_dataset()
units_str = 'days since 2000-01-01 00:00:00'
cal_str = 'noleap'
ds[TIME_STR].attrs['units'] = units_str
ds[TIME_STR].attrs['calendar'] = cal_str
with pytest.raises(KeyError):
ds[TIME_WEIGHTS_STR]
ds = add_uniform_time_weights(ds)
time_weights_expected = xr.DataArray(
[1, 1, 1], coords=ds[TIME_STR].coords, name=TIME_WEIGHTS_STR)
time_weights_expected.attrs['units'] = 'days'
assert ds[TIME_WEIGHTS_STR].identical(time_weights_expected)
示例14: test_ensure_time_as_index_with_change
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def test_ensure_time_as_index_with_change():
# Time bounds array doesn't index time initially, which gets fixed.
arr = xr.DataArray([-93], dims=[TIME_STR], coords={TIME_STR: [3]})
arr[TIME_STR].attrs['units'] = 'days since 2000-01-01 00:00:00'
arr[TIME_STR].attrs['calendar'] = 'standard'
ds = arr.to_dataset(name='a')
ds.coords[TIME_WEIGHTS_STR] = xr.DataArray(
[1], dims=[TIME_STR], coords={TIME_STR: arr[TIME_STR]}
)
ds.coords[TIME_BOUNDS_STR] = xr.DataArray(
[[3.5, 4.5]], dims=[TIME_STR, BOUNDS_STR],
coords={TIME_STR: arr[TIME_STR]}
)
ds = ds.isel(**{TIME_STR: 0})
actual = ensure_time_as_index(ds)
expected = arr.to_dataset(name='a')
expected.coords[TIME_WEIGHTS_STR] = xr.DataArray(
[1], dims=[TIME_STR], coords={TIME_STR: arr[TIME_STR]}
)
expected.coords[TIME_BOUNDS_STR] = xr.DataArray(
[[3.5, 4.5]], dims=[TIME_STR, BOUNDS_STR],
coords={TIME_STR: arr[TIME_STR]}
)
xr.testing.assert_identical(actual, expected)
示例15: db
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array [as 别名]
def db(audio):
if len(audio.shape) > 1:
maxx = np.max(np.abs(audio), axis=1)
return 20 * np.log10(maxx) if np.any(maxx != 0) else np.array([0])
maxx = np.max(np.abs(audio))
return 20 * np.log10(maxx) if maxx != 0 else np.array([0])