台大林轩田《机器学习基石》:作业三python实现

article/2025/11/7 0:24:23

台大林轩田《机器学习基石》:作业一python实现
台大林轩田《机器学习基石》:作业二python实现
台大林轩田《机器学习基石》:作业三python实现
台大林轩田《机器学习基石》:作业四python实现

完整代码:
https://github.com/xjwhhh/LearningML/tree/master/MLFoundation
欢迎follow和star

在学习和总结的过程中参考了不少别的博文,且自己的水平有限,如果有错,希望能指出,共同学习,共同进步

##13

13题题目描述

给定target function,我们的工作是在X=[-1,1]x[-1,1]上随机产生1000个点,利用f(x1,x2)计算它的值,然后在基础上添加10%的噪声(二元分类的噪声就是把10%的样本的y值取相反数)。如果不做feacher transform 直接利用数据做线性回归,利用得到的参数做线性分类器,问此时得到的Ein是多少。运行1000次取平均值。

步骤:
1.随机产生训练样本并添加噪声
2.利用训练样本进行线性回归
3.用得到的线性回归参数w作为二元分类器的参数,计算sign(w*x)得到预测值,计算他与y的0/1错误,得到错误率E_in

代码如下:

import random
import numpy as np# target function f(x1, x2) = sign(x1^2 + x2^2 - 0.6)
def target_function(x1, x2):if (x1 * x1 + x2 * x2 - 0.6) >= 0:return 1else:return -1# create train_set
def training_data_with_random_error(num=1000):features = np.zeros((num, 3))labels = np.zeros((num, 1))points_x1 = np.array([round(random.uniform(-1, 1), 2) for i in range(num)])points_x2 = np.array([round(random.uniform(-1, 1), 2) for i in range(num)])for i in range(num):# create random featurefeatures[i, 0] = 1features[i, 1] = points_x1[i]features[i, 2] = points_x2[i]labels[i] = target_function(points_x1[i], points_x2[i])# choose 10% error labelsif i <= num * 0.1:if labels[i] < 0:labels[i] = 1else:labels[i] = -1return features, labelsdef error_rate(features, labels, w):wrong = 0for i in range(len(labels)):if np.dot(features[i], w) * labels[i, 0] < 0:wrong += 1return wrong / (len(labels) * 1.0)def linear_regression_closed_form(X, Y):"""linear regression:model     : g(x) = Wt * Xstrategy  : squared erroralgorithm : close form(matrix)result    : w = (Xt.X)^-1.Xt.Y林老师上课讲的公式"""return np.linalg.inv(np.dot(X.T, X)).dot(X.T).dot(Y)if __name__ == '__main__':# 13error_rate_array = []for i in range(1000):(features, labels) = training_data_with_random_error(1000)w13 = linear_regression_closed_form(features, labels)error_rate_array.append(error_rate(features, labels, w13))# error rate, approximately 0.5avr_err = sum(error_rate_array) / (len(error_rate_array) * 1.0)print("13--Linear regression for classification without feature transform:Average error--", avr_err)

运行结果是0.5079380000000009

##14

14题题目描述

在第13题,直接利用逻辑回归做分类是很不理想的,错误率为50%,没有实际意义。但是我们可以先进行特征转换,正确率就会高很多。我们要将特征转换到如题所示

与13题的不同在于多了一个feature_transform(features)方法,在1000次计算中比较得到最好的w

def feature_transform(features):new = np.zeros((len(features), 6))new[:, 0:3] = features[:, :] * 1new[:, 3] = features[:, 1] * features[:, 2]new[:, 4] = features[:, 1] * features[:, 1]new[:, 5] = features[:, 2] * features[:, 2]return new

main方法变为:

# 14
(features, labels) = training_data_with_random_error(1000)
new_features = feature_transform(features)
w14 = linear_regression_closed_form(new_features, labels)
min_error_in = float("inf")
# print(w14)
# plot_dot_pictures(features, labels, w)
error_rate_array = []
for i in range(1000):(features, labels) = training_data_with_random_error(1000)new_features = feature_transform(features)w = linear_regression_closed_form(new_features, labels)error_in = error_rate(new_features, labels, w)if error_in <= min_error_in:w14 = wmin_error_in = error_inerror_rate_array.append(error_in)
print("w14", w14)

运行结果为
w14 [[-0.95043879]
[ 0.02597952]
[ 0.00375311]
[ 0.00370397]
[ 1.54904793]
[ 1.60014614]]

##15

15题题目描述

在14题得到的最优w的基础上,我们利用产生训练样本的方法一样产生1000个测试样本,计算误差。重复1000次求平均误差

在14题的main方法里添加:

# 15
error_out = []
for i in range(1000):(features, labels) = training_data_with_random_error(1000)new_features = feature_transform(features)error_out.append(error_rate(new_features, labels, w14))
print("15--Average of E_out is: ", sum(error_out) / (len(error_out) * 1.0))

运行结果为0.1176709999999998

##18

18题题目描述

下载训练样本和测试样本,进行逻辑回归。取迭代步长ita = 0.001,迭代次数T=2000,求E_out

梯度下降时注意公式转化为代码

代码如下:

import numpy as npdef data_load(file_path):# open file and read linesf = open(file_path)try:lines = f.readlines()finally:f.close()# create features and labels arrayexample_num = len(lines)feature_dimension = len(lines[0].strip().split())features = np.zeros((example_num, feature_dimension))features[:, 0] = 1labels = np.zeros((example_num, 1))for index, line in enumerate(lines):# items[0:-1]--features   items[-1]--labelitems = line.strip().split(' ')# get featuresfeatures[index, 1:] = [float(str_num) for str_num in items[0:-1]]# get labellabels[index] = float(items[-1])return features, labels# gradient descent
def gradient_descent(X, y, w):# -YnWtXntmp = -y * (np.dot(X, w))# θ(-YnWtXn) = exp(tmp)/1+exp(tmp)# weight_matrix = np.array([math.exp(_)/(1+math.exp(_)) for _ in tmp]).reshape(len(X), 1)weight_matrix = np.exp(tmp) / ((1 + np.exp(tmp)) * 1.0)gradient = 1 / (len(X) * 1.0) * (sum(weight_matrix * -y * X).reshape(len(w), 1))return gradient# gradient descent
def stochastic_gradient_descent(X, y, w):# -YnWtXntmp = -y * (np.dot(X, w))# θ(-YnWtXn) = exp(tmp)/1+exp(tmp)# weight = math.exp(tmp[0])/((1+math.exp(tmp[0]))*1.0)weight = np.exp(tmp) / ((1 + np.exp(tmp)) * 1.0)gradient = weight * -y * Xreturn gradient.reshape(len(gradient), 1)# LinearRegression Class
class LinearRegression:def __init__(self):pass# fit modeldef fit(self, X, y, Eta=0.001, max_iteration=2000, sgd=False):# ∂E/∂w = 1/N * ∑θ(-YnWtXn)(-YnXn)self.__w = np.zeros((len(X[0]), 1))# whether use stochastic gradient descentif not sgd:for i in range(max_iteration):self.__w = self.__w - Eta * gradient_descent(X, y, self.__w)else:index = 0for i in range(max_iteration):if (index >= len(X)):index = 0self.__w = self.__w - Eta * stochastic_gradient_descent(np.array(X[index]), y[index], self.__w)index += 1# predictdef predict(self, X):binary_result = np.dot(X, self.__w) >= 0return np.array([(1 if _ > 0 else -1) for _ in binary_result]).reshape(len(X), 1)# get vector wdef get_w(self):return self.__w# score(error rate)def score(self, X, y):predict_y = self.predict(X)return sum(predict_y != y) / (len(y) * 1.0)if __name__ == '__main__':# 18# training model(X, Y) = data_load("hw3_train.dat")lr = LinearRegression()lr.fit(X, Y, max_iteration=2000)# get 0/1 error in test datatest_X, test_Y = data_load("hw3_test.dat")print("E_out: ", lr.score(test_X, test_Y))

运行结果为0.475

##19

19题题目描述

把第18题的步长ita=0.001改为0.01,求E_out

只需要更改main函数里的ita

# 19
# training model
(X, Y) = data_load("hw3_train.dat")
lr_eta = LinearRegression()
lr_eta.fit(X, Y, 0.01, 2000)
# get 0/1 error in test data
test_X, test_Y = data_load("hw3_test.dat")
print("E_out: ", lr_eta.score(test_X, test_Y))

运行结果为0.22

##20

20题题目描述

ita取0.001,迭代2000次,利用随机梯度下降法(Stostic Gradieng Descent),求迭代2000次后的Eout

我在18题的代码中给出了随机梯度下降的实现,只要在调用方法时将sgd设为True即可

# 20
(X, Y) = data_load("hw3_train.dat")
lr_sgd = LinearRegression()
lr_sgd.fit(X, Y, sgd=True, max_iteration=2000)
# get 0/1 error in test data
test_X, test_Y = data_load("hw3_test.dat")
print("E_out: ", lr_sgd.score(test_X, test_Y))

运行结果为0.473


http://chatgpt.dhexx.cn/article/UK9V1OCj.shtml

相关文章

机器学习基石系列三

课程关联与可学习 核心问题 上界限制 增长上限 上界证明&#xff08;不太懂&#xff09; - step three

林轩田 《机器学习基石》学习笔记

参考资料&#xff1a; 除了redstone的笔记较好之外&#xff0c;还有豆瓣的https://www.douban.com/doulist/3381853/的笔记也比较好 -------------------------------------- 1. 什么时候机器可以学习&#xff1f; 2. 为什么要要使用机器学习&#xff1f; 3. 机器怎么可以学习到…

【机器学习】机器学习基石-林轩田-1-机器学习介绍

机器学习基石-1-机器学习介绍 本节内容What is Machine Learning&#xff1f;What is skill?Why use machine learning?When use machine learning?Key Essence of Machine LearningFun TimeApplications of Machine LearningComponents of Machine Learning相关术语Leanin…

机器学习基石 作业0

机器学习基石 作业0 1 Probability and Statistics2 Linear Algebra3 Caculus网上没找到作业0的答案,这是自己做的版本,有一些可能会有错误,欢迎讨论。 1 Probability and Statistics 用数学归纳法。N=1时满足,假定N=n满足,当N=n+1同样满足。得证。 10个挑4个正面 C 10 4…

机器学习基石 作业三

机器学习基石 作业三 代入计算 线性回归得到的映射函数 H H H的性质问题。显然映射多次与映射一次效果一样。其它的可以根据 H H H的性质,秩为d+1,显然不可逆。特征值的部分不是非常清楚,大概是根据 I − H I-H I−H的迹等于 N − ( d + 1 ) N-(d+1) N−(d+1)得到的。3. PLA…

机器学习基石笔记

文章目录 一. 机器学习什么时候用二. 机器学习的基本流程三. 什么是机器学习四. 机器学习的可行性NFL定理从统计学中找到可行的方法统计学与机器学习产生联系 一. 机器学习什么时候用 事物本身存在某种潜在规律某些问题难以使用普通编程解决有大量的数据样本可供使用 二. 机器…

机器学习基石 作业二

机器学习基石 作业二 1 计算一下本来预测对与预测错时加上噪音导致的错误率然后相加即可。 2 选择一个 λ \lambda λ的值让 μ \mu μ的系数为0。 3 根据VC bound 公式带入计算即可,N=46000的时候error最接近0.05。下面的代码可以计算不同的N与目标error之间的差距。 def …

机器学习基石2-Learning to Answer Yes-No

注&#xff1a; 文章中所有的图片均来自台湾大学林轩田《机器学习基石》课程。 笔记原作者&#xff1a;红色石头 微信公众号&#xff1a;AI有道 上节课&#xff0c;简述了机器学习的定义及其重要性&#xff0c;并用流程图的形式介绍了机器学习的整个过程&#xff1a;根据模型\(…

机器学习基石-林轩田-第一周笔记

Lecture 01 - The Learning Problem When Can Machine Learn ?Why Can Machine Learn ?How Can Machine Learn ?How Can Machine Learn Better ? What is Machine Learning 什么是“学习”&#xff1f;学习就是人类通过观察、积累经验&#xff0c;掌握某项技能或能力。就…

机器学习基石16:三个重要原则(Three Learning Principles)

本节介绍了机器学习中三个重要原则&#xff0c;包括奥卡姆剃刀原理&#xff0c;样本偏差&#xff0c;数据窥探&#xff1b;并对16课程所学知识进行了总结。 系列文章 机器学习基石01&#xff1a;机器学习简介 机器学习基石02&#xff1a;感知器算法&#xff08;Perceptron Alg…

机器学习基石1(ML基本概念和VC dimension)

文章目录 一、什么是机器学习?二、什么时候可以使用机器学习?三、感知机perceptron四、机器学习的输入形式五、机器真的可以学习吗&#xff1f;六、vc dimension 一、什么是机器学习? 其实第一个问题和第二个问题是穿插到一块儿回答的&#xff0c;首先机器学习要解决的是常规…

Wireshark抓包数据

首先官网下载Wireshark&#xff0c;下载好后&#xff0c;用浏览器打开桂林生活网&#xff0c;无需注册&#xff0c;输入账号密码。 打开Wireshark&#xff0c;用命令提示符查看本机ip 在Wireshark的过滤搜索中输入ip10.34.152.44&#xff0c;找到http类型的数据查看&#xff0…

Wireshark抓包数据分析

文章目录 准备数据链路层实作一 熟悉 Ethernet 帧结构实作二 了解子网内/外通信时的 MAC 地址实作三 掌握 ARP 解析过程 网络层实作一 熟悉 IP 包结构实作二 IP 包的分段与重组实作三 考察 TTL 事件 传输层实作一 熟悉 TCP 和 UDP 段结构实作二 分析 TCP 建立和释放连接 应用层…

网络数据包分析与抓取

多年的网络数据包分析与抓取经验&#xff0c;闲话少说&#xff0c;上干货。先列举数据包的种类&#xff1a;1、Http数据包&#xff1b;2、UDP数据包&#xff1b;3、TCP数据包&#xff1b;4、ARP数据包&#xff1b;其实数据包的概念是很泛的&#xff0c;在软件可逆领域&#xff…

如何进行数据的抓包

抓包 抓包就是对网络传输中发送与接收的数据包进行截获、重发、编辑、转存等操作。 前提&#xff1a;抓取的数据包是从网卡设备中进行抓取的&#xff1b; win wiresharkLinux tcpdump命令 从上图我们就可以了解到tcpdump就是我们使用的一个工具&#xff1b; 我们在使用它时有…

WireShark基本抓包数据分析

WireShark抓包数据分析&#xff1a; 1、TCP报文格式 源端口、目的端口&#xff1a;16位长。标识出远端和本地的端口号。 顺序号&#xff1a;32位长。表明了发送的数据报的顺序。 确认号&#xff1a;32位长。希望收到的下一个数据报的序列号。 TCP协议数据报头DE 头长&#xff…

网络抓包及分析

今天我们主要来讲一下网络抓包的教程&#xff0c;我们用WireShark来说明 我们先说明下抓包工具界面 我们现在本地机子上用上面两个比较多 上面是抓无线网卡&#xff0c;就是你访问外网的包 下面是抓环回地址 &#xff0c;就是你访问127.0.0.1或localhost的包 我们抓上面WLAN…

Wireshark数据抓包分析之UDP协议

目录 预备知识1.UDP协议概述2.什么是UDP协议3.UDP协议的特点 实验目的实验环境实验步骤一1.配置TCP&UDP测试工具2.配置服务器端3.配置客户端4.获取UDP数据包 实验步骤二1.UDP首部格式2.分析UDP数据包 预备知识 1.UDP协议概述 UDP是User Datagram Protocol&#xff08;用户…

常见的几种网络抓包及协议分析工具

常见的几种网络抓包及协议分析工具 引言 网络工程师必备技能-抓取网络数据。 在本篇博客中&#xff0c;我们将集中记下几个问题进行探讨&#xff1a; 如何抓取电脑本机发送/接收的网络数据&#xff1f;如何在主机 A 上抓取 主机 B 上的网络数据&#xff1f;如何使用第三方设…

WireShark抓包分析

简述&#xff1a;本文介绍了抓包数据含义&#xff0c;有TCP报文、Http报文、DNS报文。如有错误&#xff0c;欢迎指正。 1、TCP报文 TCP&#xff1a;&#xff08;TCP是面向连接的通信协议&#xff0c;通过三次握手建立连接&#xff0c;通讯完成时要拆除连接&#xff0c;由于TCP …