【问题标题】:Python: threading + curve_fit: null argument to internal routinePython:threading + curve_fit:内部例程的空参数
【发布时间】:2014-05-01 23:24:54
【问题描述】:

我在使用以下代码时遇到了一些问题,它应该使用线程进行高斯拟合:



    from PIL import Image
    import numpy as np
    from scipy.optimize import curve_fit
    import threading

    class myThread (threading.Thread):
        def __init__(self, index):
            threading.Thread.__init__(self)
            self.index = index
        def run(self):
            for i in np.arange(n_Bild.shape[1]):
                curve_fit(self.gauss, x_x, Intensitaet[self.index, ...], p0=(Intensitaet[self.index, i], i, 1, 0))
        def gauss(self, x, a, b, c, d):
            return a * np.exp(-(x-b) ** 2 / (2 * c ** 2)) + d

    Bild = Image.open("test.bmp")
    n_Bild = np.asarray(Bild)
    Intensitaet = np.zeros((n_Bild.shape[0], n_Bild.shape[1]), dtype=np.uint32)
    Intensitaet += n_Bild[..., ..., 0]
    Intensitaet += n_Bild[..., ..., 1]
    Intensitaet += n_Bild[..., ..., 2]
    x_x = np.arange(n_Bild.shape[1]) #Pixel auf "x"-Achse

    threads = []
    # Create new threads
    thread0 = myThread(0)
    thread1 = myThread(1)
    # Add threads to thread list
    threads.append(thread0)
    threads.append(thread1)
    # Start new Threads
    thread0.start()
    thread1.start()

    # Wait for all threads to complete
    for t in threads:
        t.join()
    print "finished"

如果我运行我的程序,我会收到一个错误:


SystemError: null argument to internal routine
Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Anaconda\lib\threading.py", line 808, in __bootstrap_inner
    self.run()
  File "G:/DropBox/Daten/Dropbox/Uni/Bachelorarbeit/Python/ThreadTest.py", line 12, in run
    curve_fit(self.gauss, x_x, Intensitaet[self.index, ...], p0=(Intensitaet[self.index, i], i, 1, 0))
  File "C:\Anaconda\lib\site-packages\scipy\optimize\minpack.py", line 533, in curve_fit
    res = leastsq(func, p0, args=args, full_output=1, **kw)
  File "C:\Anaconda\lib\site-packages\scipy\optimize\minpack.py", line 378, in leastsq
    gtol, maxfev, epsfcn, factor, diag)
error: Internal error constructing argument list.#

如果我只运行一个线程而不是两个线程,程序可以正常工作,但我不知道我做错了什么。 感谢您的帮助。

【问题讨论】:

    标签: python multithreading class curve-fitting python-multithreading


    【解决方案1】:

    我相信 leastsq() 不是线程安全的,您需要在对 curve_fit() 的调用周围使用 threading.Lock() (这可能会破坏您的目的)或使用多处理。

    【讨论】:

    • 并且无论如何都应该使用multiprocessing,因为感谢GIL,python 线程仅在 I/O 绑定的情况下才有用。它们实际上会使数字运算变慢。
    • 实际上,在这种情况下,如果leastsq 在 C 端做了不重要的事情,它会绕过 GIL(因为它可以在 C 端释放它)。我对 leastsq 在内部所做的工作不够熟悉,无法判断它在回调残差计算回调之前是否做了很多工作,但如果确实如此,那么它肯定是绕过 GIL 的候选人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2016-03-12
    • 2017-04-08
    • 2013-07-30
    相关资源
    最近更新 更多