2022年1月4日 星期二

為什麼要用 Numpy?

 只用Python不好嗎?

前言

正文

Data scientist 常用的工具組合
VEC_LENGTH = 100000
w = np.random.rand(VEC_LENGTH)
x = np.random.rand(VEC_LENGTH)
# for loop
c = 0
for i in range(VEC_LENGTH):
c += w[i] * x[i]
# numpy
import numpy as np
c = np.dot(w, x)
A = np.array([
[1, 2, 3],
[2, 3, 4],
])
B = np.array([
[2],
[0],
])
A * B
# array([[2 4 6], [0 0 0]])
A = np.array([1, 2, 3])
A ** 2
# array([1, 4, 9])
VEC_LENGTH = 100000
w = np.random.rand(VEC_LENGTH)
x = np.random.rand(VEC_LENGTH)

tic = time.time()
c = 0
for i in range(VEC_LENGTH):
c += w[i] * x[i]
toc = time.time()
print('For loop took: %s ms' % str(1000 * (toc - tic)))
# >> For loop took: 124.56703186 mstic = time.time()
c = np.dot(w, x)
toc = time.time()
print('Vectorized dot took: %s ms' % str(1000 * (toc - tic)))
# >> Vectorized dot took: 0.262975692749 ms
電競GPU都長得超帥的 😅

結論

沒有留言:

張貼留言

Python 標準函式庫 (Standard Library

Python 標準函式庫 (Standard Library) — Python 3.12.0a3 說明文件 ...