Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_grad_type_check_shape(self):
a = chainer.Variable(np.empty((3,), dtype=np.float32))
with self.assertRaises(ValueError):
a.grad = np.empty((2,), dtype=np.float32)
def interpol(a, inds, order=3, mode="nearest", mask_nan=False, cval=0.0, prefilter=True):
"""Given an array a[{x},{y}] and a list of float indices into a,
inds[len(y),{z}], returns interpolated values at these positions as [{x},{z}]."""
a = np.asanyarray(a)
inds = np.asanyarray(inds)
inds_orig_nd = inds.ndim
if inds.ndim == 1: inds = inds[:,None]
npre = a.ndim - inds.shape[0]
res = np.empty(a.shape[:npre]+inds.shape[1:],dtype=a.dtype)
fa, fr = partial_flatten(a, range(npre,a.ndim)), partial_flatten(res, range(npre, res.ndim))
if mask_nan:
mask = ~np.isfinite(fa)
fa[mask] = 0
for i in range(fa.shape[0]):
fr[i].real = scipy.ndimage.map_coordinates(fa[i].real, inds, order=order, mode=mode, cval=cval, prefilter=prefilter)
if np.iscomplexobj(fa[i]):
fr[i].imag = scipy.ndimage.map_coordinates(fa[i].imag, inds, order=order, mode=mode, cval=cval, prefilter=prefilter)
if mask_nan and np.sum(mask) > 0:
fmask = np.empty(fr.shape,dtype=bool)
for i in range(mask.shape[0]):
fmask[i] = scipy.ndimage.map_coordinates(mask[i], inds, order=0, mode=mode, cval=cval, prefilter=prefilter)
fr[fmask] = np.nan
if inds_orig_nd == 1: res = res[...,0]
return res
def initCoefficients(nLayers, nFrequencies, nCoefficients, frequencies, omega, lamda, lamda2, par):
nL1 = nLayers + 1
un = empty((nL1, nFrequencies, nCoefficients), dtype=complex128)
Y = empty((nL1, nFrequencies, nCoefficients), dtype=complex128)
Yn = empty((nL1, nFrequencies, nCoefficients), dtype=complex128)
# Compute the Admitivity, yn=j*omega*eps+sigma
for i in range(nFrequencies):
oTmp = 1.0 / omega[i]
for jc in range(nCoefficients):
Y[0, i, jc] = oTmp
p = par[0]
for i in range(nFrequencies):
tTmp = (omega[i] * eps0 + p) * omega[i]
for jc in range(nCoefficients):
unTmp = sqrt(tTmp + lamda2[i, jc])
un[0, i, jc] = unTmp
Yn[0, i, jc] = unTmp * Y[0, i, jc]
for k in range(1, nL1):
qf1_target.load_state_dict(qf1.state_dict())
qf2_target.load_state_dict(qf2.state_dict())
q_optimizer = optim.Adam(list(qf1.parameters()) + list(qf2.parameters()), lr=args.learning_rate)
actor_optimizer = optim.Adam(list(actor.parameters()), lr=args.learning_rate)
loss_fn = nn.MSELoss()
exploration_noise = NormalActionNoise(np.zeros(output_shape)) if args.action_noise == "normal" else OrnsteinUhlenbeckActionNoise(np.zeros(output_shape))
policy_noise = NormalActionNoise(np.zeros(output_shape)) if args.action_noise == "normal" else OrnsteinUhlenbeckActionNoise(np.zeros(output_shape))
# TRY NOT TO MODIFY: start the game
global_step = 0
exploration_noise.sigma = 0.1
policy_noise.sigma = 0.2
while global_step < args.total_timesteps:
next_obs = np.array(env.reset())
actions = np.empty((args.episode_length,), dtype=object)
rewards, dones = np.zeros((2, args.episode_length))
td_losses = np.zeros(args.episode_length)
obs = np.empty((args.episode_length,) + env.observation_space.shape)
# TRY NOT TO MODIFY: prepare the execution of the game.
for step in range(args.episode_length):
global_step += 1
obs[step] = next_obs.copy()
# ALGO LOGIC: put action logic here
if global_step < args.learning_starts:
actions[step] = env.action_space.sample()
else:
action = actor.forward(obs[step:step+1])
actions[step] = (action.tolist()[0] + exploration_noise()).clip(env.action_space.low, env.action_space.high)
log.debug2('memory = %s', mem_now)
max_memory = max(2000, mydf.max_memory-mem_now)
# nkptj for 3c-coulomb arrays plus 1 Lpq array
buflen = min(max(int(max_memory*.6*1e6/16/naux/(nkptj+1)), 1), nao_pair)
shranges = _guess_shell_ranges(cell, buflen, aosym)
buflen = max([x[2] for x in shranges])
# +1 for a pqkbuf
if aosym == 's2':
Gblksize = max(16, int(max_memory*.2*1e6/16/buflen/(nkptj+1)))
else:
Gblksize = max(16, int(max_memory*.4*1e6/16/buflen/(nkptj+1)))
Gblksize = min(Gblksize, ngs, 16384)
pqkRbuf = numpy.empty(buflen*Gblksize)
pqkIbuf = numpy.empty(buflen*Gblksize)
# buf for ft_aopair
buf = numpy.empty((nkptj,buflen*Gblksize), dtype=numpy.complex128)
col1 = 0
for istep, sh_range in enumerate(shranges):
log.debug1('int3c2e [%d/%d], AO [%d:%d], ncol = %d', \
istep+1, len(shranges), *sh_range)
bstart, bend, ncol = sh_range
col0, col1 = col1, col1+ncol
j3cR = []
j3cI = []
for k, idx in enumerate(adapted_ji_idx):
v = fuse(numpy.asarray(feri['j3c/%d'%idx][:,col0:col1]))
if is_zero(kpt):
for i, c in enumerate(vbar):
if c != 0:
v[i] -= c * ovlp[k][col0:col1]
j3cR.append(numpy.asarray(v.real, order='C'))
def _robust_regression(time, flux, flux_err, periods, loss, scale):
"""
Periodogram peaks for a given loss function and scale.
"""
beta0 = np.array([0, 1, 0])
mu = np.median(flux)
x = np.ones([len(time), len(beta0)])
chi_model = np.empty([len(periods)])
chi_noise = np.empty([len(periods)])
for i in range(len(periods)):
chi_model[i] = least_squares(
_model,
beta0,
loss=loss,
f_scale=scale,
args=(x, periods[i], time, flux, flux_err),
).cost
chi_noise[i] = least_squares(
_noise, mu, loss=loss, f_scale=scale, args=(time, flux, flux_err)
).cost
power = 1 - chi_model / chi_noise
return power
self.pnet, self.rnet, self.onet,
threshold_list, factor)
# 模型得出的边界框
box_2d_array_1 = box_2d_array.reshape(-1, 5)
# 模型预测出box的4个值、box的置信度,共5个值
box_2d_array_2 = box_2d_array_1[:, 0:4]
box_list = []
image_height, image_width, _ = image_3d_array.shape
image_size = image_width, image_height
for box in box_2d_array_2:
new_box = get_new_box(box, margin, image_size)
box_list.append(new_box)
box_2d_array_3 = np.array(box_list).astype('int')
# 模型得出的人脸5个关键点,即10个值
if len(point_2d_array) == 0:
point_2d_array_1 = np.empty((0, 10))
else:
point_2d_array_1 = np.transpose(point_2d_array, [1, 0])
return box_2d_array_3, point_2d_array_1
def f(N, D, M):
X = np.random.randint(0, 5, size=(N, D)).astype(np.int32)
y = np.empty(N, dtype=np.int32)
for i in prange(N):
y[i] = i % 4
p = np.random.randint(0, 5, size=(M, D)).astype(np.int32)
clf = hpat.ml.MultinomialNB(n_classes=4)
t1 = time.time()
clf.train(X, y)
res = clf.predict(p)
print("Exec time:", time.time() - t1)
return res.sum()
def _grab_real(self, index=None):
array = np.empty(self._record_shape, dtype=self._record_dtype)
data = array.__array_interface__['data'][0]
if index is not None:
if self.uca.readout(data, index):
return array
else:
raise base.CameraError('No frame available')
if self.uca.grab(data):
return array
else:
raise base.CameraError('No frame available')
bucket_sizes = [len(data[b]) for b in range(len(_buckets))]
data_variable = []
ss = [0] * len(_buckets)
ss1 = [0] * len(_buckets)
for bucket_id in range(len(_buckets)):
bucket_size = bucket_sizes[bucket_id]
if bucket_size == 0:
data_variable.append((1, 1))
continue
bucket_length = _buckets[bucket_id]
char_length = min(MAX_CHAR_LENGTH, max_char_length[bucket_id] + NUM_CHAR_PAD)
wid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)
cid_inputs = np.empty([bucket_size, bucket_length, char_length], dtype=np.int64)
pid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)
xpid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)
hid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)
tid_inputs = np.empty([bucket_size, bucket_length], dtype=np.int64)
masks_inputs = np.zeros([bucket_size, bucket_length], dtype=np.float32)
single_inputs = np.zeros([bucket_size, bucket_length], dtype=np.int64)
lengths_inputs = np.empty(bucket_size, dtype=np.int64)
order_inputs = np.empty(bucket_size, dtype=np.int64)
raw_word_inputs, raw_lines = [], []
for i, inst in enumerate(data[bucket_id]):
ss[bucket_id]+=1
ss1[bucket_id]=bucket_length