Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ################################
- # Machine Learning with Python #
- ################################
- Reference:
- http://machinelearningmastery.com/machine-learning-in-python-step-by-step/
- ---------------------------Type This-----------------------------------
- sudo apt install -y python-scipy python-numpy python-matplotlib python-matplotlib-data python-pandas python-sklearn python-sklearn-pandas python-sklearn-lib python-scikits-learn
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- vi libcheck.py
- -----------------------------------------------------------------------
- #!/usr/bin/env python
- # Check the versions of libraries
- # Python version
- import sys
- print('Python: {}'.format(sys.version))
- # scipy
- import scipy
- print('scipy: {}'.format(scipy.__version__))
- # numpy
- import numpy
- print('numpy: {}'.format(numpy.__version__))
- # matplotlib
- import matplotlib
- print('matplotlib: {}'.format(matplotlib.__version__))
- # pandas
- import pandas
- print('pandas: {}'.format(pandas.__version__))
- # scikit-learn
- import sklearn
- print('sklearn: {}'.format(sklearn.__version__))
- -----------------------------------------------------------------------
- ---------------------------Type This-----------------------------------
- python
- import pandas csv
- from pandas.tools.plotting import scatter_matrix
- import matplotlib.pyplot as plt
- from sklearn import model_selection
- from sklearn.metrics import classification_report
- from sklearn.metrics import confusion_matrix
- from sklearn.metrics import accuracy_score
- from sklearn.linear_model import LogisticRegression
- from sklearn.tree import DecisionTreeClassifier
- from sklearn.neighbors import KNeighborsClassifier
- from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
- from sklearn.naive_bayes import GaussianNB
- from sklearn.svm import SVC
- url = "https://raw.githubusercontent.com/johnniev5/Microsoft-Malware-Classification-Challenge/master/sampleSubmission.csv"
- names = ["Id", "Prediction1", "Prediction2", "Prediction3", "Prediction4", "Prediction5", "Prediction6", "Prediction7", "Prediction8", "Prediction9"]
- dataset = pandas.read_csv(url, names=names)
- -----------------------------------------------------------------------
- Summarize the Dataset
- ---------------------
- We can get a quick idea of how many instances (rows) and how many attributes (columns) the data contains with the shape property.
- ---------------------------Type This-----------------------------------
- >>> print(dataset.shape)
- >>> print(dataset.head(20))
- -----------------------------------------------------------------------
- You should see the first 20 rows of the data:
- Statistical Summary
- -------------------
- Now we can take a look at a summary of each attribute.
- This includes the count, mean, the min and max values as well as some percentiles.
- ---------------------------Type This-----------------------------------
- >>> print(dataset.describe())
- -----------------------------------------------------------------------
- Class Distribution
- ------------------
- Let’s now take a look at the number of instances (rows) that belong to each class. We can view this as an absolute count.
- ---------------------------Type This-----------------------------------
- >>> print(dataset.groupby('class').size())
- -----------------------------------------------------------------------
- We can see that each class has the same number of instances
- Data Visualization
- ------------------
- We now have a basic idea about the data. We need to extend that with some visualizations.
- We are going to look at two types of plots:
- - Univariate plots to better understand each attribute.
- - Multivariate plots to better understand the relationships between attributes.
- Univariate Plots
- We start with some univariate plots, that is, plots of each individual variable.
- Given that the input variables are numeric, we can create box and whisker plots of each.
- ---------------------------Type This-----------------------------------
- >>> dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
- >>> plt.show()
- -----------------------------------------------------------------------
- This gives us a much clearer idea of the distribution of the input attributes:
- ******************* INSERT DIAGRAM SCREENSHOT *******************
- We can also create a histogram of each input variable to get an idea of the distribution.
- ---------------------------Type This-----------------------------------
- >>> dataset.hist()
- >>> plt.show()
- -----------------------------------------------------------------------
- It looks like perhaps two of the input variables have a Gaussian distribution. This is useful to note as we can use algorithms that can exploit this assumption.
- ******************* INSERT DIAGRAM SCREENSHOT *******************
- Multivariate Plots
- ------------------
- Now we can look at the interactions between the variables.
- First let’s look at scatterplots of all pairs of attributes. This can be helpful to spot structured relationships between input variables.
- ---------------------------Type This-----------------------------------
- >>> scatter_matrix(dataset)
- >>> plt.show()
- -----------------------------------------------------------------------
- Note the diagonal grouping of some pairs of attributes. This suggests a high correlation and a predictable relationship.
- ******************* INSERT DIAGRAM SCREENSHOT *******************
- Create a Validation Dataset
- ---------------------------
- We need to know that the model we created is any good.
- Later, we will use statistical methods to estimate the accuracy of the models that we create on unseen data. We also want a more concrete estimate of the accuracy of the best model on unseen data by evaluating it on actual unseen data.
- That is, we are going to hold back some data that the algorithms will not get to see and we will use this data to get a second and independent idea of how accurate the best model might actually be.
- We will split the loaded dataset into two, 80% of which we will use to train our models and 20% that we will hold back as a validation dataset.
- ---------------------------Type This-----------------------------------
- >>> array = dataset.values
- >>> X = array[:,0:4]
- >>> Y = array[:,4]
- >>> validation_size = 0.20
- >>> seed = 7
- >>> X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)
- -----------------------------------------------------------------------
- Test Harness
- ------------
- We will use 10-fold cross validation to estimate accuracy.
- This will split our dataset into 10 parts, train on 9 and test on 1 and repeat for all combinations of train-test splits.
- ---------------------------Type This-----------------------------------
- >>> seed = 7
- >>> scoring = 'accuracy'
- -----------------------------------------------------------------------
- We are using the metric of ‘accuracy‘ to evaluate models.
- This is a ratio of the number of correctly predicted instances in divided by the total number of instances in the dataset multiplied by 100 to give a percentage (e.g. 95% accurate).
- We will be using the scoring variable when we run build and evaluate each model next.
- Build Models
- ------------
- We don’t know which algorithms would be good on this problem or what configurations to use. We get an idea from the plots that some of the classes are partially linearly separable in some dimensions, so we are expecting generally good results.
- Let’s evaluate 6 different algorithms:
- - Logistic Regression (LR)
- - Linear Discriminant Analysis (LDA)
- - K-Nearest Neighbors (KNN).
- - Classification and Regression Trees (CART).
- - Gaussian Naive Bayes (NB).
- - Support Vector Machines (SVM).
- This is a good mixture of simple linear (LR and LDA), nonlinear (KNN, CART, NB and SVM) algorithms. We reset the random number seed before each run to ensure that the evaluation of each algorithm is performed using exactly the same data splits. It ensures the results are directly comparable.
- Let’s build and evaluate our five models:
- -----------------------------------------------------------------------
- # Spot Check Algorithms
- models = []
- models.append(('LR', LogisticRegression()))
- models.append(('LDA', LinearDiscriminantAnalysis()))
- models.append(('KNN', KNeighborsClassifier()))
- models.append(('CART', DecisionTreeClassifier()))
- models.append(('NB', GaussianNB()))
- models.append(('SVM', SVC()))
- # evaluate each model in turn
- results = []
- names = []
- for name, model in models:
- kfold = model_selection.KFold(n_splits=10, random_state=seed)
- cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
- results.append(cv_results)
- names.append(name)
- msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
- print(msg)
- -----------------------------------------------------------------------
- Select Best Model
- -----------------
- We now have 6 models and accuracy estimations for each. We need to compare the models to each other and select the most accurate.
- Running the example above, we get the following raw results:
- ******************* INSERT DIAGRAM SCREENSHOT *******************
- We can see that it looks like KNN has the largest estimated accuracy score.
- We can also create a plot of the model evaluation results and compare the spread and the mean accuracy of each model.
- There is a population of accuracy measures for each algorithm because each algorithm was evaluated 10 times (10 fold cross validation).
- -----------------------------------------------------------------------
- # Compare Algorithms
- fig = plt.figure()
- fig.suptitle('Algorithm Comparison')
- ax = fig.add_subplot(111)
- plt.boxplot(results)
- ax.set_xticklabels(names)
- plt.show()
- -----------------------------------------------------------------------
- You can see that the box and whisker plots are squashed at the top of the range, with many samples achieving 100% accuracy.
- Make Predictions
- ----------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement