|
|
|
|
|
import pandas as pd |
|
|
from sklearn.datasets import load_iris |
|
|
from sklearn.model_selection import train_test_split |
|
|
from sklearn.ensemble import RandomForestClassifier |
|
|
from sklearn.metrics import accuracy_score, classification_report |
|
|
import matplotlib.pyplot as plt |
|
|
import seaborn as sns |
|
|
import joblib |
|
|
from datetime import datetime |
|
|
|
|
|
start_time = datetime.now() |
|
|
|
|
|
|
|
|
print("Loading Dataset...") |
|
|
data = load_iris() |
|
|
print("Dataset Loaded. Extracting data from the dataset...") |
|
|
X = pd.DataFrame(data.data, columns=data.feature_names) |
|
|
print("Extracting Features or target values...") |
|
|
y = pd.Series(data.target, name='species') |
|
|
|
|
|
|
|
|
print("Concating the new df") |
|
|
df = pd.concat([X, y], axis=1) |
|
|
print("Renaming columns...") |
|
|
df.columns = data.feature_names + ['species'] |
|
|
print("Plots the graph") |
|
|
sns.pairplot(df, hue='species') |
|
|
print("Showing the graph...") |
|
|
plt.show() |
|
|
|
|
|
|
|
|
print("Splicing...") |
|
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) |
|
|
|
|
|
|
|
|
print("Training the model...") |
|
|
model = RandomForestClassifier(n_estimators=100, random_state=42) |
|
|
model.fit(X_train, y_train) |
|
|
print("Training completed.") |
|
|
|
|
|
|
|
|
print("Testing the model...") |
|
|
y_pred = model.predict(X_test) |
|
|
|
|
|
|
|
|
print("Finding Accuracy and classification report") |
|
|
print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}") |
|
|
print("Classification Report:") |
|
|
print(classification_report(y_test, y_pred)) |
|
|
|
|
|
|
|
|
print("Extracting Important Features...") |
|
|
feature_importances = pd.Series(model.feature_importances_, index=data.feature_names) |
|
|
print("Sorting and plotting the graph...") |
|
|
feature_importances.sort_values(ascending=True).plot(kind='barh') |
|
|
plt.title('Feature Importances') |
|
|
print("Plotted.") |
|
|
plt.show() |
|
|
|
|
|
|
|
|
print("Saving the model...") |
|
|
joblib.dump(model, 'random_forest_model.pkl') |
|
|
print("Model saved as random_forest_model.pkl") |
|
|
end_time = datetime.now() |
|
|
|
|
|
elapsed_time = end_time - start_time |
|
|
print("Elapsed time:", elapsed_time) |