<jupyter_start><jupyter_text>LetsGrowMore LGMVIP internship Task 2   Prediction using Decision Tree  Algorithm - Create the Decision Tree classifier and visualize it graphically. The purpose is if we feed any new data to this classifier, it would be able to  predict the right class accordingly.  - Author :- <NAME>  importing library<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import plot_tree
from sklearn import tree
from sklearn.metrics import accuracy_score<jupyter_output><empty_output><jupyter_text>Loading Data set<jupyter_code># Load the iris dataset
df = pd.read_csv('Iris.csv')
df.head()<jupyter_output><empty_output><jupyter_text>Dataset Info<jupyter_code>df.info()<jupyter_output><class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 6 columns):
 #   Column         Non-Null Count  Dtype  
---  ------         --------------  -----  
 0   Id             150 non-null    int64  
 1   SepalLengthCm  150 non-null    float64
 2   SepalWidthCm   150 non-null    float64
 3   PetalLengthCm  150 non-null    float64
 4   PetalWidthCm   150 non-null    float64
 5   Species        150 non-null    object 
dtypes: float64(4), int64(1), object(1)
memory usage: 7.2+ KB<jupyter_text>Finding Null Values<jupyter_code>df.isnull().sum<jupyter_output><empty_output><jupyter_text>Drop Id Columns<jupyter_code>df = df.drop(columns= ['Id'])
df.head()<jupyter_output><empty_output><jupyter_text>- Describe() is used to view some basic statistical details like percentile, mean, std etc. of a data frame or a series of numeric values.- The describe() function is used to generate descriptive statistics that summarize the central tendency, dispersion and shape of a dataset's distribution, excluding NaN values.<jupyter_code>df.describe()
df.shape
df['Species'].value_counts()
df['SepalLengthCm'].hist()
df['SepalWidthCm'].hist()
df['PetalLengthCm'].hist()
df['PetalWidthCm'].hist()
# Scatterplot 
colors = ['red', 'orange', 'blue']
species = ['Iris-virginica','Iris-versicolor','Iris-setosa']
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
l = ['Versicolor', 'Setosa', 'Virginica']
s = [50,50,50]
ax.pie(s, labels = l,autopct='%1.2f%%')
plt.show()
for i in range(3):
    x = df[df['Species'] == species[i]]
    plt.scatter(x['SepalLengthCm'], x['SepalWidthCm'], c = colors[i], label=species[i])
plt.xlabel("Sepal Length")
plt.ylabel("Sepal Width")
plt.legend()
for i in range(3):
    x = df[df['Species'] == species[i]]
    plt.scatter(x['PetalLengthCm'], x['PetalWidthCm'], c = colors[i], label=species[i])
plt.xlabel("Petal Length")
plt.ylabel("Petal Width")
plt.legend()
for i in range(3):
    x = df[df['Species'] == species[i]]
    plt.scatter(x['SepalLengthCm'], x['PetalLengthCm'], c = colors[i], label=species[i])
plt.xlabel("Sepal Length")
plt.ylabel("Petal Length")
plt.legend()
#Checking for outliars
import matplotlib.pyplot as plt
plt.figure(1)
plt.boxplot([df['SepalLengthCm']])
plt.figure(2)
plt.boxplot([df['SepalWidthCm']])
plt.show()
df.plot(kind ='density',subplots = True, layout =(3,3),sharex = False)
df.plot(kind ='box',subplots = True, layout =(2,5),sharex = False)
plt.figure(figsize=(15,10))
plt.subplot(2,2,1)
sns.violinplot(x='Species',y='PetalLengthCm',data=df)
plt.subplot(2,2,2)
sns.violinplot(x='Species',y='PetalWidthCm',data=df)
plt.subplot(2,2,3)
sns.violinplot(x='Species',y='SepalLengthCm',data=df)
plt.subplot(2,2,4)
sns.violinplot(x='Species',y='SepalWidthCm',data=df)
sns.pairplot(df,hue='Species');
df.corr()
corr = df.corr()
fig, ax = plt.subplots(figsize=(5,4))
sns.heatmap(corr, annot=True, ax=ax, cmap = 'coolwarm')
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df['Species'] = le.fit_transform(df['Species'])
df.head()
from sklearn.model_selection import train_test_split
# train - 70
# test - 30
X = df.drop(columns=['Species'])
Y = df['Species']
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.30)
#Model Building Decision Tree Model
clf = DecisionTreeClassifier()
clf = clf.fit(x_train,y_train)
clf
#Predict the response for test dataset
y_pred = clf.predict(x_test)
y_pred
y_test
data_frame = pd.DataFrame({"Actual Data" :y_test, "Predicted Data":y_pred})
data_frame.head()
data_frame.tail()<jupyter_output><empty_output><jupyter_text>Accuracy of the model<jupyter_code>print("Accuracy:",accuracy_score(y_test, y_pred))<jupyter_output>Accuracy: 0.9555555555555556<jupyter_text>Visualizing the Decision Tree<jupyter_code>col_names = ["Sepal length", "Sepal width", "Petal length", "Petal width"]
target_names = ["Setosa", "Versicolor", "Virginica"]
plot_tree(clf, feature_names=col_names, class_names=target_names, filled=True)
model = DecisionTreeClassifier().fit(X,Y)
plt.figure(figsize=(20,15))
tree = tree.plot_tree(model, feature_names=col_names, class_names=target_names, filled=True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14997012547301333, 'fraction_numerical': 0.023700458076080462, 'mean_word_length': 6.063291139240507, 'pattern_counts': {'":': 1, '<': 33, '<?xml version=': 0, '>': 33, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '385751', 'license': 'MIT', 'n_tokens_mistral': 1968, 'n_tokens_neox': 1833, 'n_words': 411, 'path': 'Task 2nd/Prediction using Decision Tree  Algorithm .ipynb', 'repo_name': 'bhushanasati25/LGMVIP-DataScience', 'size': '5028'}