使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib

这篇具有很好参考价值的文章主要介绍了使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

from sklearn.datasets import make_circles
from sklearn.cluster import KMeans, DBSCAN, SpectralClustering, Birch, MeanShift, AgglomerativeClustering
from sklearn.metrics import silhouette_score, silhouette_samples
from sklearn.decomposition import PCA

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time, os
import functools
import matplotlib.cm as cm

from torchvision.io.video import read_video
from torchvision.models.video import r3d_18, R3D_18_Weights
from torchvision.models.video import mvit_v1_b, MViT_V1_B_Weights
 
 
def cluster_test(model_name, model, X, clusters_list = [2,3,4,5,6,7]):
    for n_clusters in clusters_list:
        if hasattr(model, "n_clusters"):
            model.set_params(n_clusters = n_clusters)
        elif len(clusters_list) >= 2 and n_clusters == clusters_list[1]:
            print("{} do not have parameter 'n_clusters', return automatically.".format(model_name))
            return
        
        fig, (ax1, ax2) = plt.subplots(1, 2)
        fig.set_size_inches(18, 7)
 
        ax1.set_xlim([-0.1, 1])
        ax1.set_ylim([0, X.shape[0] + (n_clusters + 1) * 10])
 
        clusterer, t = cluster_function(model_name, model, X)
        cluster_labels = clusterer.labels_
        silhouette_avg = silhouette_score(X, cluster_labels)
        print("For n_clusters = ", n_clusters, " the average silhoutte_score is ", silhouette_avg)
        sample_silhouette_values = silhouette_samples(X, cluster_labels)
 
        y_lower = 10
        for i in range(n_clusters):
            ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]
            ith_cluster_silhouette_values.sort()
            size_cluster_i = ith_cluster_silhouette_values.shape[0]
            y_upper = y_lower + size_cluster_i
            color = cm.nipy_spectral(float(i) / n_clusters)
 
            ax1.fill_betweenx(np.arange(y_lower, y_upper), ith_cluster_silhouette_values, facecolor = color, alpha = 0.7)
            ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
            y_lower = y_upper + 10
 
        ax1.set_title("The silhouette plot for the various clusters")
        ax1.set_xlabel("The silhouette coefficient values")
        ax1.set_ylabel("Cluster label")
        ax1.axvline(x = silhouette_avg, color = 'red', linestyle = "--")
        ax1.set_yticks([])
        ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
        
        colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
        ax2.scatter(pca_result[:,0], pca_result[:,1], marker = 'o', s = 8, c = colors)
        if hasattr(clusterer, 'cluster_centers_'):
            centers = clusterer.cluster_centers_
            ax2.scatter(centers[:, 0], centers[:, 1], marker = 'x', c = 'red', alpha = 1, s = 200)
        ax2.text(.99, .01, ('%.2fs' % (t)).lstrip('0'), transform=plt.gca().transAxes, size=12,horizontalalignment='right')
        ax2.set_title("The visualization of the clustered data")
        ax2.set_xlabel("Feature space for the 1st feature")
        ax2.set_ylabel("Feature space for the 2nd feature")
 
        plt.suptitle("Silhouette analysis for {} clustering on sample data with n_clusters = {} ({})".format(model_name, n_clusters, silhouette_avg), fontsize = 14, fontweight="bold")
        plt.show()
 
        
def time_cost(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        t0 = time.time()
        func(*args, **kwargs)
        t1 = time.time()
        return func(*args, **kwargs), t1 - t0
    return wrapper
 
 
@time_cost
def cluster_function(model_name, model, data):
    model = model.fit(data)
    return model
 
 
def load_data(file_dir):
    assert file_dir != ''
    x = []
    for item in os.listdir(file_dir):
        data = video_feature(os.path.join(file_dir, item))
        x.append(np.array(data))
    x = np.array(x)
    print(x.shape)
    #x = df.values
    pca = PCA(n_components=6)
    pca_result = pca.fit_transform(x)
    return x, pca_result
 
def video_feature(file_path):
    vid, _, _ = read_video(file_path, output_format="TCHW")
    vid = vid[:16]
    # Step 1: Initialize model with the best available weights
    # weights = R3D_18_Weights.DEFAULT
    # model = r3d_18(weights=weights)
    weights = MViT_V1_B_Weights.DEFAULT
    model = mvit_v1_b(weights)
    model.eval()
    # Step 2: Initialize the inference transforms
    preprocess = weights.transforms()
    # Step 3: Apply inference preprocessing transforms
    batch = preprocess(vid).unsqueeze(0)
    prediction = model(batch).squeeze(0)
    prediction = prediction.cpu().detach().numpy()
    # print(prediction.shape)
    
    return prediction
    # Step 4: Use the model and print the predicted category
    prediction = model(batch).squeeze(0).softmax(0)
    label = prediction.argmax().item()
    score = prediction[label].item()
    category_name = weights.meta["categories"][label]
    print(f"{category_name}: {100 * score}%")
 

if __name__ == "__main__":
    path = r"/home/markjhon/Common/Dataset/Infant/Left_hand"

    # 加载数据
    x, pca_result = load_data(path)
    cluster_test("AgglomerativeClustering", AgglomerativeClustering(), x)

使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib,深度学习,pytorch,人工智能使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib,深度学习,pytorch,人工智能使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib,深度学习,pytorch,人工智能使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib,深度学习,pytorch,人工智能使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib,深度学习,pytorch,人工智能使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib,深度学习,pytorch,人工智能文章来源地址https://www.toymoban.com/news/detail-620153.html

到了这里,关于使用深度学习模型对视频进行聚类分析-Pytorch、Skleran、Matplotlib的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • 使用PyTorch解决多分类问题:构建、训练和评估深度学习模型

    💗💗💗欢迎来到我的博客,你将找到有关如何使用技术解决问题的文章,也会找到某个技术的学习路线。无论你是何种职业,我都希望我的博客对你有所帮助。最后不要忘记订阅我的博客以获取最新文章,也欢迎在文章下方留下你的评论和反馈。我期待着与你分享知识、互

    2024年02月07日
    浏览(34)
  • 医学图像的深度学习的完整代码示例:使用Pytorch对MRI脑扫描的图像进行分割

    图像分割是医学图像分析中最重要的任务之一,在许多临床应用中往往是第一步也是最关键的一步。在脑MRI分析中,图像分割通常用于测量和可视化解剖结构,分析大脑变化,描绘病理区域以及手术计划和图像引导干预,分割是大多数形态学分析的先决条件。 本文我们将介绍

    2024年02月05日
    浏览(35)
  • Python与深度学习:Keras、PyTorch和Caffe的使用和模型设计

      深度学习已经成为当今计算机科学领域的热门技术,而Python则是深度学习领域最受欢迎的编程语言之一。在Python中,有多个深度学习框架可供选择,其中最受欢迎的包括Keras、PyTorch和Caffe。本文将介绍这三个框架的使用和模型设计,帮助读者了解它们的优势、特点和适用场

    2024年02月09日
    浏览(31)
  • 使用高斯混合模型进行聚类

            高斯混合模型 (GMM) 是一种基于概率密度估计的聚类分析技术。它假设数据点是由具有不同均值和方差的多个高斯分布的混合生成的。它可以在某些结果中提供有效的聚类结果。         K 均值聚类算法在每个聚类的中心周围放置一个圆形边界。当数据具有圆

    2024年02月09日
    浏览(27)
  • 使用MobaXterm连接服务器并利用Anaconda进行安装pytoch框架跑深度学习模型(使用学校服务器+显卡进行深度学习)

    在开始之前你需要找学校服务器负责人 申请服务器账号和密码 以及 校内外网IP和端口号 ;另外还需要知道学校 服务器显卡cuda版本 ,以及去pytorch官网查看显卡cuda版本对应的 pytorch版本 一、安装MobaXterm 1.下载MobaXterm 软件的下载可以去这里:我都已经给大家准备好了。 在我网

    2024年02月07日
    浏览(45)
  • Pytorch迁移学习使用Resnet50进行模型训练预测猫狗二分类

    目录   1.ResNet残差网络 1.1 ResNet定义  1.2 ResNet 几种网络配置  1.3 ResNet50网络结构 1.3.1 前几层卷积和池化 1.3.2 残差块:构建深度残差网络 1.3.3 ResNet主体:堆叠多个残差块 1.4 迁移学习猫狗二分类实战 1.4.1 迁移学习 1.4.2 模型训练 1.4.3 模型预测   深度学习在图像分类、目标检

    2024年02月16日
    浏览(28)
  • Python使用pytorch深度学习框架构造Transformer神经网络模型预测红酒分类例子

    经典的红酒分类数据集是指UCI机器学习库中的Wine数据集。该数据集包含178个样本,每个样本有13个特征,可以用于分类任务。 具体每个字段的含义如下: alcohol:酒精含量百分比 malic_acid:苹果酸含量(克/升) ash:灰分含量(克/升) alcalinity_of_ash:灰分碱度(以mEq/L为单位)

    2024年02月02日
    浏览(33)
  • Pytorch迁移学习使用MobileNet v3网络模型进行猫狗预测二分类

    目录 1. MobileNet 1.1 MobileNet v1 1.1.1 深度可分离卷积  1.1.2 宽度和分辨率调整 1.2 MobileNet v2 1.2.1 倒残差模块 1.3 MobileNet v3 1.3.1 MobieNet V3 Block  1.3.2 MobileNet V3-Large网络结构 1.3.3 MobileNet V3预测猫狗二分类问题 送书活动   MobileNet v1 是MobileNet系列中的第一个版本,于2017年由Google团队提

    2024年02月14日
    浏览(26)
  • 在 WSL2 中使用 NVIDIA Docker 进行全栈开发和深度学习 TensorFlow pytorch GPU 加速

    0.1 起源 生产环境都是在 k8d pod 中运行,直接在容器中开发不好嘛? 每次换电脑,都要配配配,呸呸呸 新电脑只安装日常用的软件不好嘛,环境变量配配配,各种日常软件和开发软件到处拉💩 虚拟机呗,怎么调用 GPU 是个问题,hyper-v 好像是可以魔改配置实现,又得改改改。

    2024年02月11日
    浏览(44)
  • 【深度学习】使用ffmpg及gstreamer进行视频拉流及编解码(一):ffmpg

    视频流需要编解码的主要原因是视频文件的数据量很大,直接传输视频文件会占用大量网络带宽和存储空间。而通过对视频进行编码和解码,可以将视频数据压缩到较小的体积,从而实现更高效的传输和存储。 具体来说,编码就是将原始的视频数据转换为压缩后的视频数据,

    2024年02月15日
    浏览(37)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包