Machine Learning No.2

Task - handwriting KNN classification algorithm

1. Import data set

When the saw guide to find information iris data sets may also be directly used in the machine learning packages Python scikit-learn directly introduced.

from sklearn.datasets Import load_iris 
data = load_iris ()
 Print (the dir (data))   # view data has property or method 
Print (data.DESCR)   # view profile data set 

Import pandas PD AS
 # read directly the data pandas box 
pd.DataFrame (data = data.data, columns = data.feature_names)
['DESCR', 'data', 'feature_names', 'filename', 'target', 'target_names']
.. _iris_dataset:

Iris plants dataset
--------------------

**Data Set Characteristics:**

    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
                
    :Summary Statistics:

    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)
    ============== ==== ==== ======= ===== ====================

    :Missing Attribute Values: None
    :Class Distribution: 33.3% for each of 3 classes.
    :Creator: R.A. Fisher
    :Donor: Michael Marshall (MARSHALL%[email protected])
    :Date: July, 1988

The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.

This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.

.. topic:: References

   - Fisher, R.A. "The use of multiple measurements in taxonomic problems"
     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
     Mathematical Statistics" (John Wiley, NY, 1950).
   - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.
     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
     Structure and Classification Rule for Recognition in Partially Exposed
     Environments".  IEEE Transactions on Pattern Analysis and Machine
     Intelligence, Vol. PAMI-2, No. 1, 67-71.
   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions
     on Information Theory, May 1972, 431-433.
   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II
     conceptual clustering system finds 3 classes in the data.
   - Many, many more ...

 

Reference: https: //scikit-learn.org/stable/datasets/index.html#iris-plants-database

2. To find the distance function is defined

Calculated Euclidean distance to get a good, square directly according to the formula first differencing and then prescribing.

def euc_dis(instance1, instance2):
    diff = instance1 - instance2
    diff = diff**2
    dist = sum(diff)**0.5
    return dist

 

3. Define KNN classification function

DEF knn_classify (X, Y, testInstance, K): 
    DIS = []
     for I in X: 
        dis.append (euc_dis (I, testInstance)) # between each vector X and testInstance call Euclidean distance function to calculate Solving Euclidean distance 
    maxIndex = Map (dis.index, heapq.nsmallest (K, DIS)) # obtains the K subscript minimum distance 
    maxY = []
     for I in maxIndex: 
        maxY.append (Y [I]) # the sample is added to the corresponding tag array maxY 
    return max (maxY, Key = maxY.count) # largest number of occurrences tag value

This function is based on the principle of KNN algorithm to write, first in an array are calculated after which all distances, ordering, returns the highest number of minimum distance index appears.

Heap sort used here (also the first contact heap sort function usage inside the python), the minimum range value acquired stack using the code in the title heapq.nsmallest (), the maximum range can be used heapq.nlargest ()

About library module heapq:

(1) Creating the heap

Can use an empty list, then heapq.heappush () function is added to the value of the stack, may be used heap.heapify (list) becomes a stack structure conversion list.

(2) Method

In addition to heapq.nsmallest () and heapq.nlargest () as well.

 

heapq.heappop (): the minimum value of the pop heap.

heapq.heaprepalce(): Remove the smallest element of the heap and add an element.

Wait...

(Find time to knock it better, then you can look at what other sort)

4. Prediction Results

predictions = [knn_classify(X_train,y_train,data,3) for data in X_test]
correct = np.count_nonzero((predictions == y_test)== True)
print("Accuracy is %.3f" %(correct/len(X_test)))

5. Experience

KNN algorithm is regarded as a relatively simple algorithm, the process is easy to understand, beating achieve.

Every task will be a little bit rich had no contact with his past or vague knowledge, or should practice more, new knowledge are found in every knock again to understand it, and then step by step to expand.

 

Guess you like

Origin www.cnblogs.com/Ygrittee/p/11918019.html