python各框架和模組對矩陣的運算比較
阿新 • • 發佈:2019-02-20
最近在學習numpy,pandas,tensorflow和pytorch,突然想試試各種不同的方法對矩陣的運算效率如何,以下是程式碼:
import tensorflow as tf
import pandas as pd
import torch
import time
import numpy as np
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'#mac Os 下有一個警告可以通過這個語句使之不顯
print('==============TensorFlow==============')
mat_1 = tf.constant(np.arange(12 ).reshape(3,4).astype(np.float32))
mat_2 = tf.constant(np.arange(12).reshape(4,3).astype(np.float32))
start = time.time()
product = tf.matmul(mat_1,mat_2)
sess = tf.Session()
res = sess.run(product)
print(res)
end = time.time()
print('run rime = ',end-start)
print()
print('==============PyTorch==============' )
x = torch.from_numpy(np.arange(12).reshape(3,4).astype(np.float32))
y = torch.from_numpy(np.arange(12).reshape(4,3).astype(np.float32))
start = time.time()
z = torch.mm(x,y)
print(z)
end = time.time()
print('run rime = ',end-start)
print()
print('==============Pandas==============')
x = pd.DataFrame(np.arange(12 ).reshape(3,4).astype(np.float32))
y = pd.DataFrame(np.arange(12).reshape(4,3).astype(np.float32))
start = time.time()
z = x.dot(y)
print(z)
end = time.time()
print('run rime = ',end-start)
print()
print('==============NumPy==============')
x = np.arange(12).reshape(3,4).astype(np.float32)
y = np.arange(12).reshape(4,3).astype(np.float32)
start = time.time()
z = x.dot(y)
print(z)
end = time.time()
print('run rime = ',end-start)
print()
以下是執行結果:
可以看到pytorch確實比tensorflow對矩陣的運算效率要高不少。