繁体   English   中英

在Python中加速矩阵向量乘法和求幂,可能通过调用C / C ++

[英]Speeding up matrix-vector multiplication and exponentiation in Python, possibly by calling C/C++

我目前的工作在哪里机器学习项目-给定数据矩阵Z和矢量rho -我要计算的价值和坡度逻辑损失函数rho 计算涉及基本矩阵向量乘法和log / exp运算,以避免数值溢出(在一篇文章中描述)。

我目前正在使用NumPy在Python中执行此操作,如下所示(作为参考,此代码运行时间为0.2秒)。 虽然这很好用,但我想加快速度,因为我在代码中多次调用该函数(它代表了我项目中90%以上的计算)。

我正在寻找任何方法来改善没有并行化的代码的运行时间(即只有1个CPU)。 我很高兴使用Python中任何公开的软件包,或者调用C或C ++(因为我听说这可以将运行时间提高一个数量级)。 预处理数据矩阵Z也可以。 可能更好的计算被利用一些事情是该载体rho通常是稀疏的(具有50%左右的条目= 0)和有比列通常远远更多的行(在大多数情况下n_cols <= 100


import time
import numpy as np

np.__config__.show() #make sure BLAS/LAPACK is being used
np.random.seed(seed = 0)

#initialize data matrix X and label vector Y
n_rows, n_cols = 1e6, 100
X = np.random.random(size=(n_rows, n_cols))
Y = np.random.randint(low=0, high=2, size=(n_rows, 1))
Y[Y==0] = -1
Z = X*Y # all operations are carried out on Z

def compute_logistic_loss_value_and_slope(rho, Z):
    #compute the value and slope of the logistic loss function in a way that is numerically stable
    #loss_value: (1 x 1) scalar = 1/n_rows * sum(log( 1 .+ exp(-Z*rho))
    #loss_slope: (n_cols x 1) vector = 1/n_rows * sum(-Z*rho ./ (1+exp(-Z*rho))
    #see also: https://stackoverflow.com/questions/20085768/

    scores = Z.dot(rho)
    pos_idx = scores > 0
    exp_scores_pos = np.exp(-scores[pos_idx])
    exp_scores_neg = np.exp(scores[~pos_idx])

    #compute loss value
    loss_value = np.empty_like(scores)
    loss_value[pos_idx] = np.log(1.0 + exp_scores_pos)
    loss_value[~pos_idx] = -scores[~pos_idx] + np.log(1.0 + exp_scores_neg)
    loss_value = loss_value.mean()

    #compute loss slope
    phi_slope = np.empty_like(scores)
    phi_slope[pos_idx]  = 1.0 / (1.0 + exp_scores_pos)
    phi_slope[~pos_idx] = exp_scores_neg / (1.0 + exp_scores_neg)
    loss_slope = Z.T.dot(phi_slope - 1.0) / Z.shape[0]

    return loss_value, loss_slope


#initialize a vector of integers where more than half of the entries = 0
rho_test = np.random.randint(low=-10, high=10, size=(n_cols, 1))
set_to_zero = np.random.choice(range(0,n_cols), size =(np.floor(n_cols/2), 1), replace=False)
rho_test[set_to_zero] = 0.0

start_time = time.time()
loss_value, loss_slope = compute_logistic_loss_value_and_slope(rho_test, Z)
print "total runtime = %1.5f seconds" % (time.time() - start_time)

BLAS系列的图书馆已经过高度调整以获得最佳性能。 因此,无需链接到某些C / C ++代码就可以为您带来任何好处。 但是你可以尝试各种BLAS实现,因为它们中有很多,包括一些专门调整到一些CPU。

我想到的另一件事是使用像theano (或Google的tensorflow )这样的 ,它能够代表整个计算图(上面函数中的所有操作)并对其应用全局优化。 然后它可以通过C ++从该图形生成CPU代码(并通过翻转简单的开关也可以生成GPU代码)。 它还可以自动为您计算符号导数。 我已经将theano用于机器学习问题,它是一个非常好的库,虽然不是最容易学习的。

(我发布这个作为答案,因为评论太长了)

编辑:

我实际上在theano中有这个,但结果实际上在CPU上慢了2倍,见下面的原因。 无论如何我都会在这里发布,也许这是其他人做一些更好的事情的起点:(这只是部分代码,完成了原帖的代码)

import theano

def make_graph(rho, Z):
    scores = theano.tensor.dot(Z, rho)

    # this is very inefficient... it calculates everything twice and
    # then picks one of them depending on scores being positive or not.
    # not sure how to express this in theano in a more efficient way
    pos = theano.tensor.log(1 + theano.tensor.exp(-scores))
    neg = theano.tensor.log(scores + theano.tensor.exp(scores))
    loss_value = theano.tensor.switch(scores > 0, pos, neg)
    loss_value = loss_value.mean()

    # however computing the derivative is a real joy now:
    loss_slope = theano.tensor.grad(loss_value, rho)

    return loss_value, loss_slope

sym_rho = theano.tensor.col('rho')
sym_Z = theano.tensor.matrix('Z')
sym_loss_value, sym_loss_slope = make_graph(sym_rho, sym_Z)

compute_logistic_loss_value_and_slope = theano.function(
        inputs=[sym_rho, sym_Z],
        outputs=[sym_loss_value, sym_loss_slope]
        )

# use function compute_logistic_loss_value_and_slope() as in original code

Numpy非常优化。 您可以做的最好的事情是尝试其他库,其中相同大小的数据初始化为随机(未初始化为0)并执行您自己的基准测试。

如果你想尝试,你当然可以尝试BLAS。 您还应尝试使用eigen ,我个人在我的某个应用程序中发现它更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM