机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

这篇具有很好参考价值的文章主要介绍了机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

[实验1 回归分析]

一、 预备知识

  1. 使用梯度下降法求解多变量回归问题
机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

  1. 数据集

Iris 鸢尾花数据集是一个经典数据集,在统计学习和机器学习领域都经常被用作示例。数据集内包含 3 类共 150 条记录,每类各 50 个数据,每条记录都有 4 项特征:花萼长度、花萼宽度、花瓣长度、花瓣宽度,可以通过这4个特征预测鸢尾花卉属于(iris-setosa, iris-versicolour, iris-virginica)中的哪一品种。

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

sepal length:花萼长度,单位cm;sepal width:花萼宽度,单位cm
petal length:花瓣长度,单位cm;petal width:花瓣宽度,单位cm

种类:setosa(山鸢尾),versicolor(杂色鸢尾),virginica(弗吉尼亚鸢尾)

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

我们用100组数据作为训练数据iris-train.txt,50组数据作为测试数据iris-test.txt。

'setosa' 'versicolor' 'virginica'

0 1 2

二、 实验目的

  1. 掌握梯度下降法的原理及设计;

  2. 掌握利用梯度下降法解决回归类问题。

三、 实验内容

数据读取:(前4列是特征x,第5列是标签y)

import numpy as np
train_data  = np.loadtxt('iris-train.txt', delimiter='\t')
x_train=np.array(train_data[:,:4])
y_train=np.array(train_data[:,4])
  1. 设计多变量回归分析方法,利用训练数据iris-train.txt求解参数

思路:首先确定h(x)函数,由于是4个特征,我们可以取5个参数

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

  1. 设计逻辑回归分析方法,利用训练数据iris-train.txt求解参数

思路:首先确定h(x)函数,由于是4个特征,我们可以取5个参数

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

  1. 利用测试数据iris-test.txt,统计逻辑回归对测试数据的识别正确率 ACC,Precision,Recall。

四、 操作方法和实验步骤

​ 1.对于多变量回归分析:

\[\alpha \frac{\partial}{\partial \theta _j}L(\theta _0,\theta _1...\theta _n)=\frac { \alpha } { m } X^T(X\theta-y) \]

​ (1)实现损失函数、h(x)、梯度下降函数等:

def hypothesis(X, theta):
    return np.dot(X, theta)

def cost_function(X, y, theta):
    m = len(y)
    J = np.sum((hypothesis(X, theta) - y) ** 2) / (2 * m)
    return J

def gradient_descent(X, y, theta, alpha, num_iters):
    m = len(y)
    J_history = np.zeros(num_iters)
    for i in range(num_iters):
        theta = theta - (alpha / m) * np.dot(X.T, (hypothesis(X, theta) - y))
        J_history[i] = cost_function(X, y, theta)
    return theta, J_history

​ (2)处理输出X并开始计算

X_train_hat= np.hstack((np.ones((X_train.shape[0], 1)), X_train))
X_train= X_train_hat
theta = np.ones(X_train.shape[1])

alpha = 0.0005
num_iters = 120

theta, J_history = gradient_descent(X_train, y_train, theta, alpha, num_iters)


print("Parameter vector: ", theta)
print("Final cost: ", J_history[-1])
  1. 对于逻辑回归分析
import numpy as np
from sklearn.metrics import classification_report
from sklearn.preprocessing import LabelEncoder

train_data = np.loadtxt("iris/iris-train.txt", delimiter="\t")
X_train = train_data[:, 0:4]
y_train = train_data[:, 4]
encoder = LabelEncoder()
y_train = encoder.fit_transform(y_train)  # Convert class labels to 0, 1, 2
X_train_hat = np.hstack((np.ones((X_train.shape[0], 1)), X_train))
X_train = X_train_hat
def sigmoid(z):
    return 1 / (1 + np.exp(-z))

def cost_function(X, y, theta):
    m = len(y)
    epsilon = 1e-5
    h = sigmoid(np.dot(X, theta))
    J = (-1 / m) * np.sum(y * np.log(h+epsilon) + (1 - y) * np.log(1 - h+epsilon))
    grad = (1 / m) * np.dot(X.T, (h - y))
    return J, grad

def gradient_descent(X, y, theta, alpha, num_iters):
    m = len(y)
    J_history = np.zeros(num_iters)
    for i in range(num_iters):
        J, grad = cost_function(X, y, theta)
        theta = theta - (alpha * grad)
        J_history[i] = J
    return theta, J_history
def logistic_regression(X, y, alpha, num_iters):
    theta = np.ones((X_train.shape[1], 3))
    # Perform gradient descent to minimize the cost function for each class
    for i in range(3):
        y_train_i = (y_train == i).astype(int)
        theta_i, J_history_i = gradient_descent(X_train, y_train_i, theta[:, i], alpha, num_iters)
        import matplotlib.pyplot as plt

        plt.plot(J_history_i)
        plt.xlabel('Iterations')
        plt.ylabel('Cost')
        plt.title('Cost function'+str(i))
        plt.show()
        theta[:, i] = theta_i
        print(f"Class {i} parameter vector: {theta_i}")
        print(f"Class {i} final cost: {J_history_i[-1]}")
    return theta
def predict(test_data, theta):
    X_test = test_data[:, 0:4]
    X_test_hat = np.hstack((np.ones((X_test.shape[0], 1)), X_test))
    X_test = X_test_hat
y_test = test_data[:, 4]
    y_test = encoder.transform(y_test)  # Convert class labels to 0, 1, 2
    y_pred = np.zeros(X_test.shape[0])
    for i in range(3):
        sigmoid_outputs = sigmoid(np.dot(X_test, theta[:, i]))
        threshold = np.median(sigmoid_outputs[y_test == i])#不采用统一的阈值,而是采用每个类别的中位数作为阈值
        y_pred_i = (sigmoid_outputs >= threshold).astype(int)
        y_pred[y_pred_i == 1] = i
    y_pred = encoder.inverse_transform(y_pred.astype(int))  # Convert class labels back to original values
    print(classification_report(y_test, y_pred))

test_data = np.loadtxt("iris/iris-test.txt", delimiter="\t")
theta = logistic_regression(X_train, y_train, 0.0005, 5000)
predict(test_data, theta)

实验结果和分析

1.对于多变量回归分析的实验结果:

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

代价曲线:

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

那么计算函数也就是:

\[y=-0.306x_1+0.0653x_2+0.280x_3+0.697x_4-0.713 \]

​ 2.对于逻辑回归分析的实验结果

代价曲线:

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

​ 利用测试数据iris-test.txt,统计逻辑回归对测试数据的识别正确率 ACC,Precision,Recall:

​ 通过sigmoid函数实现的逻辑回归只能处理二分类,我是通过分别计算三个二分类实现的。【猜测:预测1时把0和2归为同一类会对模型产生误导】

​ 由于实现方法是One VS One.效果并不是很好,而且得到如下结果还是在处理sigmoid函数结果时还修改了原本0.5的阈值,有泄露结果的嫌疑。

不采用统一的阈值,而是采用每个类别的h函数结果中位数作为阈值

机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合

五、 思考题

给出 RANSAC 线性拟合的 python 实现

import random
import numpy as np
from matplotlib import pyplot as plt


def ransac_line_fit(data, n_iterations, threshold):
    """
    RANSAC algorithm for linear regression.

    Parameters:
    data (list): list of tuples representing the data points
    n_iterations (int): number of iterations to run RANSAC
    threshold (float): maximum distance a point can be from the line to be considered an inlier

    Returns:
    tuple: slope and y-intercept of the best fit line
    """
    best_slope, best_intercept = None, None
    best_inliers = []

    for i in range(n_iterations):
        # Randomly select two points from the data
        sample = random.sample(data, 2)
        x1, y1 = sample[0]
        x2, y2 = sample[1]

        # Calculate slope and y-intercept of line connecting the two points
        slope = (y2 - y1) / (x2 - x1)
        intercept = y1 - slope * x1

        # Find inliers within threshold distance of the line
        inliers = []
        outliers = []
        for point in data:
            x, y = point
            distance = abs(y - (slope * x + intercept))
            distance = distance / np.sqrt(slope ** 2 + 1)
            if distance <= threshold:
                inliers.append(point)
            else:
                outliers.append(point)

        # If the number of inliers is greater than the current best, update the best fit line
        if len(inliers) > len(best_inliers):
            best_slope = slope
            best_intercept = intercept
            best_inliers = inliers

    outliers = [point for point in data if point not in best_inliers]
    # Plot the data points, best fit line, and inliers and outliers
    fig, ax = plt.subplots()
    # ax.scatter([x for x, y in data], [y for x, y in data], color='black')
    ax.scatter([x for x, y in best_inliers], [y for x, y in best_inliers], color='green')
    ax.scatter([x for x, y in outliers], [y for x, y in outliers], color='black')
    x_vals = np.array([-5,5])
    y_vals = best_slope * x_vals + best_intercept
    ax.plot(x_vals, y_vals, '-', color='red')
    # threshold_line = best_slope * x_vals + best_intercept + threshold*np.sqrt((1/best_slope) ** 2 + 1)
    threshold_line = best_slope * x_vals + best_intercept + threshold * np.sqrt(best_slope ** 2 + 1)
    ax.plot(x_vals, threshold_line, '--', color='blue')
    # threshold_line = best_slope * x_vals + best_intercept - threshold*np.sqrt((1/best_slope) ** 2 + 1)
    threshold_line = best_slope * x_vals + best_intercept - threshold * np.sqrt(best_slope ** 2 + 1)
    ax.plot(x_vals, threshold_line, '--', color='blue')
    # ax.set_xlim([-10, 10])
    ax.set_ylim([-6, 6])
    plt.show()

    return best_slope, best_intercept


import numpy as np

# Generate 10 random points with x values between 0 and 10 and y values between -5 and 5
data = [(x, y) for x, y in zip(np.random.uniform(-5, 5, 10), np.random.uniform(-5, 5, 10))]

print(data)

# Fit a line to the data using RANSAC
slope, intercept = ransac_line_fit(data, 10000, 1)
print(slope, intercept)

结果:机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合文章来源地址https://www.toymoban.com/news/detail-412242.html

到了这里,关于机器学习(六):回归分析——鸢尾花多变量回归、逻辑回归三分类只用numpy,sigmoid、实现RANSAC 线性拟合的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 机器学习——鸢尾花数据集

    鸢尾花数据集即iris iris数据集文件: https://pan.baidu.com/s/1saL_4Q9PbFJluU4htAgFdQ .提取码:1234 数据集包含150个样本(数据集的行) 数据集包含4个属性(数据集的列):Sepal Length,Sepal Width,Petal Length,Petal Width:‘feature_names’ 利用numpy.ndarray存储这150x4的数据:‘data’ 分类标签取

    2023年04月08日
    浏览(24)
  • PyTorch深度学习实战 | 基于线性回归、决策树和SVM进行鸢尾花分类

    鸢尾花数据集是机器学习领域非常经典的一个分类任务数据集。它的英文名称为Iris Data Set,使用sklearn库可以直接下载并导入该数据集。数据集总共包含150行数据,每一行数据由4个特征值及一个标签组成。标签为三种不同类别的鸢尾花,分别为:Iris Setosa,Iris Versicolour,Iri

    2023年04月10日
    浏览(28)
  • 【机器学习】KNN算法-鸢尾花种类预测

    K最近邻(K-Nearest Neighbors,KNN)算法是一种用于模式识别和分类的简单但强大的机器学习算法。它的工作原理非常直观:给定一个新数据点,KNN算法会查找离这个数据点最近的K个已知数据点,然后基于这K个最近邻数据点的类别来决定新数据点的类别。简而言之,KNN算法通过周

    2024年02月07日
    浏览(28)
  • 机器学习-KNN算法(鸢尾花分类实战)

    前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。 K近邻(K Nearest Neighbors,KNN)算法是最简单的分类算法之一,也就是根据现有训练数据判断输入样本是属于哪一个类别。 “近朱者赤近墨者黑\\\",所谓的K近邻,也就

    2023年04月08日
    浏览(60)
  • 机器学习实验3——支持向量机分类鸢尾花

    基于鸢尾花数据集,完成关于支持向量机的分类模型训练、测试与评估。 代码 认识数据 属性:花萼长度,花萼宽度,花瓣长度,花瓣宽度 分类:Setosa,Versicolour,Virginica 相关性分析 如下图,可以直观看到花瓣宽度(Petal Width)和花瓣长度(Petal Length)存在很高的正相关性,

    2024年01月24日
    浏览(26)
  • 机器学习:KNN算法对鸢尾花进行分类

    1.算法概述 KNN(K-NearestNeighbor)算法经常用来解决分类与回归问题, KNN算法的原理可以总结为\\\"近朱者赤近墨者黑\\\",通过数据之间的相似度进行分类。就是通过计算测试数据和已知数据之间的距离来进行分类。 如上图,四边形代表测试数据,原型表示已知数据,与测试数据最

    2024年02月09日
    浏览(36)
  • 【机器学习实例讲解】机器学习-鸢尾花数据集多分类第02课

    问题定义与理解: 明确机器学习任务的目标,是分类、回归、聚类、强化学习还是其他类型的问题。 确定业务背景和需求,了解所处理数据的现实意义。 数据收集: 根据任务目标从各种来源获取原始数据,可以是数据库、文件、传感器、网络日志等。 数据预处理: 数据清

    2024年01月18日
    浏览(28)
  • 初识机器学习——感知机(Perceptron)+ Python代码实现鸢尾花分类

      假设输入空间 χ ⊆ R n chisubseteq R^n χ ⊆ R n ,输出空间为 γ = { + 1 , − 1 } gamma=left { +1,-1right } γ = { + 1 , − 1 } 。其中每一个输入 x ⊆ χ xsubseteq chi x ⊆ χ 表示对应于实例的特征向量,也就是对应于输入空间(特征空间)的一个点, y ⊆ γ ysubseteq gamma y ⊆ γ 输出表

    2023年04月08日
    浏览(33)
  • 【机器学习案例】不同的模型算法对鸢尾花数据集进行分类

    经典机器学习入门项目,使用逻辑回归、线性判别分析、KNN、分类与回归树、朴素贝叶斯、向量机、随机森林、梯度提升决策树对不同占比的训练集进行分类 数据源 :Iris Species | Kaggle 150行,5列,分三种鸢尾花类型,每种类型50个样本,每行数据包含花萼长度、花萼宽度、花

    2024年02月04日
    浏览(23)
  • 【机器学习】决策树案例二:利用决策树进行鸢尾花数据集分类预测

    手动反爬虫,禁止转载: 原博地址 https://blog.csdn.net/lys_828/article/details/122045161(CSDN博主:Be_melting) 在进行逻辑回归分类的过程中已经有使用过iris数据集,这里直接加载数据,并进行字段名称的修改。 输出结果如下。 通过info()方法查看各个字段的基本详情,输出结果如下。

    2024年02月08日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包