Advertisement
joemccray

Python Big Data

Jun 6th, 2017
879
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.20 KB | None | 0 0
  1. Reference:
  2. http://machinelearningmastery.com/machine-learning-in-python-step-by-step/
  3.  
  4.  
  5. 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
  6.  
  7.  
  8.  
  9. vi libcheck.py
  10.  
  11. ----------------------------------------------------------
  12. #!/usr/bin/env python
  13.  
  14. # Check the versions of libraries
  15.  
  16. # Python version
  17. import sys
  18. print('Python: {}'.format(sys.version))
  19. # scipy
  20. import scipy
  21. print('scipy: {}'.format(scipy.__version__))
  22. # numpy
  23. import numpy
  24. print('numpy: {}'.format(numpy.__version__))
  25. # matplotlib
  26. import matplotlib
  27. print('matplotlib: {}'.format(matplotlib.__version__))
  28. # pandas
  29. import pandas
  30. print('pandas: {}'.format(pandas.__version__))
  31. # scikit-learn
  32. import sklearn
  33. print('sklearn: {}'.format(sklearn.__version__))
  34. ----------------------------------------------------------
  35.  
  36.  
  37.  
  38.  
  39. python
  40.  
  41. import pandas csv
  42. from pandas.tools.plotting import scatter_matrix
  43. import matplotlib.pyplot as plt
  44. from sklearn import model_selection
  45. from sklearn.metrics import classification_report
  46. from sklearn.metrics import confusion_matrix
  47. from sklearn.metrics import accuracy_score
  48. from sklearn.linear_model import LogisticRegression
  49. from sklearn.tree import DecisionTreeClassifier
  50. from sklearn.neighbors import KNeighborsClassifier
  51. from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
  52. from sklearn.naive_bayes import GaussianNB
  53. from sklearn.svm import SVC
  54.  
  55.  
  56.  
  57.  
  58.  
  59. url = "https://s3.amazonaws.com/infosecaddictsfiles/sampleSubmission.csv"
  60. names = ["Id", "Prediction1", "Prediction2", "Prediction3", "Prediction4", "Prediction5", "Prediction6", "Prediction7", "Prediction8", "Prediction9"]
  61. dataset = pandas.read_csv(url, names=names)
  62.  
  63.  
  64.  
  65.  
  66. Summarize the Dataset
  67. ---------------------
  68. We can get a quick idea of how many instances (rows) and how many attributes (columns) the data contains with the shape property.
  69.  
  70. >>> print(dataset.shape)
  71.  
  72.  
  73.  
  74.  
  75. >>> print(dataset.head(20))
  76.  
  77. You should see the first 20 rows of the data:
  78.  
  79.  
  80.  
  81.  
  82.  
  83. Statistical Summary
  84. -------------------
  85.  
  86. Now we can take a look at a summary of each attribute.
  87.  
  88. This includes the count, mean, the min and max values as well as some percentiles.
  89.  
  90. >>> print(dataset.describe())
  91.  
  92.  
  93.  
  94.  
  95.  
  96. Class Distribution
  97. ------------------
  98. 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.
  99.  
  100. >>> print(dataset.groupby('class').size())
  101.  
  102. We can see that each class has the same number of instances
  103.  
  104.  
  105.  
  106.  
  107. Data Visualization
  108. ------------------
  109.  
  110. We now have a basic idea about the data. We need to extend that with some visualizations.
  111.  
  112. We are going to look at two types of plots:
  113.  
  114. - Univariate plots to better understand each attribute.
  115. - Multivariate plots to better understand the relationships between attributes.
  116.  
  117.  
  118. Univariate Plots
  119.  
  120. We start with some univariate plots, that is, plots of each individual variable.
  121.  
  122. Given that the input variables are numeric, we can create box and whisker plots of each.
  123.  
  124. >>> dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)
  125. >>> plt.show()
  126.  
  127. This gives us a much clearer idea of the distribution of the input attributes:
  128.  
  129.  
  130.  
  131. ******************* INSERT DIAGRAM SCREENSHOT *******************
  132.  
  133.  
  134.  
  135. We can also create a histogram of each input variable to get an idea of the distribution.
  136.  
  137.  
  138. >>> dataset.hist()
  139. >>> plt.show()
  140.  
  141. 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.
  142.  
  143.  
  144. ******************* INSERT DIAGRAM SCREENSHOT *******************
  145.  
  146.  
  147.  
  148.  
  149. Multivariate Plots
  150. ------------------
  151. Now we can look at the interactions between the variables.
  152.  
  153. First let’s look at scatterplots of all pairs of attributes. This can be helpful to spot structured relationships between input variables.
  154.  
  155.  
  156. >>> scatter_matrix(dataset)
  157. >>> plt.show()
  158.  
  159. Note the diagonal grouping of some pairs of attributes. This suggests a high correlation and a predictable relationship.
  160.  
  161. ******************* INSERT DIAGRAM SCREENSHOT *******************
  162.  
  163.  
  164.  
  165.  
  166. Create a Validation Dataset
  167. ---------------------------
  168.  
  169. We need to know that the model we created is any good.
  170.  
  171. 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.
  172.  
  173. 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.
  174.  
  175. 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.
  176.  
  177.  
  178. >>> array = dataset.values
  179. >>> X = array[:,0:4]
  180. >>> Y = array[:,4]
  181. >>> validation_size = 0.20
  182. >>> seed = 7
  183. >>> X_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)
  184.  
  185.  
  186.  
  187. Test Harness
  188. ------------
  189. We will use 10-fold cross validation to estimate accuracy.
  190.  
  191. This will split our dataset into 10 parts, train on 9 and test on 1 and repeat for all combinations of train-test splits.
  192.  
  193.  
  194. >>> seed = 7
  195. >>> scoring = 'accuracy'
  196.  
  197. We are using the metric of ‘accuracy‘ to evaluate models.
  198. 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).
  199. We will be using the scoring variable when we run build and evaluate each model next.
  200.  
  201.  
  202.  
  203.  
  204. Build Models
  205. ------------
  206. 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.
  207.  
  208. Let’s evaluate 6 different algorithms:
  209.  
  210. - Logistic Regression (LR)
  211. - Linear Discriminant Analysis (LDA)
  212. - K-Nearest Neighbors (KNN).
  213. - Classification and Regression Trees (CART).
  214. - Gaussian Naive Bayes (NB).
  215. - Support Vector Machines (SVM).
  216.  
  217. 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.
  218.  
  219. Let’s build and evaluate our five models:
  220.  
  221.  
  222.  
  223. # Spot Check Algorithms
  224. models = []
  225. models.append(('LR', LogisticRegression()))
  226. models.append(('LDA', LinearDiscriminantAnalysis()))
  227. models.append(('KNN', KNeighborsClassifier()))
  228. models.append(('CART', DecisionTreeClassifier()))
  229. models.append(('NB', GaussianNB()))
  230. models.append(('SVM', SVC()))
  231. # evaluate each model in turn
  232. results = []
  233. names = []
  234. for name, model in models:
  235. kfold = model_selection.KFold(n_splits=10, random_state=seed)
  236. cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
  237. results.append(cv_results)
  238. names.append(name)
  239. msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
  240. print(msg)
  241.  
  242.  
  243.  
  244.  
  245. Select Best Model
  246. -----------------
  247. We now have 6 models and accuracy estimations for each. We need to compare the models to each other and select the most accurate.
  248.  
  249. Running the example above, we get the following raw results:
  250.  
  251.  
  252. ******************* INSERT DIAGRAM SCREENSHOT *******************
  253.  
  254.  
  255. We can see that it looks like KNN has the largest estimated accuracy score.
  256.  
  257. We can also create a plot of the model evaluation results and compare the spread and the mean accuracy of each model.
  258. There is a population of accuracy measures for each algorithm because each algorithm was evaluated 10 times (10 fold cross validation).
  259.  
  260.  
  261.  
  262. # Compare Algorithms
  263. fig = plt.figure()
  264. fig.suptitle('Algorithm Comparison')
  265. ax = fig.add_subplot(111)
  266. plt.boxplot(results)
  267. ax.set_xticklabels(names)
  268. plt.show()
  269.  
  270. You can see that the box and whisker plots are squashed at the top of the range, with many samples achieving 100% accuracy.
  271.  
  272.  
  273. Make Predictions
  274. ----------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement