下面的问题是针对使用 PyCharm 的人。\n有嵌套for循环,tqdm用于与每个for循环对应的进度条。代码如下所示。
from tqdm import tqdm\nimport time\n\nfor i in tqdm(range(5), desc="i", colour='green'):\n for j in tqdm(range(10), desc="j", colour='red'):\n time.sleep(0.5)\nRun Code Online (Sandbox Code Playgroud)\n但问题是,每次进度条中有更新时,内部循环的进度条都会以换行符显示,如下所示。
\ni: 0%| | 0/5 [00:00<?, ?it/s]\nj: 0%| | 0/10 [00:00<?, ?it/s]\nj: 10%|\xe2\x96\x88 | 1/10 [00:00<00:04, 1.94it/s]\nj: 20%|\xe2\x96\x88\xe2\x96\x88 | 2/10 [00:01<00:04, 1.94it/s]\nj: 30%|\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 | 3/10 [00:01<00:03, 1.96it/s]\nj: 40%|\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 | 4/10 [00:02<00:03, 1.96it/s]\nj: 50%|\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 | 5/10 [00:02<00:02, 1.97it/s]\nj: 60%|\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 | 6/10 [00:03<00:02, 1.97it/s]\nj: 70%|\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 | 7/10 [00:03<00:01, 1.97it/s]\nj: 80%|\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88\xe2\x96\x88 | 8/10 [00:04<00:01, …Run Code Online (Sandbox Code Playgroud) 我有 2 个二维数组。我试图沿轴 1 进行卷积。np.convolve没有提供axis参数。这里的答案是,使用 1 个 2D 数组与 1D 数组进行卷积np.apply_along_axis。但它不能直接应用于我的用例。这里的问题没有答案。
MWE如下。
import numpy as np
a = np.random.randint(0, 5, (2, 5))
"""
a=
array([[4, 2, 0, 4, 3],
[2, 2, 2, 3, 1]])
"""
b = np.random.randint(0, 5, (2, 2))
"""
b=
array([[4, 3],
[4, 0]])
"""
# What I want
c = np.convolve(a, b, axis=1) # axis is not supported as an argument
"""
c=
array([[16, 20, 6, …Run Code Online (Sandbox Code Playgroud) 我有一个具有以下结构的神经网络:
class myNetwork(nn.Module):
def __init__(self):
super(myNetwork, self).__init__()
self.bigru = nn.GRU(input_size=2, hidden_size=100, batch_first=True, bidirectional=True)
self.fc1 = nn.Linear(200, 32)
torch.nn.init.xavier_uniform_(self.fc1.weight)
self.fc2 = nn.Linear(32, 2)
torch.nn.init.xavier_uniform_(self.fc2.weight)
Run Code Online (Sandbox Code Playgroud)
我需要通过重置神经网络的参数来将模型恢复到未学习的状态。nn.Linear我可以使用以下方法对图层执行此操作:
def reset_weights(self):
torch.nn.init.xavier_uniform_(self.fc1.weight)
torch.nn.init.xavier_uniform_(self.fc2.weight)
Run Code Online (Sandbox Code Playgroud)
但是,要重置图层的权重nn.GRU,我找不到任何此类片段。
我的问题是如何重置图层nn.GRU?重置网络的任何其他方法也可以。任何帮助表示赞赏。
我有一个数据矩阵,a并且我有存储在 array 中的索引列表idx。我想从idx. 现在我使用for循环来实现这一点。但它非常慢,因为我必须在迭代中提取大约 1000 次数据。下面是一个最小的工作示例。
import numpy as np
a = np.random.random(1000)
idx = np.array([1, 5, 89, 54])
# I want "data" array to have np.array([a[1:11], a[5:15], a[89:99], a[54:64]])
# I use for loop below but it is slow
data = []
for id in idx:
data.append(a[id:id+10])
data = np.array(data)
Run Code Online (Sandbox Code Playgroud)
有没有办法加快这个过程?谢谢。
编辑:我的问题与这里提出的问题不同。在问题中,与我的问题中的固定块大小相比,块的大小是随机的。存在其他差异。我不必用完整个数组a,一个元素可以出现在多个块中。我的问题不一定“拆分”数组。
我正在尝试生成仅包含0's 和1's 的序列。我编写了以下代码,并且可以正常工作。
import numpy as np
batch = 1000
dim = 32
while 1:
is_same = False
seq = np.random.randint(0, 2, [batch, dim])
for i in range(batch):
for j in range(i + 1, batch):
if np.array_equal(seq[i], seq[j]):
is_same = True
if is_same:
continue
else:
break
Run Code Online (Sandbox Code Playgroud)
我的batch变量是数以千计。上面的这个循环大约需要 30 秒才能完成。这是另一个for循环的数据生成部分,该循环运行了大约 500 次迭代,因此非常慢。有没有更快的方法来生成这个序列列表而不重复?谢谢。
期望的结果是一个batch_size序列的集合,每个序列的长度dim只包含0s 和1s,这样集合中没有两个序列是相同的。
我正在尝试实现一个神经网络,其中我只需要内核与输入的乘法。Tensorflow 中的致密层还增加了偏差,我试图将其设置为零。从文档中,唯一可以使用的变量是bias_regularizer。所以我尝试执行以下操作:
def make_zero(_):
return np.zeros(21,)
out1 = tf.layers.dense(inputs=codeword, units=21, activation=None, bias_regularizer=make_zero)
Run Code Online (Sandbox Code Playgroud)
但我仍然看到偏差值不为零。还有其他方法可以实现这一目标吗?
我有一个a形状张量(1, N, 1)。我需要沿维度左移张量1并添加一个新值作为替换。我找到了一种方法来完成这项工作,下面是代码。
a = torch.from_numpy(np.array([1, 2, 3]))
a = a.unsqueeze(0).unsqeeze(2) # (1, 3, 1), my data resembles this shape, therefore the two unsqueeze
# want to left shift a along dim 1 and insert a new value at the end
# I achieve the required shifts using the following code
b = a.squeeze
c = b.roll(shifts=-1)
c[-1] = 4
c = c.unsqueeze(0).unsqueeze(2)
# c = [[[2], [3], [4]]]
Run Code Online (Sandbox Code Playgroud)
我的问题是,有没有更简单的方法来做到这一点?谢谢。
我正在运行一段简单的代码来返回和batch之间的整数数量(无需替换)。02**63
from random import sample
batch = 1000
n = 63
rand_nos = sample(range(2**n), batch)
Run Code Online (Sandbox Code Playgroud)
我收到错误
Python int too large to convert to C ssize_t
Run Code Online (Sandbox Code Playgroud)
random.sample我认为这与函数内部将范围长度转换为值有关int。但我找不到任何可以设置的参数,要求函数使用更大范围的数据类型。我该怎么办?谢谢。
我有一个处理复杂数据类型的函数,我正在使用它numba来加快处理速度。我声明了一个零数组numpy,使用复杂数据类型,稍后在函数中填充。但在运行时numba不能使零发生函数过载。为了重现错误,我提供了一个 MWE。
import numpy as np
from numba import njit
@njit
def my_func(idx):
a = np.zeros((10, 5), dtype=complex)
a[idx] = 10
return a
my_func(4)
Run Code Online (Sandbox Code Playgroud)
以下错误显示在a初始化数组的位置。
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<built-in function zeros>) found for signature:
zeros(Tuple(Literal[int](10), Literal[int](5)), dtype=Function(<class 'complex'>))
There are 2 candidate implementations:
Of which 2 did not match due to:
Overload of function 'zeros': File: numba\core\typing\npydecl.py: Line 511.
With argument(s): '(UniTuple(int64 …Run Code Online (Sandbox Code Playgroud) 我有两个 numpy 数组a和 ,b形状分别为[5, 5, 5]和[5, 5]。对于两者来说a,b形状中的第一个条目是批量大小。当我执行矩阵乘法选项时,我得到一个 shape 数组[5, 5, 5]。MWE如下。
import numpy as np
a = np.ones((5, 5, 5))
b = np.random.randint(0, 10, (5, 5))
c = a @ b
# c.shape is (5, 5, 5)
Run Code Online (Sandbox Code Playgroud)
假设我要对批量大小运行一个循环,即a[0] @ b[0].T,它将产生一个 shape 的数组[5, 1]。最后,如果我沿着轴 1 连接所有结果,我将得到一个 shape 的结果数组[5, 5]。下面的代码更好地描述了这些行。
a = np.ones((5, 5, 5))
b = np.random.randint(0, 10, (5, 5))
c …Run Code Online (Sandbox Code Playgroud) 我正在编写一个多线程程序来并行计算矩阵。换句话说,每个线程独立计算一个大矩阵,然后将其附加到从保存的文件加载的数组中。最后,附加的变量被保存回磁盘(使用np.save)。但是,当两个线程同时写入/访问文件时,就会出现问题。我的问题是,当一个线程写入文件时是否设置了一个锁,以便其他线程可以等待锁被释放来写入/访问文件?
MWE 如下所示
import os
import time
import numpy as np
from multiprocessing import Pool
def main():
p = Pool(processes=8)
files = os.listdir("matrices/dummy")
for f in files:
try:
os.remove(f)
except FileNotFoundError:
print("File not found while deleting")
a = np.random.randn(1, 10, 10)
np.save("matrices/dummy/saved_mat.npy", a)
p.starmap(save_mat, enumerate(np.random.rand(8)))
def save_mat(index, sleep_dur):
# time.sleep(sleep_dur)
np.random.seed(index)
try:
a = np.load("matrices/dummy/saved_mat.npy")
new_val = np.random.randn(1, 10, 10)
a = np.concatenate([a, new_val], axis=0)
except FileNotFoundError:
a = np.random.randn(1, 10, 10)
np.save("matrices/dummy/saved_mat.npy", a)
if __name__ == "__main__": …Run Code Online (Sandbox Code Playgroud) python ×9
python-3.x ×7
numpy ×6
arrays ×3
random ×2
convolution ×1
list ×1
numba ×1
performance ×1
pycharm ×1
pytorch ×1
sample ×1
tensorflow ×1
torch ×1
tqdm ×1