import numpy as np
這裡的np是我們在使用庫時起的別名。
1. np.dot()
矩陣或向量乘法https://blog.csdn.net/meini32/article/details/126125740
2.np.zreos(shape, dtype)
import numpy as np
# 返回一個 2*3 矩陣 其數據類型是int型
print(np.zeros([2,3],int))
# [[0 0 0]
# [0 0 0]]
3.np.sum()
import numpy as np
A = [1,2,3]
print(np.sum(A)) #6
4.np.max()、min()
import numpy as np
A = [-1,2,-3]
print(np.max(A)) #2
print(np.min(A)) #-3
5.np.abs()
import numpy as np
A = [-1,2,-3]
print(np.abs(A)) #[1,2,3]
6.np.add
import numpy as np
A = [-1,2,-3]
print(np.add(A,3)) #[2 5 0]
7.np.log()
import numpy as np
A = [10,2,3]
print(np.log2(4)) #2.0
print(np.log(np.exp(1))) #1.0
print(np.log10(A)) #[1. 0.30103 0.47712125]
8.np.exp()
import numpy as np
A = [1,2,3]
#返回單個e的x方
print(np.exp(1)) #2.718281828459045
# 返回整個數組的e的A[x]方
print(np.exp(A)) #[ 2.71828183 7.3890561 20.08553692]
9.random.randn(x)
import numpy as np
print(np.random.randn(5))
#[-0.82887289 -1.08409144 -0.08997643 -0.46342376 1.00813753]
1.給出kal值,計算水果中的物質的卡路裡占比
import numpy as np
fruit = np.array([[56.0,0.0,4.4,68.0],
[1.2,104.0,52.0,8.0],
[1.8,35.0,99.0,8.9]])
total_Kal = fruit.sum(0) #axis = 0 豎向相加 =1橫向相加
#計算總卡路裡
print(total_Kal) #[ 59. 139. 155.4 84.9]
#print(fruit.sum(1)) #[128.4 165.2 144.7]
KalPercent = (fruit/total_Kal)*100
print(KalPercent)
#[[94.91525424 0. 2.83140283 80.0942285 ]
# [ 2.03389831 74.82014388 33.46203346 9.42285041]
#[ 3.05084746 25.17985612 63.70656371 10.48292108]]
2.n維向量和n維向量的相乘 (數字/n*n矩陣)
import numpy as np
#隨機生成兩個3維向量
a=np.random.randn(3)*100
b=np.random.randn(3)*100
print(a) #[213.05321938 143.03672134 112.62974255]
print(b) #[-58.82663801 -25.64361092 -63.52288988]
print(a*b) #直接相乘 輸出為一維向量:向量中相同位置相乘結果 #[-12533.20461396 -3667.97802873 -7154.56673368]
print(np.dot(a,b)) #點積運算 數字 #-23355.749376371125
#想要得到矩陣,就得把a、b一個變成行向量,一個變成列向量
a.shape = (3,1) #行
b.shape = (1,3)
print(np.dot(a,b))
#[[-12533.20461396 -5463.45386213 -13533.75619366]
# [ -8414.36942888 -3667.97802873 -9086.10589881]
# [ -6625.62909471 -2888.2332956 -7154.56673368]]
//如果想要直接得到矩陣 可以直接在定義a、b時設置行或列
a=np.random.randn(3,1)*100
b=np.random.randn(1,3)*100