1. K-Nearest Neighbor Algorithm
Algorithm principle:
There is a sample dataset (training sample set), and we know the correspondence between each data in the sample set and its category. After inputting data of unknown categories, each feature of the new data is compared with the feature corresponding to the data in the sample set. Then, the algorithm extracts K groups of data with the most similar features (nearest neighbor) in the sample set. Then, the K-group data contains the most frequent categories as the new data category.
Algorithm steps:
- Calculate the distance between each vertex in a dataset of known classes and the current vertex. (Similarity measurement)
- Sort by ascending distance
- Select K points with the minimum distance from the current point
- Determine the frequency of occurrence of the category of K points
- The category with the highest return frequency is the category of the current vertex.
Python code implementation:
def classify0(inX, dataSet, labels, k): dataSetSize = dataSet.shape[0] diffMat = tile(inX, (dataSetSize,1)) - dataSet #当前点的值矩阵(列表复制成矩阵)与训练样本集特征值矩阵差 sqDiffMat = diffMat**2 sqDistances = sqDiffMat.sum(axis=1) #将矩阵列的值相加 distances = sqDistances**0.5 sortedDistIndicies = distances.argsort() classCount={} for i in range(k): voteIlabel = labels[sortedDistIndicies[i]] classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0]
Input:
inX:当前点的特征值列表 dataSet、label:训练集的特征值矩阵及分类值 k:kNN算法k的取值
Output:
sortedClassCount[0][0]:k组数据中出现频率最高的分类sortedClassCount 是一个字典,存储的是k组数据中各个分类对应的出现次数
2. Decision Tree (ID3)
Principle:
Which feature is selected on the current dataset to classify data. Raw data is divided into several data subsets, which are distributed across all branches of the Decision Point. If the data under the branch belongs to the same type, no further data division is required. Otherwise, you need to repeat the data subset process. (Recursion)
End condition: the program traverses the mathematics of all partitioned datasets, or all instances under each branch have the same classification (to obtain the leaf node or terminate the block ).
Data Division data based on features: disordered data is more ordered.
One way to organize disorganized data is to use information theory to measure information. (Entropy)
Information Gain: information changes before and after the dataset is divided. The best choice is the feature with the highest information gain.
Entropy: H =-Σ pI * log2pi
Note: Another another method to measure the degree of disorder is the Gini purity (Gini impurity ).
Python code calculates the entropy of a dataset:
def calcShannonEnt(dataSet): numEntries = len(dataSet) labelCounts = {} for featVec in dataSet: #the the number of unique elements and their occurance currentLabel = featVec[-1] if currentLabel not in labelCounts.keys(): labelCounts[currentLabel] = 0 labelCounts[currentLabel] += 1 shannonEnt = 0.0 for key in labelCounts: prob = float(labelCounts[key])/numEntries shannonEnt -= prob * log(prob,2) #log base 2 return shannonEnt
Obtain the best dataset partitioning method:
def splitDataSet(dataSet, axis, value): #根据给定特征及其值来划分数据 retDataSet = [] for featVec in dataSet: if featVec[axis] == value: reducedFeatVec = featVec[:axis] #chop out axis used for splitting reducedFeatVec.extend(featVec[axis+1:]) retDataSet.append(reducedFeatVec) return retDataSet def chooseBestFeatureToSplit(dataSet): numFeatures = len(dataSet[0]) - 1 #the last column is used for the labels baseEntropy = calcShannonEnt(dataSet) bestInfoGain = 0.0; bestFeature = -1 for i in range(numFeatures): #iterate over all the features featList = [example[i] for example in dataSet]#create a list of all the examples of this feature uniqueVals = set(featList) #get a set of unique values newEntropy = 0.0 for value in uniqueVals: subDataSet = splitDataSet(dataSet, i, value) prob = len(subDataSet)/float(len(dataSet)) newEntropy += prob * calcShannonEnt(subDataSet) infoGain = baseEntropy - newEntropy #calculate the info gain; ie reduction in entropy if (infoGain > bestInfoGain): #compare this to the best gain so far bestInfoGain = infoGain #if better than current best, set to best bestFeature = i return bestFeature #returns an integer
Recursive decision tree construction
def majorityCnt(classList): classCount={} for vote in classList: if vote not in classCount.keys(): classCount[vote] = 0 classCount[vote] += 1 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) return sortedClassCount[0][0]def createTree(dataSet,labels): classList = [example[-1] for example in dataSet] if classList.count(classList[0]) == len(classList): return classList[0]#stop splitting when all of the classes are equal if len(dataSet[0]) == 1: #stop splitting when there are no more features in dataSet return majorityCnt(classList)
bestFeat = chooseBestFeatureToSplit(dataSet) bestFeatLabel = labels[bestFeat] myTree = {bestFeatLabel:{}} del(labels[bestFeat]) featValues = [example[bestFeat] for example in dataSet] uniqueVals = set(featValues) for value in uniqueVals: subLabels = labels[:] #copy all of labels, so trees don‘t mess up existing labels myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),subLabels) return myTree
2014-10-12
The content of this article complies with the cc3.0 copyright agreement. For more information, please note: transfer from an excellent student to an excellent student.
Link: machine learning practice learning notes (1)
Machine Learning Practice Study Notes (1)