pythonasmatrix
1. python中array和matrix的區別
二者的區別主要在於在做乘法運算的時候,一個是矩陣乘,一個是數組乘,這里和MATLAb很相似。
調用的時候需要用numpy.array
Numpy matrices必須是2維的,但是numpy arrays (ndarrays) 可以是多維的(1D,2D,3D····ND). Matrix是Array的一個小的分支,包含於Array。所以matrix 擁有array的所有特性。
在numpy中matrix的主要優勢是:相對簡單的乘法運算符號。例如,a和b是兩個matrices,那麼a*b,就是積。
import numpy as np a=np.mat('4 3; 2 1') b=np.mat('1 2; 3 4')print(a)# [[4 3]# [2 1]]print(b)# [[1 2]# [3 4]]print(a*b)# [[13 20]# [ 5 8]]
matrix 和 array 都可以通過在have.Tto return the transpose, but matrix objects also have.Hfor the conjugate transpose, and.Ifor the inverse.
In contrast, numpy arrays consistently abide by the rule that operations are applied element-wise. Thus, if a and b are numpy arrays, then a*b is the array formed by multiplying the components element-wise:
c=np.array([[4, 3], [2, 1]]) d=np.array([[1, 2], [3, 4]])print(c*d)# [[4 6]# [6 4]]
To obtain the result of matrix multiplication, you use np.dot :
print(np.dot(c,d))# [[13 20]# [ 5 8]]
2. Python解決矩陣問題
下面是基於python3.4的數組矩陣輸入方法:
1.import numpy as np
2.arr = [1,2,3,4,5,6,7,8,9]
3.matrix_a = np.array(arr)2.
4.手動定義一個空數組:arr =[],鏈表數組:a = [1,2,[1,2,3]]。
Python, 是一種面向對象的解釋型計算機程序設計語言,由荷蘭人Guido van Rossum於1989年發明,第一個公開發行版發行於1991年。
Python是純粹的自由軟體,源代碼和解釋器CPython遵循GPL(GNUGeneral Public License)協議[2]。Python語法簡潔清晰,特色之一是強制用空白符(white space)作為語句縮進。
Python具有豐富和強大的庫。它常被昵稱為膠水語言,能夠把用其他語言製作的各種模塊(尤其是C/C++)很輕松地聯結在一起。常見的一種應用情形是,使用Python快速生成程序的原型(有時甚至是程序的最終界面),然後對其中[3]有特別要求的部分,用更合適的語言改寫,比如3D游戲中的圖形渲染模塊,性能要求特別高,就可以用C/C++重寫,而後封裝為Python可以調用的擴展類庫。需要注意的是在您使用擴展類庫時可能需要考慮平台問題,某些可能不提供跨平台的實現。
7月20日,IEEE發布2017年編程語言排行榜:Python高居首位。
3. python pandas 導入txt數據如何加入標頭
li = list(row.tolist() for index,row in df.iterrows())
雖然比df.as_matrix()的啰嗦一點,但這個返回是嵌套列表,as_matrix是向量組成的列表
4. 在Python中使用矩陣,需要調用什麼庫函數:
numpy庫的mat函數
importnumpyasnp
matrix=np.mat([[1,2,3],[4,5,6]])
printmatrix
printtype(matrix)
結果為:
[[1 2 3]
[4 5 6]]
<class 'numpy.matrixlib.defmatrix.matrix'>
5. 在python中,怎麼給矩陣刪除一個元素
L1=np.c_[[1],L] 是連接兩個矩陣得到矩陣L1
而L2=np.delete(L1,0,1)是沿矩陣L1縱軸去掉矩陣中的第1列的元素得到矩陣L2,其中0表示第1列,1表示縱軸axis=1
我給你一個Python語言的例子,你看看吧
#!/usr/bin/python
importnumpyasnp
L=np.matrix([1,2,3,4]);
L1=np.c_[[1],L]
print(L1)
L2=np.delete(L1,0,1)
print(L2)
6. python如何輸入矩陣
使用numpy創建矩陣有2種方法,一種是使用numpy庫的matrix直接創建,另一種則是使用array來創建。
首先導入numpy:
(1)import numpy
(2)from numpy import *
(3)import numpy as np
相關推薦:《Python基礎教程》
然後分別用上面說的2種方法來分別構建一個4×3的矩陣,如圖:
7. 如何用python畫好confusion matrix
在做分類的時候,經常需要畫混淆矩陣,下面我們使用python的matplotlib包,scikit-learning機器學習庫也同樣提供了例子:, 但是這樣的圖並不能滿足我們的要求,
首先是刻度的顯示是在方格的中間,這需要隱藏刻度,其次是如何把每個label顯示在每個方塊的中間, 其次是如何在每個方格中顯示accuracy數值, 最後是如何在橫坐標和縱坐標顯示label的名字,在label name比較長的時候,如何處理顯示問題。
直接貼上代碼:
[python]view plain
'''''computeconfusionmatrix
labels.txt:containlabelname.
predict.txt:predict_labeltrue_label
'''
fromsklearn.metricsimportconfusion_matrix
importmatplotlib.pyplotasplt
importnumpyasnp
#loadlabels.
labels=[]
file=open('labels.txt','r')
lines=file.readlines()
forlineinlines:
labels.append(line.strip())
file.close()
y_true=[]
y_pred=[]
#loadtrueandpredictlabels.
file=open('predict.txt','r')
lines=file.readlines()
forlineinlines:
y_true.append(int(line.split("")[1].strip()))
y_pred.append(int(line.split("")[0].strip()))
file.close()
tick_marks=np.array(range(len(labels)))+0.5
defplot_confusion_matrix(cm,title='ConfusionMatrix',cmap=plt.cm.binary):
plt.imshow(cm,interpolation='nearest',cmap=cmap)
plt.title(title)
plt.colorbar()
xlocations=np.array(range(len(labels)))
plt.xticks(xlocations,labels,rotation=90)
plt.yticks(xlocations,labels)
plt.ylabel('Truelabel')
plt.xlabel('Predictedlabel')
cm=confusion_matrix(y_true,y_pred)
printcm
np.set_printoptions(precision=2)
cm_normalized=cm.astype('float')/cm.sum(axis=1)[:,np.newaxis]
printcm_normalized
plt.figure(figsize=(12,8),dpi=120)
#setthefontsizeoflabel.
#forlabelinplt.gca().xaxis.get_ticklabels():
#label.set_fontsize(8)
#textportion
ind_array=np.arange(len(labels))
x,y=np.meshgrid(ind_array,ind_array)
forx_val,y_valinzip(x.flatten(),y.flatten()):
c=cm_normalized[y_val][x_val]
if(c>0.01):
plt.text(x_val,y_val,"%0.2f"%(c,),color='red',fontsize=7,va='center',ha='center')
#offsetthetick
plt.gca().set_xticks(tick_marks,minor=True)
plt.gca().set_yticks(tick_marks,minor=True)
plt.gca().xaxis.set_ticks_position('none')
plt.gca().yaxis.set_ticks_position('none')
plt.grid(True,which='minor',linestyle='-')
plt.gcf().subplots_adjust(bottom=0.15)
plot_confusion_matrix(cm_normalized,title='Normalizedconfusionmatrix')
#showconfusionmatrix
plt.show()
linchunmian
2017-05-08 2
結果如下圖所示:
閱讀全文
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
目前您尚未登錄,請登錄或注冊後進行評論
8. python中怎麼將一個數據集中的每條數據轉換成相應的矩陣
python的一個很重要的包是numpy包,這個包可以很方便的做數據科學計算。numpy中有很多方法,array,matrix,對於數據集的每一條數據,可以通過matrix函數來將其轉換為矩陣形式,並且還有reshape方法,可以調整矩陣的行和列。
9. python語言將一個以為矩陣解包成n*n的矩陣
在python中,如果if後面表達式的取值是 0,none,空列表,空元組,空字典,空集合等都認為是false
10. python中如何將Series里的datetime格式去掉
a.apply(lambda x: str(x)) 直接轉換為字元串格式