Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
1.6 kB
1
Indexable
Never
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score

breast_cancer=load_breast_cancer()
X=breast_cancer.data
y=breast_cancer.target

X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)

ntrees=[1,5,10,20,50,100,200]

accu_score=[]
pres_score=[]
rec_score=[]
f1score=[]

for n in ntrees:
    rf_clf=RandomForestClassifier(n_estimators=n,random_state=42)
    rf_clf.fit(X_train,y_train)

    y_pred=rf_clf.predict(X_test)
    
    acc=accuracy_score(y_test, y_pred)
    pr=precision_score(y_test, y_pred,average='weighted')
    rec=recall_score(y_test, y_pred,average='weighted')
    f1=f1_score(y_test, y_pred,average='weighted')

    accu_score.append(acc)
    pres_score.append(pr)
    rec_score.append(rec)
    f1score.append(f1)

    print(f'No of trees: {n}')
    print(f'Accuracy: {acc:.2f}')
    print(f'Precision: {pr:.2f}')
    print(f'Recall: {rec:.2f}')
    print(f'F1_score: {f1:.2f}')
    print("-----------------")

plt.figure(figsize=(6,6))
plt.plot(ntrees,accu_score,label='Accuracy',marker='o')
plt.plot(ntrees,pres_score,label='Precision',marker='.')
plt.plot(ntrees,rec_score,label='Recall',marker='d')
plt.plot(ntrees,f1score,label='F1',marker='s')
plt.xlabel("No of trees")
plt.ylabel("Score")
plt.title("Rrandom forest classifoer Breast Cancer Dataset")
plt.legend()
plt.grid(True)
plt.show()
Leave a Comment