numpy知識點筆記

weixin_34402408發表於2016-10-31
  • 沿指定軸求和
>>> np.sum([[3.,4], [5.,6], [6.,7]], axis=0)
array([ 14.,  17.])
>>> np.sum([[3.,4], [5.,6], [6.,7]], axis=1)
array([  7.,  11.,  13.])
>>> x = np.array([[3.,4], [5.,6], [6.,7]])
>>> np.sum(x, axis=0)
array([ 14.,  17.])
>>> np.sum(x, axis=1)
array([  7.,  11.,  13.])
2422746-f1f928ee2cdaaeeb.png
numpy索引,`:`的位置處如同普通列表一樣索引
  • 索引維數超過 3 的多維陣列
arr = np.arange(24).reshape((2, 3, 4))
print arr[1, ...]               # 等價於 arr[1, :, :]
print arr[..., 1]               # 等價於 arr[:, :, 1]
  • 隨機生成正態分佈資料x,y是x的一次線性函式+噪音,然後畫出
import numpy as np

num_points = 1000
vectors_set = []
for i in range(num_points):
         x1= np.random.normal(0.0, 0.55)
         y1= x1 * 0.1 + 0.3 + np.random.normal(0.0, 0.03)
         vectors_set.append([x1, y1])
 
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]

import matplotlib.pyplot as plt

plt.plot(x_data, y_data, 'ro', label='Original data')
plt.legend('hello')
plt.show()
2422746-94e23cba346377a5.png
plt.show
  • 計算陣列某一維度上的平均值 numpy.mean
    numpy.meantensorflow.reduce_mean效果是一樣的。
c = np.array([[3.,4], [5.,6], [6.,7]])
print(np.mean(c,1))
# [ 3.5 5.5 6.5]
Mean = tf.reduce_mean(c,1)
with tf.Session() as sess:
    result = sess.run(Mean)
    print(result)
# [ 3.5 5.5 6.5]

參考:stackoverflow

  • np.reshape()重新排列陣列形狀。
    np.concatenate((a, b), axis=1)按指定軸方向組合陣列a和b。

  • 在第三維上組合矩陣

>>> a = np.arange(9).reshape(3,3)
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> b = 2 * a
array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
>>> np.dstack((a, b))
array([[[ 0,  0],
        [ 1,  2],
        [ 2,  4]],

       [[ 3,  6],
        [ 4,  8],
        [ 5, 10]],

       [[ 6, 12],
        [ 7, 14],
        [ 8, 16]]])

相關文章