1. 程式人生 > >機器學習之numpy和matplotlib學習(十五)

機器學習之numpy和matplotlib學習(十五)

今天來學習矩陣的建立和一些基本運算

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : SundayCoder-俊勇
# @File    : numpy7.py
import numpy as np
# numpy基本學習第七課。
# 學習矩陣建立;
# 學習基本運算;

array=np.arange(12).reshape(3,4)
print array
# array為:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# 之前我們把這樣建立的陣列也叫作矩陣,實際上numpy中有建立矩陣的官方方法。
# 1、使用mat()函式建立一個矩陣,矩陣的行與行之間用分號隔開,行內的元素之間用空格隔開。 A=np.mat('0 1 2 3; 4 5 6 7; 8 9 10 11') print A # 輸出結果與之前的方法基本一樣: # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # 我們還可以使用NumPy陣列進行建立: B=np.mat(array) print B # 輸出結果與A一樣: # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # 2、矩陣的轉置矩陣。 print A.T # 輸出結果:
# [[ 0 4 8] # [ 1 5 9] # [ 2 6 10] # [ 3 7 11]] # 3、矩陣的逆矩陣。 print A.I # 輸出結果: # [[-0.3375 -0.1 0.1375 ] # [-0.13333333 -0.03333333 0.06666667] # [ 0.07083333 0.03333333 -0.00416667] # [ 0.275 0.1 -0.075 ]] # 4、divide函式在整數和浮點數除法中均只保留整數部分。 a = np.array([2, 6, 5]) b = np.array([1
, 2, 3]) print np.divide(a, b) print np.divide(b, a) # 運算結果如下: # [2 3 1] # [0 0 0] # 預設情況下,使用/運算子相當於呼叫divide函式 print a/b # 運算結果如下: # [2 3 1] # 5、true_divide函式與數學中的除法定義更為接近,即返回除法的浮點數結果而不作截斷: print np.true_divide(a, b) print np.true_divide(b, a) # 運算結果如下: # [ 2. 3. 1.66666667] # [ 0.5 0.33333333 0.6 ] # 6、floor_divide函式總是返回整數結果,相當於先呼叫divide函式再呼叫floor函式。 # floor函式將對浮點數進行向下取整並返回整數: print np.floor_divide(a,b) # 運算結果如下: # [2 3 1] # 預設情況下,使用運算子//對應於floor_divide函式。 print a//b # 運算結果如下: # [2 3 1]

更新完畢