如何使这两个代码段并行运行

时间:2019-06-08 20:10:48

标签: multithreading parallel-processing

我想并行运行这两部分代码。这可能在python中吗?我将如何修改代码以适应此要求?

def smo(self, X, y):
    iterations = 0
    n_samples = X.shape[0]
    # Initial coefficients
    alpha = numpy.zeros(n_samples)
    # Initial gradient
    g = numpy.ones(n_samples)
    while True:
        yg = g * y
        # KKT Conditions
        y_pos_ind = (y == 1)
        y_neg_ind = (numpy.ones(n_samples) - y_pos_ind).astype(bool)
        alpha_pos_ind = (alpha >= self.C)
        alpha_neg_ind = (alpha <= 0)

        indices_violating_Bi_1 = y_pos_ind * alpha_pos_ind
        indices_violating_Bi_2 = y_neg_ind * alpha_neg_ind
        indices_violating_Bi = indices_violating_Bi_1 + indices_violating_Bi_2
        yg_i = yg.copy()
        yg_i[indices_violating_Bi] = float('-inf')
        # First of the maximum violating pair
        i = numpy.argmax(yg_i)

        Kik = self.kernel_matrix(X, i)

        indices_violating_Ai_1 = y_pos_ind * alpha_neg_ind
        indices_violating_Ai_2 = y_neg_ind * alpha_pos_ind
        indices_violating_Ai = indices_violating_Ai_1 + indices_violating_Ai_2
        yg_j = yg.copy()
        yg_j[indices_violating_Ai] = float('+inf')
        # Second of the maximum violating pair
        j = numpy.argmin(yg_j)

        Kjk = self.kernel_matrix(X, j)

        # Optimality criterion
        if(yg_i[i] - yg_j[j]) < self.tol or (iterations >= self.max_iter):
            break

        min_term_1 = (y[i] == 1) * self.C - y[i] * alpha[i]
        min_term_2 = y[j] * alpha[j] + (y[j] == -1) * self.C
        min_term_3 = (yg_i[i] - yg_j[j]) / (Kik[i] + Kjk[j] - 2 * Kik[j])

        # Direction search
        lamda = numpy.min([min_term_1, min_term_2, min_term_3])
        # Gradient update
        g += lamda * y * (Kjk - Kik)
        # Update coefficients
        alpha[i] = alpha[i] + y[i] * lamda
        alpha[j] = alpha[j] - y[j] * lamda

        iterations += 1

    print('{} iterations to arrive at the minimum'.format(iterations))
    return alpha

我想运行此行

Kik = self.kernel_matrix(X,i)

和这一行

Kjk = self.kernel_matrix(X,j)

并行。如何更改代码以适应这种情况?

1 个答案:

答案 0 :(得分:0)

仅使用完成的多线程代码为您提供响应可能不会对您有帮助,并且由于我不知道函数本身的功能,但是要查看以下链接,就很难了:https://realpython.com/intro-to-python-threading/

总体思路是,您必须为要并行运行的每个任务启动一个线程,如下所示:

thread1 = threading.Thread(target=kernel_matrix,args=(X,j))
thread1.start()

如果要等待线程完成,请调用thread.join()

您需要注意种族状况,这里的线程太好了:What is a race condition?