机器学习 学习

前置函数

numpy.shape[0] 为第一维长度(行长度),numpy.shape[1]为第二维长度(列长度)

array= numpy.array([[1,3,4],[1,45,6]])
print(array)
print(array.shape)
[[ 1  3  4]
 [ 1 45  6]]
(2, 3)

2.numpy.tile

原型:numpy.tile(A,reps)

tile共有2个参数,A指待输入数组,reps则决定A重复的次数。整个函数用于重复数组A来构建新的数组。

参数(1,2) 1是重复行 2是重复列

array= numpy.array([[1,3,4],[1,45,6]])
a= numpy.tile(array,(2,2))
print(a)
[[ 1  3  4  1  3  4]
 [ 1 45  6  1 45  6]
 [ 1  3  4  1  3  4]
 [ 1 45  6  1 45  6]]
  1. sum(axis=1) axis = 0: 按列计算,axis = 1: 按行计算
array= numpy.array([[1,3,4],[1,45,6]])

b=array.sum(axis=1)
print(b)
[ 8 52]
array= numpy.array([[1,3,4],[1,45,6]])

b=array.sum(axis=0)
print(b)
[ 2 48 10]

numpy.argsort()

argsort函数返回的是数组值从小到大的索引值

参数axis=1按行排序 axis=0按列排序

#按行
array= numpy.array([[1,3,4],[1,45,6]])

print(array.argsort(axis=1))

#[[0 1 2]
 [0 2 1]]
#按列
array= numpy.array([[1,3,4],[1,45,6]])

print(array.argsort(axis=0))
#[[0 0 0]
 [1 1 1]]

给一维数组排序

array2=numpy.array([1,3,3,2,55,4])

a=numpy.argsort(-array2)
print(a)
#[4 5 1 2 3 0]

返回的还是索引值

举个简单的例子,我们可以使用k-近邻算法分类一个电影是爱情片还是动作片。

函数代码

import numpy
import gmpy2

def createData():
    data=numpy.array([[2,104],[5,85],[108,5],[115,8]])
    labels =['爱情片','爱情片','动作片','动作片']
    return data,labels


def classify(inX,dataSet,labels,k):
    #inX 测试集 dataSet 训练集 上面group 上面labels k 选择距离最小的k个点
    dataSetSize=dataSet.shape[0]  #c.shape[0] 为第一维的长度,c.shape[1] 为第二维的长度。

    sub_data= numpy.tile(inX,(dataSetSize,1))-dataSet  #将第一行复制dataSetSize 到多行,列也是这里是1 不复制
    pow_data =sub_data**2
    print(pow_data)

    line_add = pow_data.sum(axis=1) #行相加

    distances = line_add ** 0.5
    #print(distances)
    sortedDistIndices = distances.argsort()
    sortedDistIndices=numpy.argsort(-sortedDistIndices)
    print(sortedDistIndices)
    dict_count = {
     }
    for i in range(k):
        # 取出前k个元素的类别
        voteIlabel = labels[sortedDistIndices[i]]

        dict_count[voteIlabel] = dict_count.get(voteIlabel, 0) + 1
    print(dict_count)

    sortedClassCount = sorted(dict_count.items(), key=lambda x:x[1], reverse=True)
    return sortedClassCount


if __name__ == '__main__':
    text=[101,20] #训练集
    dataSet,labels=createData()
    print(classify(text,dataSet,labels,3))


你可能感兴趣的:(机器学习,python,算法)