Python 机器学习基石 作业2

实现简单的决策树(先找出合适的决策参量,再估计错误率)

import sys
import numpy as np
import math
from random import *

def read_input(path):
    x = []
    y = []
    for line in open(path).readlines():
        items = line.strip().split(' ')
        tmp_x = []
        for i in range(0, len(items)-1):
            tmp_x.append(float(items[i]))
        x.append(tmp_x)
        y.append(float(items[-1]))
    return np.array(x), np.array(y)

def calculate_Ein(x, y):
    thetas = np.array([float("-inf")]+[(x[i]+x[i+1])/2 for i in range(0, x.shape[0]-1)]+[float("inf")])
    target_theta = 0.0
    sign = 1
    Ein = x.shape[0]
    for theta in thetas:
        y_positive = np.where(x>theta, 1, -1)
        y_negative = np.where(x<theta, 1, -1)
        err_positive = sum(y_positive != y)
        err_negative = sum(y_negative != y)
        if err_positive > err_negative:
            if Ein > err_negative:
                Ein = err_negative
                sign = -1
                target_theta = theta
        else:
            if Ein > err_positive:
                Ein = err_positive
                sign = 1
                target_theta = theta
    return Ein, target_theta, sign
        

if __name__ == '__main__':
    x, y = read_input('train.txt')
    x_test, y_test = read_input('test.txt')
    Ein = x.shape[0]
    theta = 0.0
    sign = 1
    index = 0
    for i in range(0, x.shape[1]):
        cur_x = x[:,i]
        cur_data = np.transpose(np.array([cur_x, y]))
        cur_data = cur_data[np.argsort(cur_data[:,0])]
        cur_Ein, cur_theta, cur_sign = calculate_Ein(cur_data[:,0], cur_data[:,1])
        if cur_Ein < Ein:
            Ein = cur_Ein
            theta = cur_theta
            sign = cur_sign
            index = i
    print(Ein/x.shape[0])
    # test
    x_test = x_test[:, index]
    if sign == 1:
        y_predict = np.where(x_test > theta, 1.0, -1.0)
    else:
        y_predict = np.where(x_test < theta, 1.0, -1.0)
    Eout = sum(y_predict != y_test)
    print(Eout/x_test.shape[0])

注意:

  1. python中把数据每一行分开后得到的是一系列字符串,要先把它转化成浮点数再后续计算。
  2. np.array([cur_x, y])两个列向量拼接后得到了两个行向量,要转置变成想要的格式。

references:
http://www.cnblogs.com/xbf9xbf/p/4595990.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2018年4月13日星期五天气小雨 这两天的小雨下的还真是及时,但是也打乱了我的很多计划,比如早上去徒步,晚上去散...
    森琳妈妈阅读 193评论 0 0
  • 夏天,是个很漂亮的女生。 那时还不像现在一样随意的叫女生美女,妹子,女生只是女生。似乎只有这一种称呼。夏天,如同盛...
    是颜夕不是夕颜啦阅读 265评论 0 1
  • 轩妈 20180113 画日记践行 D006 今天是第一次带轩轩去看电影,选的是动画片《寻梦环游记》。去看之前就猜...
    臭臭轩妈阅读 261评论 0 0
  • 自2017年马云首次在云栖大会上提出“新零售”一词,开创了一个零售行业的新热点,拉动着互联网及传统实体经济发生巨变...
    新零售观察者阅读 287评论 0 0