35
Trí tu tính toán và ng d ng PGS.TS. Trn Văn Lăng

Trí tuệ tính toán và ứng dụng - FAIR

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Trí tuệ tính toán và ứng dụng - FAIR

Trí tuệ tính toán và ứng dụngPGS.TS. Trần Văn Lăng

Page 2: Trí tuệ tính toán và ứng dụng - FAIR

ThuậttoánK-lánggiềnggầnnhất

• Tentie)ngAnhlaKNN(K-NearestNeighbor),• Lathuattoanthuocloaisupervised-learningđơngiannha) t• KNNcotheE apdungđươcchocaClassiHicationvaRegression• Khitraining,KNNkhonghocmotđieLugıtưdưlieu,moitınhtoanđươcthưchienkhidưđoanke) tquacuadưlieumơi

2

Page 3: Trí tuệ tính toán và ứng dụng - FAIR

• Vơiviệcphânlớp,nhan(đaLura)cuamotđieEmdưlieu(DataPoint)mơiđươcsuyratưKđieEmdưlieugaLnnha) ttrongtaphua)nluyen.

• Vơihồiquy,đaLuracuamotđieEmdưlieubaVngchınhđaLuracuađieEmdưlieuđabie) tgaLnnha) t(trongtrươnghơpK=1)

• Tómtại,KNNlathuattoanđitımđaLuracuamotđieEmdưlieumơibaVngcachchıdưatrenthongtincuaKđieEmdưlieutrongtaphua)nluyengaLnnonha) t(K-lancan),makhongquantamđe)nvieccomotvaiđieEmdưlieutrongnhưngđieEmgaLnnha) tnaylanhieYu(dưlieumacolơigiaisai)

3

Page 4: Trí tuệ tính toán và ứng dụng - FAIR

Minhhoạ

• GiasưcomotdatasetgoLm2loaidưlieulamàuđỏ(class1)vamàuxanh(class0)nhưhınhbencanh.

• ThuattoanK-NNhaytımđieEm(50,25)–cohìnhdấuOmàuđen–đeE bie) tđieEmnaythuocclass1hayclass2

• Cachlam:• TınhkhoangcachtưđiểmOđe)nta) tcacacđieEmcotrongDataSet.

• SauđochıraKđieEmgaLn(ơđayla)yK=3)vơiđieEmdấuOnaynha) t

4

• Co2đieEmthuocclass1,va1đieEmthuocclass0.

• VayđiểmOnaythuocclass1

File:Draw-graph.ipynb

Page 5: Trí tuệ tính toán và ứng dụng - FAIR

• Chươngtrınhgiaiquye) tva)nđeL naynhưsau:• Taodưlieuimport random N, M = 21, 2 X1, X2, Y1, Y2 = [], [], [], [] for i in range(0, N): X1.append([]), X2.append([]) X1[i].append(i*5) X1[i].append( int(random.random()*50) ) X2[i].append(i*5) X2[i].append( int(random.random()*50) ) Y1.append( 1 ) Y2.append( 0 ) y = Y1 + Y2 X = X1 + X2

5

• Taodưlieux = np.arange( 0,N*5,5 ) y1, y2 = [], [] for i in range(0,N): y1.append( X[i][1] ) y2.append( X[i+N][1] )

• Vehınhplt.figure( figsize=(10,6) ) plt.scatter( x,y1,c='r',marker='x',label='class 1' ) plt.scatter( x,y2,c='b',marker='+',label='class 0' ) plt.plot( 50, 25, 'o', color="black" ) plt.legend() plt.show()

Page 6: Trí tuệ tính toán và ứng dụng - FAIR

6

• Hua)nluyenvadưbaofrom sklearn import neighbors model = neighbors.KNeighborsClassifier( n_neighbors=3 ) model.fit( X,y ) print( "Thuộc lớp: ", model.predict( [[50,25]]) )

print( "với xác suất là ", model.predict_proba( [[50,25]]) )

File:Draw-graph.py

Page 7: Trí tuệ tính toán và ứng dụng - FAIR

Địnhnghĩavềkhoảngcách

• Cho2vector cocacthanhphaLnla

• Khoangcachbac cua2vectornaylaconso) đươckyhieula,ngươitacongoilakhoangcachMiskowsky

• Trongmotso) trươnghơprieng

X, YX = (x1, x2, . . . , xn)T, Y = (y1, y2, . . . , yn)T

p

∥X − Y∥p = (N

∑i=1

|xi − yi |p )

1/p

7

• Trongmotso) trươnghơprieng,co

• KhoangcachEuclide(haylachuaEn )

• Khoangcachtuyetđo) i( )haycongoilakhoangcachHamming,hayManhattan

L2

∥X − Y∥2 =N

∑i=1

|xi − yi |2

p = 1

∥X − Y∥ =N

∑i=1

|xi − yi |

Page 8: Trí tuệ tính toán và ứng dụng - FAIR

VídụKNN

• KhoangcachChebyshev∥X − Y∥ = lim

p→∞∥X − Y∥p

= (N

∑i=1

|xi − yi |p )

1/p

= max1≤i≤n

|xi − yi |

8

• La)ydưlieubenhtieEuđươngcuangươiAj nĐo(https://www.kaggle.com/uciml/pima-indians-diabetes-database)

• DưlieubaogoLm:• Pregnancies:So) laLnmangthai• Glucose:LươngGlucose• BloodPressure:An phuye) ttamtrương• SkinThickness:VeL da• Insulin:NoL ngđoinsulin• BMI:Bodymassindex(tylegiưatrong

lươngvachieLucao)• DiabetesPedigreeFunction:loaitieEu

đương• Age:TuoE i• Outcome:Ke) tqua1hoac0

Page 9: Trí tuệ tính toán và ứng dụng - FAIR

Pythonvớisci-kitlearn

• MotavachuaEnbidưlieuimport pandas as pd import numpy as np from sklearn import model_selection,metrics,neighbors import matplotlib.pyplot as plt data = pd.read_csv( '../dataset/diabetes.csv' ) N = len( data.columns ) - 1 X = data.iloc[:,:-1].values y = data.iloc[:,N].values X_train, X_test, y_train, y_test = model_selection.train_test_split( X,y,test_size=0.3,random_state=42 )

9

• TaomohınhvathưnghiemNUM_K = 3 model = neighbors.KNeighborsClassifier( n_neighbors=NUM_K,p=2 ) model.fit( X_train,y_train ) y_pred = model.predict( X_test )

Page 10: Trí tuệ tính toán và ứng dụng - FAIR

• ThưvơinhieLuKkhacnhauđeE bieEudieYnthanhđoL thi,quađobie) tđươcvơiKbaVngma)ythıcotyleso) trươnghơpdưđoansai

NUM_K, error = 50, [] for i in range(1,NUM_K): model = neighbors.KNeighborsClassifier(

n_neighbors=i ) model.fit( X_train,y_train ) y_pred = model.predict( X_test ) error.append( np.mean(y_pred != y_test) )

10

plt.figure( figsize=(8,6) ) plt.title( "Đồ thị số lượng khác nhau giữa kết quả đự đoán và dataset" ) plt.plot( range(1,NUM_K),error,color='red',linestyle='dashed',marker='o',markerfacecolor='blue', markersize=5 ) plt.xlabel( "Số láng giềng K" ) plt.ylabel( "Số lượng khác trên tổng số dữ liệu cần test" ) plt.show()

File:KNN-sklearn.py

Page 11: Trí tuệ tính toán và ứng dụng - FAIR

KNNdùngTensorFlowver2

data = pd.read_csv( '../dataset/diabetes.csv' ) N = len( data.columns ) - 1 X = data.iloc[:,:-1].values y = data.iloc[:,N].values X_train,X_test,Y_train,Y_test = model_selection.train_test_split( X,y,test_size=0.33,random_state=42 )

• Ơu đaytađinhnghıahamđeE tımkhoangcachnhonha) ttưcacphaLntưtrongtapkieEmtrađe)ntaphua)nluyen.def mindist( x_test, x_train ): L = tf.sqrt( tf.reduce_sum( tf.square(tf.subtract(x_test,x_train)),1 ) ) return tf.argmin( L,0 ).numpy()

• La)ylaidưlieuđacotrongvıdutrươcveL benhtieEuđương.• MotathemthưvienTensorFlowimport tensorflow as tf import pandas as pd import numpy as np from sklearn import model_selection, metrics

• Loaddưlieutưtaptinsauđodanhra30%lamdưlieukieEmtra,vadưlieunayco) đinhtrongcaclaLnthưcthikhacnhaucuachươngtrınh

11

Page 12: Trí tuệ tính toán và ứng dụng - FAIR

• Goihammindist()ơtrenđeE laLnlươttımphaLntưnaotrongtaphua)nluyenmagaLnvơitưngphaLntưcuatapkieEmtranha) t,sauđola)ynhancuaphaLntưtươngưngcuataphua)nluyenganchotapdưđoannay.

• Tưđotınhđochınhxacy_pred = tf.Variable( [1]*len(X_test) ) for i in range( len(X_test) ): k = mindist( X_test[i,:],X_train ) y_pred[i].assign( Y_train[k] ) print( "Accuracy: ", metrics.accuracy_score(y_pred.numpy(),Y_test) )

• Ke) tquaAccuracy: 0.6968503937007874

12

File:KNN-tensorHlow.py

Page 13: Trí tuệ tính toán và ứng dụng - FAIR

• Tổngkếtlại:KNNđươcsưdungchoviecdưbaocaphanloaivahoL iquy.• Tuynhien,nođươcsưdungrongraichophanloai,vathươngđươcsưdungtrongcacưngdungtımkie)m.

• 1-NNđeE taomotmohınhcocaclơpdưatren1đieEmdưlieuơkhoangcachnhonha) t.Tươngtư,2-NNconghıalachungtaphaitaomotmohınhcocaclơpdưatren2đieEmdưlieuvơikhoangcachnhonha) t.

• CacbươcthuattoanbaogoLm:• TınhkhoangcachgiưacacđieEmdưlieumơisovơita) tcacacdưlieuhua)nluyen• ChonraKmuccotrongdưlieuhua)nluyengaLnnha) tvơiđieEmdưlieumơi.• BınhchonlơphaynhanphoE bie)nnha) ttrongso) cacmucK,đolalơpcuađieEmdưlieumơi.

13

Page 14: Trí tuệ tính toán và ứng dụng - FAIR

• ThuattoanKNNđươcchonkhicacso) lươngcaclơpdưlieutươngưngnhauveL kıchcơ• KhimotđieEmdưlieuphuthuocnhieLuthamso) thıKNNsephaitınhkhoangcachgiưacacđieEmra) tcham

• ChonKbaVngbaonhieucunglava)nđeL khotrenmotdatasetcutheE

14

Page 15: Trí tuệ tính toán và ứng dụng - FAIR

ThaotácthôngdụngvềTensorFlowversion2

• KhidungTensorFlowchungtaphaikhaibaotrongvungcuano.• Khaibaobie)ndungtf.Variable()• KhaibaohaVng,dungtf.constant()

• TruycapmotphaLntưcuatensor,vıdu:• t4[1,1,2]cogiatrila11.0• t3[0,3]cogiatrila4

15

Page 16: Trí tuệ tính toán và ứng dụng - FAIR

• ChuyeEnmotbie)ncuaTensorFlowtrơthanhmotbie)ncuaPythondungphươngthưcnumpy()cuađo) itươngđo

• Ngươclai,dungphươngthưcconvert_to_tensor()cuaTensorFlow

16

• ChuyeEnvimatran,nhanmatran

• Tınhgiatritrungbınh

Page 17: Trí tuệ tính toán và ứng dụng - FAIR

ThuậttoánK-means

• Trongthưcte) thươnghaycoviecphanloaimangtınhtươngđo) i,cha{nghantrongmottoE chưcdoconngươiđieLuhanhvaquanly,thıconhưngnhomngươicocungmotnhanđinhveL motsưkiennaođo.

• Va)nđeL đatralacaLnphanloaiđeE bie) tmotngươitrongtoE chưcnaycơbanlathuocveL nhomnao.

• Cungnhưvay,cobaonhieungươitrongcungmotloaibenhtrongmotcongđoL ngdancư• Va)nđeL phưctapơđaylakhongbie) ttrươccacđactrưngcuanhomđeE phanlơpnhưtrongthuattoanKNN.

• K-meanshayK-meansclustering,lathuattoangomcụmKnhómtheotrungbình.• Thuattoangiupchochungtagiaiquye) tva)nđeL nay.Đaychınhlathuattoanthuocloaihockhonggiamsat

17

Page 18: Trí tuệ tính toán và ứng dụng - FAIR

Minhhoạ

• PhancumK-meanslathuattoanđơngiantrongunsupervisedlearning.

• TrongK-meansclustering,nhancuatưngđieEmdưlieu(Datapoint)khongbie) ttrươc.

• Va)nđeL lalamtheE naođeE phandưlieuthanhcacnhom/cum(cluster)saochodưlieutrongcungmotcumconhưngtınhcha) tgio) ngnhau.

18

• TrongKNN,saukhiphanlơpxongthımoY iđieEmdưlieuchıthuocmotlơphaynhanduynha) t.

• TrongkhiđovơiK-means,moY iphaLntưcotheE thuocnhieLunhomhaycum.

• Nhom/cumơđaylataphơpcacđieEmcocacvectorđactrưnggaLnnhau.

• ViecđokhoangcachgiưacacvectorthươngđươcthưchiendưatrencacchuaYnnhưđatrınhbay,trongđokhoangcachEuclideđươcsưdungphoE bie)nnha) t.

Page 19: Trí tuệ tính toán và ứng dụng - FAIR

• ThuattoangoLmcacbươcdưatrencacđieEmdưlieu –lưuylakhongconhanvaso) nhomK.

• Chon đieEmba) tkylamđieEmtrungtamcuacacnhom(Center)goilatrongtam(Centroid)haycongoilađieEmđaidien(RepresentativePoint)

• TınhkhoangcachtưcacđieEmdưlieuđe)n đieEmCentroid

• PhanboE cacđieEmdưlieunayvaocacnhomcokhoangcachđe)nCentroidcuanhomnaygaLnnha) t

• TınhlaiCentroidcua nhombaVngcachla)ytrungbınhcongcuacacđieEmđađươcganvaonhom.

X

K

K

K

19

Page 20: Trí tuệ tính toán và ứng dụng - FAIR

Ứngdụng

• ĐeE deY hınhdungtagiasưmotcatheE (motngươidan,motngươilamviec,...)trongquaLntheE (motcongđoL ngdancư,mottoE chưc,...)đươcso) hoabaVngmottoađo

• Cha{nghantaco600đieEmdưlieuđươcphanboE nhưhınh

(xi, yi)

20

Page 21: Trí tuệ tính toán và ứng dụng - FAIR

• DưlieunayđươctaongaYunhienbaVngphanpho) iGaussxungquanh3đieEmchınh(tataorađeE đinhhương)vơimatranhiepphươngsaichıđinhcentroids = [[5,15],[12,5],[20,20]] DATASIZE = 600 K = 3 def myrand(centroid): return np.random.multivariate_normal( mean=centroid,cov=[[10,0],[0,10]],size=DATASIZE ) X0 = myrand( centroids[0] ) X1 = myrand( centroids[1] ) X2 = myrand( centroids[2] ) X = np.concatenate((X0, X1, X2), axis = 0)

21

Page 22: Trí tuệ tính toán và ứng dụng - FAIR

• ĐeE hua)nluyenbaVngK-meansmodel = cluster.KMeans( n_clusters=3 ) model.fit(X) y_pred = model.predict(X)

• Saukhicoke) tquadưbao,tathưcoilaicacđieEmtrungtamprint( "Các điểm trọng tâm là\n", model.cluster_centers_ )

print( "Kết quả phân nhóm\n", y_pred ) for i in range(len(y_pred)): print( y_pred[i], end=' ' )

• Coiquahınhminhhoa

22

Page 23: Trí tuệ tính toán và ứng dụng - FAIR

DùngTensorFlow

• La)ydưlieunhưtrongvıdudungphươngthưccuasklearn,ơđaycunggio) ngnhưkhidungTensorFlowchoKNN,takhaibaothemcacbie)nTensornhưsau:X = tf.Variable( X_train )

• La)y thanhphaLntrongtaphua)nluyen đeE lam trongtamcents = tf.Variable( X[0:K] )

KX K

23

• Xaydưnghamhua)nluyendef pred(tt): cents_expanded = tf.expand_dims( tt,1 ) L = tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(

X,cents_expanded)),axis=2)) y = tf.argmin( L,0 ) means = [] for c in range(K):

means.append( tf.reduce_mean(tf.gather(X,tf.reshape(tf.where(tf.equal(y,c)),[1,-1])),[1]) ) new_cents = tf.concat( means,0 ) return new_cents, y

Page 24: Trí tuệ tính toán và ứng dụng - FAIR

• Laplai1000laLnfor _ in range(1000): cents, y_pred = pred( cents )

• VelaihınhđeE trưcquanhoaplt.figure( figsize=(10,6) )

plt.title( "Có 3 nhóm cụ thể sau 1000 lần lặp" ) plt.xlabel('Trục x') plt.ylabel('Trục y') plt.scatter( X_train[:,0],X_train[:,1],c=y_pred,s=20 ) plt.plot( cents[:,0],cents[:,1],'k*',color='blue',markersize=15) plt.show()

24

File:Kmeans-tensorHlow.py

Page 25: Trí tuệ tính toán và ứng dụng - FAIR

VídụthựctếvềK-means

• Treninternetcora) tnhieLudatasetđeE chophepchungtathưcnghiemcacphươngphap,cungnhưđeE daLnquenvơiviecgiaiquye) tnhưngva)nđeL thưcte) baVngcactınhtoanthongminh.

• Cha{nghan,https://www.kaggle.com/datasets

25

Page 26: Trí tuệ tính toán và ứng dụng - FAIR

• HaytaikhoveL MachineLearningcuaCenterforMachineLearningandIntelligentSystems(http://archive.ics.uci.edu/ml/datasets.php)thuocUniversityofCalifornia-Irvine.

• Taiđaylưutrưdatasetcuara) tnhieLulınhvưctưnam1987đe)nnay.NhaVmđeE phantıchthưcnghiemcacthuattoanhocmay.

26

Page 27: Trí tuệ tính toán và ứng dụng - FAIR

• GiasưtadungdưlieuveL benhungthưvu(http://archive.ics.uci.edu/ml/datasets/Breast+Cancer+Coimbra)

• Datasettaihttp://archive.ics.uci.edu/ml/machine-learning-databases/00451/dataR2.csv

• Co9thuoctınhvađươcgannhanla1khoemanh(healthycontrols)va2labibenh(patients)

27

Page 28: Trí tuệ tính toán và ứng dụng - FAIR

• ChungtacotheE đoctrưctie)pHilenaytưinternetcungvơinhưngimportnhưvıdutrươcdataset = pd.read_csv( "http://archive.ics.uci.edu/ml/machine-learning-databases/00451/dataR2.csv" )

• CotheE dưlieukhongđaLyđu,baVngcachkieEmtra,roL isauđocotheE xưlybaVngcachthaygiatritrungbınhtươngưng,dataset.isnull().any() data = dataset.fillna( dataset.mean() ) dataset.isnull().any()

28

Page 29: Trí tuệ tính toán và ứng dụng - FAIR

• Docotcuo) icunglanhanđươcgan(đaphanlơp,nentadungcotnaynhưladưlieuđeE sosanhke) tqua),tưđaytaoraX_trainvay_trainnhưcachlamtrongcacvidutrươcN = len(data.columns)-1 X_train = data.iloc[:,0:-1].values y_train = data.iloc[:,N].values

• Chonso) cumla2,valaplai100laLnto) iđamodel = cluster.KMeans( n_clusters=2, max_iter=100 ).fit(X_train) y_pred = model.predict( X_train ) print( "Number of iterations run: ", model.n_iter_ ) print( "Sum of squared distances of samples to their closest cluster center: ", model.inertia_ ) print( "Coordinates of",NUM_CLUSTERS,"cluster centers\n", model.cluster_centers_ ) y_pred += 1 # Do nhãn lưu giá trị là 1 và 2 print( "Accuracy: ", metrics.accuracy_score(y_train,y_pred) )

29

Page 30: Trí tuệ tính toán và ứng dụng - FAIR

• Ke) tquasaukhihua)nluyenbaVngK-means

30

File:Kmeans-sklearn2.py

Page 31: Trí tuệ tính toán và ứng dụng - FAIR

Tómlại

• Vơiytươngcuathuattoanlabodưlieukhaosat(matahaygoiladataset)đươcphanthanhnhom.

• MoY inhomtımcentroid(trongtam)tươngưng• SauđotınhtoE ngkhoangcach(sumofsquareddistances)cuata) tcacacdưlieuthuocnhomnayđe)ncentroid;sauđocongdoL nđeE đươctoE ngcuata) tca(Totalsumofsquareddistances-TSS).

• MuctieuphanbodưlieubanđaLuthanh cumkhacnhausaochocacdưlieuthuoccungmotcumlatươngđoL ngnha) t;đieLuđoconghıaTSSlanhonha) t.

• KhokhaccuasưdungK-meanslalưachon saochoto) iưu.• Mothanche) cuaK-meansđolaviecgomcummangtınhto) iưucucbovılơigiaitımđươccancưvaođieEmtrongtamđươc"đinhhương"banđaLu

K

K

K

31

Page 32: Trí tuệ tính toán và ứng dụng - FAIR

• DoTSSgiamkhi tang,vagiamchođe)nkhongne)u baVngso) dưlieu.

• Matkhackhitang (conghıalaso) cumtang),nenthuattoantrơnenkhongcoynghıakhiso) cumlaquanhieLu.

• Chon baVngđoL thiElbow:khiđoL thicochoY ga)pnayronetnha) t,đolaso) to) iưu.• Cha{nghanvơivıdutrươc,choKđươcthưtư2chođe)n40

tss = [] K = range(2,41) for k in K: model = cluster.KMeans( n_clusters=k, max_iter=100 ).fit(X) tss.append( model.inertia_ )

K KK

K K

32

Page 33: Trí tuệ tính toán và ứng dụng - FAIR

• NhınvaođoL thiElbow,tatha)yK=3lachoY biga)pkhucnha) tplt.figure( figsize=(10,6) ) plt.plot( K,tss )

plt.title( "Đồ thị Elbow để chọn số K" )

plt.xlabel( "Số cụm" )

plt.ylabel( "Tổng của tất cả tổng các khoảng cách đến các điểm trung tâm" ) plt.grid( True ) plt.show())

33

Page 34: Trí tuệ tính toán và ứng dụng - FAIR

• NhưngdotakhongtheE chıchomay"nhınvaođoL thi"đươcnhưngươi,maphaidungtie)ngnaođođeE chı,ơđaytalaidung"tie)ngPython".

• Nhưngtrươche) tphaidungToanhocđeE nhanbie) tđaulaElbowPoint.• ĐieEmElbowlađieEmmakhoangcachtưnođe)nđươngtha{ngđiqua2đieEmđaLuvacuo) icuađươngconglalơnnha) t.

• Trươctien:đaylaphươngtrınhđươngtha{ngqua2đieEmA,B(lamangcacgiatritungđo)def fx(X,A,B): y = [] for i in range(len(X)): x = X[i] temp = A[1] + (X[i]-A[0])*(B[1]-A[1])/(B[0]-A[0]) y.append( temp ) return y

34

Page 35: Trí tuệ tính toán và ứng dụng - FAIR

• TınhkhoangcachgiưanhưngđieEmtrenđươngtha{ngnayvanhưngđieEmơtrenđươngcongmacocunghoanhđo,sauđotımđieEmcokhoangcachlơnnha) tđeE traveL .import numpy as np from scipy.spatial import distance def ElbowPoint( x_axis, curve ): N = len(curve) S = [x_axis[0],curve[0]] E = [x_axis[N-1],curve[N-1]] y = fx( K,S,E ) dist = [] for i in range(N): x = x_axis[i] dist.append( distance.cdist([[x,curve[i]]],[[x,y[i]]]) ) return np.argmax( dist )

35

• So) lươngcumcaLnphannhomđolavitrıcuakhoangcachlơnnha) tnayNUM_CLUSTERS = ElbowPoint( K, tss ) + 1

• Dochıso) mangba� tđaLutư0nenphaicongthem1lavayđo!

File:Kmeans-sklearn.py