减少预测概率所需的时间

2024-04-19 20:06:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Keras和Tensorflow后端。一旦我有了我正在使用的模型模型预测概率预测概率。这个预测函数所花费的时间似乎与数组的大小无关,或者与其预测的数组的大小关系不大。你知道吗

我能做些什么来减少这段时间?你知道吗

首先,我运行循环100次,并对预测进行计时,如下所示

fname_model = folder+"/my_modelbuy_rocbased.h5"
best_model = load_model(fname_model)
best_model.compile(loss='categorical_crossentropy', optimizer='Adam', 
metrics=['acc'])
X_test_orig = pd.read_csv(folder+"/ret_out_20170402.csv",sep=",")
x_test = X_test_orig.as_matrix()
y1=np.array([x_test[1]])
print y1.shape 
t1=datetime.now().strftime("%H:%M:%S.%f")
for i in range(0,100,1):
prob1= best_model.predict_proba(y1)
t2=datetime.now().strftime("%H:%M:%S.%f")   
print "time taken ", t1,t2

运行后*********************************************************************************

时间:11:50:53.909226 11:50:54.372596


所以对于100个预测,所用的时间是11:50:54.372596减去11:50:53.909226,这大约是463毫秒,这意味着每个预测需要4.63毫秒

但是,如果我只为一个预测运行循环,如下所示

fname_model = folder+"/my_modelbuy_rocbased.h5"
best_model = load_model(fname_model)
best_model.compile(loss='categorical_crossentropy', optimizer='Adam', 
metrics=['acc'])
X_test_orig = pd.read_csv(folder+"/ret_out_20170402.csv",sep=",")
x_test = X_test_orig.as_matrix()
y1=np.array([x_test[1]])
print y1.shape 
t1=datetime.now().strftime("%H:%M:%S.%f")
for i in range(0,1,1):
prob1= best_model.predict_proba(y1)
t2=datetime.now().strftime("%H:%M:%S.%f")   
print "time taken ", t1,t2

运行后*********************************************************************************

时间:11:54:40.683225 11:54:41.144969


所以对于1个预测,所用的时间是11:54:40.683225减去11:54:41.144969,也就是440毫秒。你知道吗

无论调用的次数如何,该模型似乎都需要固定的时间。我怎样才能减少这个?你知道吗


Tags: csvtestdatetimemodel时间folderfnamenow
1条回答
网友
1楼 · 发布于 2024-04-19 20:06:43

这是预期的,因为您预测的是单个输入,并且计算图(模型)是相同的,因此预测所需的时间是相同的。这就好像你期望同一个计算有一个不同的运行时,而这是不可能发生的。你知道吗

现在有一种加速方法:不用预测单个元素,而是将它们转换成一个数组(samples,features),只需调用model.predict,它将以批处理的方式进行处理,并根据后端设置并行运行计算。你知道吗

另一点是你不需要编译来预测。编译会将loss和optimiser操作添加到图形中,如果只是预测,则不需要这些操作。这将减少模型加载到内存中的时间等

相关问题 更多 >