从如何从两个制表符分隔的文件中获取枢轴线?,有一种使用 unix 命令从两个文件中透视行的快速方法。
如果我们有两对文件:
f1a 和 f1bf2a 和 f2b目标是提供一个 3 列制表符分隔的文件,其中包括:
f1a / f2a文件中同时出现在f1a和中的行在哪里f1b:
我尝试了以下可行的方法,但如果文件非常大,则将需要大量内存来存储f1和f2字典。例如具有数十亿行的文件。
import sys
from tqdm import tqdm
f1a, f1b, f2a, f2b = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
# Read first pair of file into memory.
with open(f1a) as fin_f1a, open(f1a) as fin_f1b:
f1 = {s.strip().replace('\t', ' ') :t.strip().replace('\t', ' ') for s, t in tqdm(zip(fin_f1a, fin_f1b))}
with open(s2) as …Run Code Online (Sandbox Code Playgroud) 我有一个网站元描述列表(128k 描述;每个描述平均有 20-30 个单词),并且正在尝试构建一个相似度排名器(如:向我显示与此网站元描述最相似的 5 个网站)
它与 TF-IDF uni- 和 bigram 配合得非常好,我认为我还可以通过添加预先训练的词嵌入(准确地说是 spacy“en_core_web_lg”)来改进它。情节扭曲:根本行不通。从字面上没有得到一个好的猜测,它突然吐出完全随机的建议。
下面是我的代码。有什么想法我可能哪里出了问题吗?我是否在监督一些高度直观的事情?
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import sys
import pickle
import spacy
import scipy.sparse
from scipy.sparse import csr_matrix
import math
from sklearn.metrics.pairwise import linear_kernel
nlp=spacy.load('en_core_web_lg')
""" Tokenizing"""
def _keep_token(t):
return (t.is_alpha and
not (t.is_space or t.is_punct or
t.is_stop or t.like_num))
def _lemmatize_doc(doc):
return [ t.lemma_ for t in doc if _keep_token(t)]
def _preprocess(doc_list):
return [_lemmatize_doc(nlp(doc)) for doc in doc_list]
def dummy_fun(doc): …Run Code Online (Sandbox Code Playgroud) 我正在尝试提高 Python 中空气动力学函数的速度。
import numpy as np
from numba import njit
def calculate_velocity_induced_by_line_vortices(
points, origins, terminations, strengths, collapse=True
):
# Expand the dimensionality of the points input. It is now of shape (N x 1 x 3).
# This will allow NumPy to broadcast the upcoming subtractions.
points = np.expand_dims(points, axis=1)
# Define the vectors from the vortex to the points. r_1 and r_2 now both are of
# shape (N x M x 3). Each row/column pair …Run Code Online (Sandbox Code Playgroud) 我有一个用于跟踪各种值的数组。数组的2500x1700大小,所以不是很大。在会话结束时,我需要将该数组中的所有值重置为零。我尝试创建一个新的零数组并将数组中的所有值替换为零,并且创建一个全新的数组要快得多。
代码示例:
\nfor _ in sessions:\n # Reset our array\n tracking_array[:,:] = 0\n\n1.44 s \xc2\xb1 19.1 ms per loop (mean \xc2\xb1 std. dev. of 7 runs, 1 loop each)\nRun Code Online (Sandbox Code Playgroud)\n相对
\nfor _ in sessions:\n # Reset our array\n tracking_array = np.zeros(shape=(2500, 1700))\n\n7.26 ms \xc2\xb1 133 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 100 loops each)\nRun Code Online (Sandbox Code Playgroud)\n与仅替换数组中的值相比,为什么创建全新的数组要快得多?
\n给定一个大的多列 Pandas 数据框,我想尽快计算N元素窗口上的滚动“k-mean” 。
这里“k-mean”定义为排除最大和最小元素的N-2k元素的均值。Nkk
给定数据框:
df = pandas.DataFrame(
{'A': [34, 78, -2, -96, 58, -34, 44, -50, 42],
'B': [-82, 28, 96, 46, 36, -34, -20, 10, -40]})
A B
0 34 -82
1 78 28
2 -2 96
3 -96 46
4 58 36
5 -34 -34
6 44 -20
7 -50 10
8 42 -40
Run Code Online (Sandbox Code Playgroud)
随着N=6与k=1预期输出是:
A B
0 NaN NaN
1 NaN NaN
2 …Run Code Online (Sandbox Code Playgroud) I\xe2\x80\x99m 在高效并行化方面遇到一些麻烦np.concatenate。这是一个最小的工作示例。(我知道在这里我可以分别对a和b求和,但我专注于并行连接操作,因为这是我在项目中需要做的事情。然后我将对连接数组进行进一步的操作,例如排序。)
无论我在多少个核心上运行此程序,它似乎总是花费相同的时间(约 10 秒)。如果说有什么不同的话,那就是核心数越多,速度就越慢。我尝试在装饰器中使用 cc 来释放 GIL nogil=True,但没有成功。请注意,即使没有加速,所有核心在计算过程中显然都在使用。
有谁能够帮助我?
\n非常感谢
\nfrom numba import prange, njit\nimport numpy as np\n\n\n@njit()\ndef cc():\n\n r = np.random.rand(20)\n a = r[r < 0.5]\n b = r[r > 0.7]\n\n c = np.concatenate((a, b))\n\n return np.sum(c)\n\n\n@njit(parallel=True)\ndef cc_wrap():\n n = 10 ** 7\n result = np.empty(n)\n for i in prange(n):\n result[i] = cc()\n\n return result\n\ncc_wrap()\nRun Code Online (Sandbox Code Playgroud)\n 目前,在具有约 15 万个节点和 200 万条边的无向图上进行计算nx.triangles(G)非常慢(大约需要 80 小时)。如果节点度分布高度倾斜,使用以下过程计算三角形是否有问题?
import networkx as nx
def largest_degree_node(G):
# this was improved using suggestion by Stef in the comments
return max(G.degree(), key=lambda x: x[1])[0]
def count_triangles(G):
G=G.copy()
triangle_counts = 0
while len(G.nodes()):
focal_node = largest_degree_node(G)
triangle_counts += nx.triangles(G, nodes=[focal_node])[focal_node]
G.remove_node(focal_node)
return triangle_counts
G = nx.erdos_renyi_graph(1000, 0.1)
# compute triangles with nx
triangles_nx = int(sum(v for k, v in nx.triangles(G).items()) / 3)
# compute triangles iteratively
triangles_iterative = count_triangles(G)
# assertion passes
assert int(triangles_nx) …Run Code Online (Sandbox Code Playgroud) np.isin我正在尝试实现更快的in版本numba,这是我到目前为止所拥有的:
import numpy as np
import numba as nb
@nb.njit(parallel=True)
def isin(a, b):
out=np.empty(a.shape[0], dtype=nb.boolean)
b = set(b)
for i in nb.prange(a.shape[0]):
if a[i] in b:
out[i]=True
else:
out[i]=False
return out
Run Code Online (Sandbox Code Playgroud)
对于数字来说它是有效的,如下例所示:
a = np.array([1,2,3,4])
b = np.array([2,4])
isin(a,b)
>>> array([False, True, False, True])
Run Code Online (Sandbox Code Playgroud)
而且它比以下更快np.isin:
a = np.random.rand(20000)
b = np.random.rand(5000)
%time isin(a,b)
CPU times: user 3.96 ms, sys: 0 ns, total: 3.96 ms
Wall time: 1.05 ms
%time np.isin(a,b)
CPU times: user 11 ms, …Run Code Online (Sandbox Code Playgroud) 请注意:这只是出于好奇而提出的问题,与编写更好的多线程代码无关。当然,我不会也不会在实际项目中编写这样的代码。
添加关键字时可能会发生内联替换inline。所以我很好奇。
假设我们有这样的代码:
static bool done = false;
inline void setDone(bool newState) {
done = newState;
}
inline bool getDone() {
return done;
}
void someWorkerThreadJob() {
// Accessing without any lock/atomic/volatile
while (getDone() == false) {
}
}
Run Code Online (Sandbox Code Playgroud)
可以someWorkerThreadJob()像下面这样编译并进入无限循环吗?
void someThreadJob() {
while (done == false) {
}
}
Run Code Online (Sandbox Code Playgroud)
这也将我引向了下一个问题。类中的getter和setter怎么样?在类中定义的成员函数是隐式的inline,所以我认为可能会发生内联替换,因此同样的问题。这样对吗?
在调查 Python 代码库中的关键路径时,我们发现 ctypes 在延迟方面的行为是相当不可预测的。
我们的应用程序的更多背景。我们有很多进程,每个进程都通过共享内存进行通信。我们利用 python 库multiprocessing.RawValue,multiprocessing.RawArray它在内部用于ctypes数据管理。在生产环境中运行时,我们发现即使get()对这些共享数据类型进行简单的访问也需要大约 30-50 us,有时需要 100 us,而且速度相当慢。即使对于蟒蛇来说也是如此。
我创建了这个简单的示例,它创建了一个ctype结构并公开了get()方法
import ctypes
import sys
import time
import numpy as np
import random
from decimal import Decimal
def get_time_ns():
return Decimal(str(time.time_ns()))
class Point(ctypes.Structure):
_fields_ = [("x", ctypes.c_int),
("y", ctypes.c_int)]
def __init__(self, x, y):
return super().__init__(x, y)
def get(self):
return self.x
#return str(self.x) + "," + str(self.y)
def benchmark(delay_mode):
p = Point(10, 20)
iters = 10
while …Run Code Online (Sandbox Code Playgroud)