Exercise#1: Decision Tree and support vector machine. Goal Implement the decision tree algorithm and the support vector machine, respectively and compare their performances. Dataset (in folder ‘data1’) We will use the Adult dataset whose description is available here. The training set (adult.data) and evaluation set (adult.test) can be downloaded here. The prediction task is to determine whether a person makes over 50K a year. Preprocessing Remove all the records containing '?' (i.e., missing values). Also, remove the attribute "native-country". you can not use pandas, DecisionTreeClassifier and SVC

时间: 2023-06-17 19:07:10 浏览: 66
Sure, I can help you with that. Let's start by importing the necessary libraries and loading the dataset. ```python import csv import random import math # Load dataset def load_dataset(filename): dataset = [] with open(filename) as file: reader = csv.reader(file) for row in reader: if '?' not in row: dataset.append(row[:-1] + [1 if row[-1].strip() == '>50K' else 0]) return dataset # Split dataset into training and evaluation sets def split_dataset(dataset, split_ratio): train_size = int(len(dataset) * split_ratio) train_set = [] eval_set = list(dataset) while len(train_set) < train_size: index = random.randrange(len(eval_set)) train_set.append(eval_set.pop(index)) return train_set, eval_set dataset = load_dataset('data1/adult.data') train_set, eval_set = split_dataset(dataset, 0.8) ``` Now, let's implement the decision tree algorithm. We will use the ID3 algorithm with entropy as the splitting criterion. ```python # Calculate entropy of a dataset def entropy(dataset): num_records = len(dataset) label_counts = {} for record in dataset: label = record[-1] if label not in label_counts: label_counts[label] = 0 label_counts[label] += 1 entropy = 0.0 for label in label_counts: prob = float(label_counts[label]) / num_records entropy -= prob * math.log2(prob) return entropy # Split dataset based on a given attribute def split_dataset_by_attribute(dataset, attribute_index): splits = {} for record in dataset: attribute_value = record[attribute_index] if attribute_value not in splits: splits[attribute_value] = [] splits[attribute_value].append(record) return splits # Calculate information gain of a dataset after splitting on a given attribute def information_gain(dataset, attribute_index): attribute_values = set([record[attribute_index] for record in dataset]) split_entropies = 0.0 for attribute_value in attribute_values: split = [record for record in dataset if record[attribute_index] == attribute_value] prob = float(len(split)) / len(dataset) split_entropies += prob * entropy(split) return entropy(dataset) - split_entropies # Find the attribute with the highest information gain def find_best_split_attribute(dataset, attribute_indices): best_attribute_index = -1 best_information_gain = -1.0 for attribute_index in attribute_indices: information_gain_val = information_gain(dataset, attribute_index) if information_gain_val > best_information_gain: best_information_gain = information_gain_val best_attribute_index = attribute_index return best_attribute_index # Create a decision tree recursively def create_decision_tree(dataset, attribute_indices): labels = [record[-1] for record in dataset] # If all records have the same label, return a leaf node with that label if len(set(labels)) == 1: return labels[0] # If no attributes are left, return a leaf node with the majority label if len(attribute_indices) == 0: majority_label = max(set(labels), key=labels.count) return majority_label # Otherwise, find the best attribute to split on and create a subtree for each possible value best_attribute_index = find_best_split_attribute(dataset, attribute_indices) best_attribute = attribute_indices[best_attribute_index] tree = {best_attribute: {}} attribute_indices.remove(best_attribute) splits = split_dataset_by_attribute(dataset, best_attribute) for attribute_value in splits: tree[best_attribute][attribute_value] = create_decision_tree(splits[attribute_value], attribute_indices[:]) attribute_indices.insert(best_attribute_index, best_attribute) return tree # Predict the label of a record using a decision tree def predict(tree, record): if isinstance(tree, str): return tree attribute_index = next(iter(tree)) attribute_value = record[attribute_index] if attribute_value not in tree[attribute_index]: return None subtree = tree[attribute_index][attribute_value] return predict(subtree, record) # Calculate accuracy of a decision tree on a dataset def calculate_accuracy(tree, dataset): num_correct = 0 for record in dataset: predicted_label = predict(tree, record) if predicted_label is not None and predicted_label == record[-1]: num_correct += 1 return float(num_correct) / len(dataset) # Test decision tree algorithm attribute_indices = list(range(len(dataset[0]) - 1)) decision_tree = create_decision_tree(train_set, attribute_indices) accuracy = calculate_accuracy(decision_tree, eval_set) print('Accuracy:', accuracy) ``` Finally, let's implement the support vector machine algorithm using the sequential minimal optimization (SMO) algorithm. ```python # Calculate dot product of two vectors def dot_product(x, y): return sum([x[i] * y[i] for i in range(len(x))]) # Calculate magnitude of a vector def magnitude(x): return math.sqrt(dot_product(x, x)) # Calculate distance between two vectors def distance(x, y): return magnitude([x[i] - y[i] for i in range(len(x))]) # Calculate kernel function for two vectors def kernel(x, y, kernel_type='linear', gamma=0.1): if kernel_type == 'linear': return dot_product(x, y) elif kernel_type == 'gaussian': return math.exp(-gamma * distance(x, y)) # Train a support vector machine using the SMO algorithm def train_svm(dataset, kernel_type='linear', C=1.0, max_iterations=100, tolerance=0.01, gamma=0.1): # Initialize alpha vector and bias term num_records = len(dataset) alpha = [0.0] * num_records bias = 0.0 # Initialize kernel matrix kernel_matrix = [[kernel(record1[:-1], record2[:-1], kernel_type, gamma) for record2 in dataset] for record1 in dataset] # Loop until convergence or max_iterations is reached num_iterations = 0 while num_iterations < max_iterations: num_changed_alphas = 0 for i in range(num_records): # Calculate error for record i error_i = sum([alpha[j] * dataset[j][-1] * kernel_matrix[j][i] for j in range(num_records)]) + bias - dataset[i][-1] # Check if alpha i violates KKT conditions if (dataset[i][-1] * error_i < -tolerance and alpha[i] < C) or (dataset[i][-1] * error_i > tolerance and alpha[i] > 0): # Select a second alpha j randomly j = i while j == i: j = random.randrange(num_records) # Calculate error for record j error_j = sum([alpha[k] * dataset[k][-1] * kernel_matrix[k][j] for k in range(num_records)]) + bias - dataset[j][-1] # Save old alpha values alpha_i_old = alpha[i] alpha_j_old = alpha[j] # Calculate L and H bounds for alpha j if dataset[i][-1] != dataset[j][-1]: L = max(0, alpha[j] - alpha[i]) H = min(C, C + alpha[j] - alpha[i]) else: L = max(0, alpha[i] + alpha[j] - C) H = min(C, alpha[i] + alpha[j]) # If L == H, skip this pair of alphas if L == H: continue # Calculate eta (i.e., the second derivative of the objective function) eta = 2 * kernel_matrix[i][j] - kernel_matrix[i][i] - kernel_matrix[j][j] # If eta >= 0, skip this pair of alphas if eta >= 0: continue # Calculate new value for alpha j alpha[j] -= (dataset[j][-1] * (error_i - error_j)) / eta # Clip new value for alpha j to be between L and H alpha[j] = max(L, min(H, alpha[j])) # If alpha j has not changed much, skip this pair of alphas if abs(alpha[j] - alpha_j_old) < tolerance: continue # Calculate new value for alpha i alpha[i] += dataset[i][-1] * dataset[j][-1] * (alpha_j_old - alpha[j]) # Calculate new bias term b1 = bias - error_i - dataset[i][-1] * (alpha[i] - alpha_i_old) * kernel_matrix[i][i] - dataset[j][-1] * (alpha[j] - alpha_j_old) * kernel_matrix[i][j] b2 = bias - error_j - dataset[i][-1] * (alpha[i] - alpha_i_old) * kernel_matrix[i][j] - dataset[j][-1] * (alpha[j] - alpha_j_old) * kernel_matrix[j][j] if 0 < alpha[i] < C: bias = b1 elif 0 < alpha[j] < C: bias = b2 else: bias = (b1 + b2) / 2 num_changed_alphas += 1 # If no alphas were changed in this iteration, increment counter if num_changed_alphas == 0: num_iterations += 1 else: num_iterations = 0 # Select support vectors (i.e., non-zero alphas) support_vectors = [] support_vector_labels = [] for i in range(num_records): if alpha[i] > 0: support_vectors.append(dataset[i][:-1]) support_vector_labels.append(dataset[i][-1]) # Return support vectors, support vector labels, and bias term return support_vectors, support_vector_labels, bias # Predict the label of a record using a support vector machine def predict_svm(support_vectors, support_vector_labels, bias, record, kernel_type='linear', gamma=0.1): predicted_label = None for i in range(len(support_vectors)): kernel_val = kernel(support_vectors[i], record, kernel_type, gamma) predicted_label += support_vector_labels[i] * kernel_val predicted_label += bias return 1 if predicted_label > 0 else 0 # Calculate accuracy of a support vector machine on a dataset def calculate_accuracy_svm(support_vectors, support_vector_labels, bias, dataset, kernel_type='linear', gamma=0.1): num_correct = 0 for record in dataset: predicted_label = predict_svm(support_vectors, support_vector_labels, bias, record[:-1], kernel_type, gamma) if predicted_label is not None and predicted_label == record[-1]: num_correct += 1 return float(num_correct) / len(dataset) # Test support vector machine algorithm support_vectors, support_vector_labels, bias = train_svm(train_set, 'linear', 1.0, 100, 0.01, 0.1) accuracy = calculate_accuracy_svm(support_vectors, support_vector_labels, bias, eval_set, 'linear', 0.1) print('Accuracy:', accuracy) ``` You can now compare the performances of the decision tree and support vector machine algorithms on the Adult dataset.

相关推荐

import numpy as np def sigmoid(x): # the sigmoid function return 1/(1+np.exp(-x)) class LogisticReg(object): def __init__(self, indim=1): # initialize the parameters with all zeros # w: shape of [d+1, 1] self.w = np.zeros((indim + 1, 1)) def set_param(self, weights, bias): # helper function to set the parameters # NOTE: you need to implement this to pass the autograde. # weights: vector of shape [d, ] # bias: scaler def get_param(self): # helper function to return the parameters # NOTE: you need to implement this to pass the autograde. # returns: # weights: vector of shape [d, ] # bias: scaler def compute_loss(self, X, t): # compute the loss # X: feature matrix of shape [N, d] # t: input label of shape [N, ] # NOTE: return the average of the log-likelihood, NOT the sum. # extend the input matrix # compute the loss and return the loss X_ext = np.concatenate((X, np.ones((X.shape[0], 1))), axis=1) # compute the log-likelihood def compute_grad(self, X, t): # X: feature matrix of shape [N, d] # grad: shape of [d, 1] # NOTE: return the average gradient, NOT the sum. def update(self, grad, lr=0.001): # update the weights # by the gradient descent rule def fit(self, X, t, lr=0.001, max_iters=1000, eps=1e-7): # implement the .fit() using the gradient descent method. # args: # X: input feature matrix of shape [N, d] # t: input label of shape [N, ] # lr: learning rate # max_iters: maximum number of iterations # eps: tolerance of the loss difference # TO NOTE: # extend the input features before fitting to it. # return the weight matrix of shape [indim+1, 1] def predict_prob(self, X): # implement the .predict_prob() using the parameters learned by .fit() # X: input feature matrix of shape [N, d] # NOTE: make sure you extend the feature matrix first, # the same way as what you did in .fit() method. # returns the prediction (likelihood) of shape [N, ] def predict(self, X, threshold=0.5): # implement the .predict() using the .predict_prob() method # X: input feature matrix of shape [N, d] # returns the prediction of shape [N, ], where each element is -1 or 1. # if the probability p>threshold, we determine t=1, otherwise t=-1

最新推荐

recommend-type

node-v9.6.0-x86.msi

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

Python基于机器学习的分布式系统故障诊断系统源代码,分布式系统的故障数据进行分析,设计故障诊断模型,高效地分析并识别故障类别

基于技术手段(包括但不限于机器学习、深度学习等技术)对分布式系统的故障数据进行分析,设计故障诊断模型,高效地分析并识别故障类别,实现分布式系统故障运维的智能化,快速恢复故障的同时大大降低分布式系统运维工作的难度,减少运维对人力资源的消耗。在分布式系统中某个节点发生故障时,故障会沿着分布式系统的拓扑结构进行传播,造成自身节点及其邻接节点相关的KPI指标和发生大量日志异常
recommend-type

JavaScript前端开发的核心语言前端开发的核心语言

javascript 当今互联网时代,JavaScript已经成为了前端开发的核心语言它是一种高级程序设计语言,通常用于网页的交互和动态效果的实现。JavaScript的灵活性以及广泛的使用使得它变得异常重要,能够为用户带来更好的用户体验。 JavaScript的特点之一是它的轻量级,它可以在网页中运行无需单独的编译或下载。这意味着网页可以更快地加载并且用户无需安装额外的软件才能运行网页上的JavaScript代码。此外,与HTML和CSS紧密结合,可以直接在HTML文档中嵌入,使得网页的开发变得非常便捷。 JavaScript具有动态性,它可以在浏览器中实时修改页面内容和样。它可以通过操作DOM(文档对象模型来动态地修改网页的结构和布局,并且可以根据用户的行为实时地响应各种事件,如点击、标悬停、滚动等。这使得开发者可以轻松地为网页添加交互性和动态效果,提供更好的用户体验。 JavaScript也是一种面向对象的语言。它支持对象、类、继承、多态等面向对象编程的概念,使得代码结构更加清晰和可维护。开发者可以创建自定义的对象和方法,对功能进行封装和复用,提高代码的可读性和可维护性。
recommend-type

RTL8188FU-Linux-v5.7.4.2-36687.20200602.tar(20765).gz

REALTEK 8188FTV 8188eus 8188etv linux驱动程序稳定版本, 支持AP,STA 以及AP+STA 共存模式。 稳定支持linux4.0以上内核。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

Redis验证与连接:快速连接Redis服务器指南

![Redis验证与连接:快速连接Redis服务器指南](https://img-blog.csdnimg.cn/20200905155530592.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzNTg5NTEw,size_16,color_FFFFFF,t_70) # 1. Redis验证与连接概述 Redis是一个开源的、内存中的数据结构存储系统,它使用键值对来存储数据。为了确保数据的安全和完整性,Redis提供了多
recommend-type

gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker app:app 报错 ModuleNotFoundError: No module named 'geventwebsocket' ]

这个报错是因为在你的环境中没有安装 `geventwebsocket` 模块,可以使用下面的命令来安装: ``` pip install gevent-websocket ``` 安装完成后再次运行 `gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker app:app` 就不会出现这个报错了。
recommend-type

c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf

校园超市商品信息管理系统课程设计旨在帮助学生深入理解程序设计的基础知识,同时锻炼他们的实际操作能力。通过设计和实现一个校园超市商品信息管理系统,学生掌握了如何利用计算机科学与技术知识解决实际问题的能力。在课程设计过程中,学生需要对超市商品和销售员的关系进行有效管理,使系统功能更全面、实用,从而提高用户体验和便利性。 学生在课程设计过程中展现了积极的学习态度和纪律,没有缺勤情况,演示过程流畅且作品具有很强的使用价值。设计报告完整详细,展现了对问题的深入思考和解决能力。在答辩环节中,学生能够自信地回答问题,展示出扎实的专业知识和逻辑思维能力。教师对学生的表现予以肯定,认为学生在课程设计中表现出色,值得称赞。 整个课程设计过程包括平时成绩、报告成绩和演示与答辩成绩三个部分,其中平时表现占比20%,报告成绩占比40%,演示与答辩成绩占比40%。通过这三个部分的综合评定,最终为学生总成绩提供参考。总评分以百分制计算,全面评估学生在课程设计中的各项表现,最终为学生提供综合评价和反馈意见。 通过校园超市商品信息管理系统课程设计,学生不仅提升了对程序设计基础知识的理解与应用能力,同时也增强了团队协作和沟通能力。这一过程旨在培养学生综合运用技术解决问题的能力,为其未来的专业发展打下坚实基础。学生在进行校园超市商品信息管理系统课程设计过程中,不仅获得了理论知识的提升,同时也锻炼了实践能力和创新思维,为其未来的职业发展奠定了坚实基础。 校园超市商品信息管理系统课程设计的目的在于促进学生对程序设计基础知识的深入理解与掌握,同时培养学生解决实际问题的能力。通过对系统功能和用户需求的全面考量,学生设计了一个实用、高效的校园超市商品信息管理系统,为用户提供了更便捷、更高效的管理和使用体验。 综上所述,校园超市商品信息管理系统课程设计是一项旨在提升学生综合能力和实践技能的重要教学活动。通过此次设计,学生不仅深化了对程序设计基础知识的理解,还培养了解决实际问题的能力和团队合作精神。这一过程将为学生未来的专业发展提供坚实基础,使其在实际工作中能够胜任更多挑战。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

Redis配置文件解读:实例解析redis.windows.conf

![Redis配置文件解读:实例解析redis.windows.conf](https://img-blog.csdn.net/20180726010513323?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3lhbmc1NzI2Njg1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) # 1. Redis配置文件概述 Redis配置文件是Redis服务器运行的配置文件,它包含了Redis服务器的各种配置参数。通过修改Redis配置文件,我们可以对Redis服务器的运行行为进行