我想使用multiprocessing.Pool并行应用函数.问题是如果一个函数调用触发了分段错误,则Pool会永久挂起.有没有人知道我如何制作一个可以检测到这种情况发生的池并引发错误?
以下示例显示了如何重现它(需要scikit-learn> 0.14)
import numpy as np
from sklearn.ensemble import gradient_boosting
import time
from multiprocessing import Pool
class Bad(object):
tree_ = None
def fit_one(i):
if i == 3:
# this will segfault
bad = np.array([[Bad()] * 2], dtype=np.object)
gradient_boosting.predict_stages(bad,
np.random.rand(20, 2).astype(np.float32),
1.0, np.random.rand(20, 2))
else:
time.sleep(1)
return i
pool = Pool(2)
out = pool.imap_unordered(fit_one, range(10))
# we will never see 3
for o in out:
print o
Run Code Online (Sandbox Code Playgroud) 我正在尝试解析*大型文件(> 5GB)的结构化标记数据.数据格式本质上是XML,但没有明确的根元素.最有效的方法是什么?
SAX解析器的问题是它们需要一个根元素,所以要么我要在数据流中添加一个伪元素(在Python中是否相当于Java的SequenceInputStream?)或者我要切换到非SAX符合基于事件的解析器(是否有sgmllib的后继?)
数据结构非常简单.基本上是元素列表:
<Document>
<docid>1</docid>
<text>foo</text>
</Document>
<Document>
<docid>2</docid>
<text>bar</text>
</Document>
Run Code Online (Sandbox Code Playgroud)
*实际上是迭代
给定np.array的形状(n_days, n_lat, n_lon),我想计算每个lat-lon单元的固定箱的直方图(即每日值的分布).
解决这个问题的一个简单方法是遍历单元格并np.histogram为每个单元格调用::
bins = np.linspace(0, 1.0, 10)
B = np.rand(n_days, n_lat, n_lon)
H = np.zeros((n_bins, n_lat, n_lon), dtype=np.int32)
for lat in range(n_lat):
for lon in range(n_lon):
H[:, lat, lon] = np.histogram(A[:, lat, lon], bins=bins)[0]
# note: code not tested
Run Code Online (Sandbox Code Playgroud)
但这很慢.有没有更有效的解决方案,不涉及循环?
我调查np.searchsorted了每个值的bin索引B,然后使用花式索引来更新H::
bin_indices = bins.searchsorted(B)
H[bin_indices.ravel(), idx[0], idx[1]] += 1 # where idx is a index grid given by np.indices
# note: code not tested
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为就地添加运算符(+ =)似乎不支持同一单元格的多个更新.
彼得,彼得