import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier as Rafo
np.random.seed(2)
X,z = datasets.make_blobs(n_samples=100,n_features=2,centers=5)
rafo = Rafo()
rafo.fit(X,z)
# สร้างเตรียมฟังก์ชันสำหรับวาดภาพแสดงผล
def plottassimo(X,z,mx,my,mz):
plt.figure()
plt.axes(aspect=1,xlim=[mx.min(),mx.max()],ylim=[my.min(),my.max()])
plt.scatter(X[:,0],X[:,1],alpha=0.6,c=z,edgecolor='k',cmap='rainbow')
plt.contourf(mx,my,mz,alpha=0.4,cmap='rainbow',zorder=0)
plt.show()
nmesh = 200
mx,my = np.meshgrid(np.linspace(X[:,0].min(),X[:,0].max(),nmesh),np.linspace(X[:,1].min(),X[:,1].max(),nmesh))
mX = np.stack([mx.ravel(),my.ravel()],1)
mz = rafo.predict(mX).reshape(nmesh,nmesh)
plottassimo(X,z,mx,my,mz)
print(len(rafo.estimators_))
print(rafo.estimators_[0])
10
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
max_features='auto', max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort=False,
random_state=388557017, splitter='best')
mz = rafo.estimators_[0].predict(mX).reshape(nmesh,nmesh)
plottassimo(X,z,mx,my,mz)
mz = rafo.estimators_[7].predict(mX).reshape(nmesh,nmesh)
plottassimo(X,z,mx,my,mz)
np.random.seed(3)
X,z = datasets.make_blobs(n_samples=100,n_features=2,centers=2,cluster_std=2.2)
rafo = Rafo(n_estimators=15)
rafo.fit(X,z)
nmesh = 200
mx,my = np.meshgrid(np.linspace(X[:,0].min(),X[:,0].max(),nmesh),np.linspace(X[:,1].min(),X[:,1].max(),nmesh))
mX = np.stack([mx.ravel(),my.ravel()],1)
mz = rafo.predict_proba(mX)[:,1].reshape(nmesh,nmesh)
plt.figure()
plt.axes(aspect=1,xlim=[mx.min(),mx.max()],ylim=[my.min(),my.max()])
plt.scatter(X[:,0],X[:,1],alpha=0.6,c=z,edgecolor='k',cmap='RdYlGn')
plt.contourf(mx,my,mz,100,alpha=1,cmap='RdYlGn',zorder=0)
plt.colorbar(pad=0.01)
plt.show()
n = [2,5,20]
plt.figure(figsize=[6,8])
for i in range(3):
rafo = Rafo(n_estimators=n[i])
rafo.fit(X,z)
for j in [0,1]:
if(j):
mz = rafo.predict_proba(mX)[:,1].reshape(nmesh,nmesh)
else:
mz = rafo.predict(mX).reshape(nmesh,nmesh)
plt.subplot(321+i*2+j,aspect=1,xlim=[mx.min(),mx.max()],ylim=[my.min(),my.max()])
plt.scatter(X[:,0],X[:,1],10,alpha=0.6,c=z,edgecolor='k',cmap='RdYlGn')
plt.contourf(mx,my,mz,100,alpha=1,cmap='RdYlGn',zorder=0)
plt.show()
ติดตามอัปเดตของบล็อกได้ที่แฟนเพจ