機器學習之numpy和matplotlib學習(九)
阿新 • • 發佈:2018-11-01
這節課我們來學習numpy的一些基本的操作和屬性。
為什麼這樣安排學習課程呢?
我覺得這樣交叉學習,使用到什麼的時候就去檢視,對於numpy也好還是matplotlib的學習也好。
他們的內容有很多,要想全部掌握還是很難的,只有不斷的自己去實踐,遇到什麼不知道的問題就去學習。
而不是想去看numpy和matplotlib的相關詳細教學,把numpy學習透徹再進行機器學習。
以上只是個人看法。
個人覺得學習numpy要有點線性代數的基礎知識。
把numpy的學習理解為一切基於矩陣。【這樣就方便理解和學習numpy的使用了!】
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : SundayCoder-俊勇
# @File : numpy1.py
import numpy as np
# numpy基本學習第一課。
# numpy基本屬性。
# 建立一個兩行三列的int型別矩陣。
# dtype全稱為datatype。也就是資料型別。
array=np.array([[1,2,3],[4,5,6]],dtype=np.int)
print array
# 形狀,也就是幾行幾列【學過線性代數就簡單多了】
print array.shape
# 維度【也就是幾行】
print array.ndim
# 共有多少和元素。這裡2行3列,總共有6個元素。
print array.size
# 獲得array這個行列式的轉置矩陣。
print array.T
# 索引值的使用
# arange與python中的range一樣,預設從0開始。
# 索引和列表的巢狀也基本一樣。
# reshape是可以改變資料變成幾行幾列的矩陣。
b=np.arange(12).reshape(3,4)
print b
# b[1][3]也可以寫成b[1,3]
print b[1][3]
# 輸出b的行資料。
for row in b:
print(row)
#這也是輸出行資料,說明這個只能輸出行資料。
for col in b:
print (col)
# 怎麼輸出列資料。學過線性代數的知道轉置矩陣的作用。
# 輸出列資料的做法
for col in b.T:
print col
結果如下:
[[1 2 3]
[4 5 6]]
(2, 3)
2
6
[[1 4]
[2 5]
[3 6]]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
7
[0 1 2 3]
[4 5 6 7]
[ 8 9 10 11]
[0 1 2 3]
[4 5 6 7]
[ 8 9 10 11]
[0 4 8]
[1 5 9]
[ 2 6 10]
[ 3 7 11]
另外補充一點就是numpy中所有的dtype型別如下: