用python训练机器学习

//样本数据
编号,色泽,根蒂,敲声,纹理,脐部,触感,密度,含糖率,好瓜  
1,青绿,蜷缩,浊响,清晰,凹陷,硬滑,0.697,0.46,是  
2,乌黑,蜷缩,沉闷,清晰,凹陷,硬滑,0.774,0.376,是  
3,乌黑,蜷缩,浊响,清晰,凹陷,硬滑,0.634,0.264,是  
4,青绿,蜷缩,沉闷,清晰,凹陷,硬滑,0.608,0.318,是  
5,浅白,蜷缩,浊响,清晰,凹陷,硬滑,0.556,0.215,是  
6,青绿,稍蜷,浊响,清晰,稍凹,软粘,0.403,0.237,是  
7,乌黑,稍蜷,浊响,稍糊,稍凹,软粘,0.481,0.149,是  
8,乌黑,稍蜷,浊响,清晰,稍凹,硬滑,0.437,0.211,是  
9,乌黑,稍蜷,沉闷,稍糊,稍凹,硬滑,0.666,0.091,否  
10,青绿,硬挺,清脆,清晰,平坦,软粘,0.243,0.267,否  
11,浅白,硬挺,清脆,模糊,平坦,硬滑,0.245,0.057,否  
12,浅白,蜷缩,浊响,模糊,平坦,软粘,0.343,0.099,否  
13,青绿,稍蜷,浊响,稍糊,凹陷,硬滑,0.639,0.161,否  
14,浅白,稍蜷,沉闷,稍糊,凹陷,硬滑,0.657,0.198,否  
15,乌黑,稍蜷,浊响,清晰,稍凹,软粘,0.36,0.37,否  
16,浅白,蜷缩,浊响,模糊,平坦,硬滑,0.593,0.042,否  
17,青绿,蜷缩,沉闷,稍糊,稍凹,硬滑,0.719,0.103,否  

  

#前期整理
# -*- coding: utf-8 -*-
from itertools import islice


def test():
    values = {
        'color': {
            '青绿': 1,
            '乌黑': 2,
            '浅白': 3
        },
        'root': {
            '蜷缩': 1,
            '稍蜷': 2,
            '硬挺': 3
        },
        'sound': {
            '浊响': 1,
            '沉闷': 2,
            '清脆': 3
        },
        'strip': {
            '清晰': 1,
            '稍糊': 2,
            '模糊': 3
        },
        'texture': {
            '凹陷': 1,
            '稍凹': 2,
            '平坦': 3
        },
        'feel': {
            '硬滑': 1,
            '软粘': 2
        },
        u'label': {
            '是': 1,
            '否': -1
        }
    }
    fileread = file('d://a/xigua.txt', 'r', -1)
    biaotou = fileread.readline().strip('\n').strip(" ").split(",")
    biaotouc = biaotou[1:7] + [biaotou[-1].strip('\n').strip(" ")]
    biaotouEn = ['color', 'root', 'sound', 'strip', 'texture', 'feel', 'label']
    biaotouDict = {}
    for index in range(len(biaotouEn)):
        biaotouDict[biaotouc[index]] = biaotouEn[index]
    res = []
    for eachLine in fileread.readlines():
        eachLineArray = eachLine.split(',')
        reselem = []
        for elemIndex in range(len(eachLineArray)):
            eachLineArrayElemIndexOp=eachLineArray[elemIndex].strip('\n').strip(" ")
            if (biaotouDict.has_key(biaotou[elemIndex])):
                reselem.append(values[biaotouDict[biaotou[elemIndex]]][eachLineArrayElemIndexOp])
            else:
                reselem.append(float(eachLineArrayElemIndexOp))
        res.append(reselem)
    print res
if __name__ == '__main__':
    test()

  

posted @ 2017-03-27 09:20  饮马天涯  阅读(221)  评论(0编辑  收藏  举报