4
\$\begingroup\$

Recentely I have started teaching myself some basic AI concepts and this was my first attemp at using a random forest in order to classify the iris data set. It would be great if anyone could give me any sort of feedback on the code, specifically the style and readability. I apologize if the code block is formatted incorrectly (this is my first time using stack exchange). Thank you!

import numpy as np
from sklearn.model_selection import cross_validate
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split

# Data goes through preprocessing, Label encoding is used to map
# String identifiers to float


def data_processor(input_file):
    data = []
    with open(input_file, 'r') as f:
        for line in f:
            line = line.strip().split(',')
            if line[-1] == 'Iris-setosa':
                line[-1] = 0
            elif line[-1] == 'Iris-versicolor':
                line[-1] = 1
            elif line[-1] == 'Iris-virginica':
                line[-1] = 2
            data.append(line)

    return np.array(data, dtype=float)


# create array of data and array of index
x, y = data_processor('iris.txt')[:, :-1], data_processor('iris.txt')[:, -1]

# create training and test data set, 80% training 20% test
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.20,
                                                random_state=5)

# params used to create classifier
# number of trees - 150, node depth - 5, random seed
params = {'n_estimators': 150, 'max_depth': 5, 'random_state': 10}
classifier = ExtraTreesClassifier(**params)
classifier.fit(x_train, y_train)
# make prediction
y_test_pred = classifier.predict(x_test)

# output info on model performance
class_names = ['Setosa', 'Versicolor', 'Virginica']
print("Training dataset results\n")
print(classification_report(y_train, classifier.predict(x_train),
                            target_names=class_names))
print("Testing dataset results\n")
print(classification_report(y_test, y_test_pred, target_names=class_names))
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

First of all, pandas, scikit-learn, numpy, keras and tf come with a lot of data loading utilities.

  • Your data_processor(input_file) can be replaced with pandas.read_csv().
  • Alternatively, IRIS dataset is avaiable at sklearn.datasets.load_iris()

I would advise to have a look at Scikit-learn's example of analyzing IRIS

\$\endgroup\$
1
  • \$\begingroup\$ Hi, Thank you for your reply and suggestions! The reason i did not use the pandas module was because the input file was in txt format. I know that this is convertable to csv, however I wanted to work on the original file. In regards to the iris data set that comes with sklearn, I did not want to import the data for the same reason, mainly to create a reusable function to work on text files of this format. I suppose that this may make the process computaionally slower, however I did not consider this a hinderance for a small data sample. \$\endgroup\$
    – Apol
    Commented Sep 2, 2019 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.