Tensorflow 音乐预测

tensorflow 音乐预测

在本文中,我展示了如何使用张量流来预测音乐风格。
在我的示例中,我比较了电子音乐和古典音乐。

你可以在我的github上找到代码:
https://github.com/victordalet/sound_to_partition

i – 数据集

第一步,您需要创建一个数据集文件夹,并在里面添加一个音乐风格文件夹,例如我添加一个 techno 文件夹和 classic 文件夹,其中放置我的 wav 歌曲。

ii – 火车

我创建一个训练文件,参数 max_epochs 需要完成。

修改构造函数中与数据集文件夹中您的目录对应的类。

在加载和处理方法中,我从不同的目录检索wav文件并获取频谱图。

出于训练目的,我使用 keras 卷积和模型。

import osimport sysfrom typing import listimport librosaimport numpy as npfrom tensorflow.keras.layers import input, conv2d, maxpooling2d, flatten, densefrom tensorflow.keras.models import modelfrom tensorflow.keras.optimizers import adamfrom sklearn.model_selection import train_test_splitfrom tensorflow.keras.utils import to_categoricalfrom tensorflow.image import resizeclass train:    def __init__(self):        self.x_train = none        self.x_test = none        self.y_train = none        self.y_test = none        self.data_dir: str = 'dataset'        self.classes: list[str] = ['techno','classic']        self.max_epochs: int = int(sys.argv[1])    @staticmethod    def load_and_preprocess_data(data_dir, classes, target_shape=(128, 128)):        data = []        labels = []        for i, class_name in enumerate(classes):            class_dir = os.path.join(data_dir, class_name)            for filename in os.listdir(class_dir):                if filename.endswith('.wav'):                    file_path = os.path.join(class_dir, filename)                    audio_data, sample_rate = librosa.load(file_path, sr=none)                    mel_spectrogram = librosa.feature.melspectrogram(y=audio_data, sr=sample_rate)                    mel_spectrogram = resize(np.expand_dims(mel_spectrogram, axis=-1), target_shape)                    data.append(mel_spectrogram)                    labels.append(i)        return np.array(data), np.array(labels)    def create_model(self):        data, labels = self.load_and_preprocess_data(self.data_dir, self.classes)        labels = to_categorical(labels, num_classes=len(self.classes))  # convert labels to one-hot encoding        self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(data, labels, test_size=0.2,                                                                                random_state=42)        input_shape = self.x_train[0].shape        input_layer = input(shape=input_shape)        x = conv2d(32, (3, 3), activation='relu')(input_layer)        x = maxpooling2d((2, 2))(x)        x = conv2d(64, (3, 3), activation='relu')(x)        x = maxpooling2d((2, 2))(x)        x = flatten()(x)        x = dense(64, activation='relu')(x)        output_layer = dense(len(self.classes), activation='softmax')(x)        self.model = model(input_layer, output_layer)        self.model.compile(optimizer=adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy'])    def train_model(self):        self.model.fit(self.x_train, self.y_train, epochs=self.max_epochs, batch_size=32,                       validation_data=(self.x_test, self.y_test))        test_accuracy = self.model.evaluate(self.x_test, self.y_test, verbose=0)        print(test_accuracy[1])    def save_model(self):        self.model.save('weight.h5')if __name__ == '__main__':    train = train()    train.create_model()    train.train_model()    train.save_model()

iii-测试

为了测试和使用模型,我创建了这个类来检索权重并预测音乐的风格。

不要忘记将正确的类添加到构造函数中。

from typing import Listimport librosaimport numpy as npfrom tensorflow.keras.models import load_modelfrom tensorflow.image import resizeimport tensorflow as tfclass Test:    def __init__(self, audio_file_path: str):        self.model = load_model('weight.h5')        self.target_shape = (128, 128)        self.classes: List[str] = ['techno','classic']        self.audio_file_path: str = audio_file_path    def test_audio(self, file_path, model):        audio_data, sample_rate = librosa.load(file_path, sr=None)        mel_spectrogram = librosa.feature.melspectrogram(y=audio_data, sr=sample_rate)        mel_spectrogram = resize(np.expand_dims(mel_spectrogram, axis=-1), self.target_shape)        mel_spectrogram = tf.reshape(mel_spectrogram, (1,) + self.target_shape + (1,))        predictions = model.predict(mel_spectrogram)        class_probabilities = predictions[0]        predicted_class_index = np.argmax(class_probabilities)        return class_probabilities, predicted_class_index    def test(self):        class_probabilities, predicted_class_index = self.test_audio(self.audio_file_path, self.model)        for i, class_label in enumerate(self.classes):            probability = class_probabilities[i]            print(f'Class: {class_label}, Probability: {probability:.4f}')        predicted_class = self.classes[predicted_class_index]        accuracy = class_probabilities[predicted_class_index]        print(f'The audio is classified as: {predicted_class}')        print(f'Accuracy: {accuracy:.4f}')

以上就是Tensorflow 音乐预测的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1349448.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月13日 12:52:55
下一篇 2025年12月10日 13:33:25

相关推荐

  • ROBOFLOW – 使用 python 进行训练和测试

    roboflow 是一个用于注释图像以用于对象检测 ai 的平台。 我将这个平台用于 c2smr c2smr.fr,我的海上救援计算机视觉协会。 在本文中,我将向您展示如何使用这个平台并使用 python 训练您的模型。 您可以在我的github上找到更多示例代码:https://github.co…

    2025年12月13日
    000
  • Ansible 入门 – 初学者指南:日复一日的 DevOps 工具系列

    欢迎来到“50 天 50 个 devops 工具”系列的第 30 天!今天,我们将探索 ansible,它是 devops 工具包中最重要的工具之一。本博客将向您介绍 ansible 的基础知识,分解其关键组件并向您展示如何从简单的示例开始。我们会让事情简单明了,使其成为初学者的完美起点。 什么是 …

    2025年12月13日
    000
  • 释放 Claude AI:用于经济实惠且灵活的 AI 集成的非官方 API

    Anthropic 开发的 Claude AI 以其令人印象深刻的能力在 AI 社区中掀起波澜。然而,官方 API 对于许多开发人员和小型企业来说可能过于昂贵。这就是我们的非官方 Claude AI API 的用武之地,它提供了一个更实惠、更灵活的解决方案,用于将 Claude 的力量集成到您的项目…

    2025年12月13日
    000
  • 可视化项目

    我目前正在开发 TanaMobility,这是一个使用 Dash 和 Python 开发的交互式平台。该项目旨在通过利用地理空间数据对马达加斯加塔那那利佛的交通流进行建模和可视化,以更好地了解人口流动和交通动态。我非常感谢社区的反馈,以帮助改进这个平台并使可视化更加富有洞察力。欢迎您的帮助和建议。您…

    2025年12月13日
    000
  • 在 Pandas 中使用 DataFrame

    天哪!? 今天我带着一个新笔记本回来了,它演示了在 Jupyter 中处理数据的方法。 源文件 我从下载了数据集Kaggle 是一个查找真实世界数据并与其他数据爱好者联系的平台。在那里您会发现令人难以置信的数据集和项目集合,您还可以参加比赛。 工作的简短证据 返回数据框的简明摘要后,我执行了数据清理…

    2025年12月13日
    000
  • API 设计的艺术:使用 Nodejs 创建有效的 RESTful API

    在 Web 开发的动态世界中,可扩展且高效的应用程序必须建立在 API 设计的坚实基础上。随着对 RESTful API 的需求不断增加,Node.js 现已成为构建高性能、事件驱动的 API 来服务大量并发请求的强大力量。以下部分实际上深入研究了使用 Node.js 进行有效 API 设计的原则,…

    2025年12月13日
    000
  • 逻辑和编程练习:方法和优化

    鉴于此练习:(来自 codewars.com) 创建一个返回数字每位数字的平方的函数。 例如,输入函数时,数字702应该返回4904,因为7的平方是49, 0的平方是0,2的平方是4。如果函数接收到零,则必须返回 0. 此练习的根本挑战是逐位遍历整数并返回结果作为另一个整数。 就像编程中的一切一样,…

    2025年12月13日
    000
  • DevOps 中的高级脚本场景:日复一日的 DevOps 工具系列

    欢迎来到“50 天 50 个 devops 工具”系列的第 28 天!今天,在“50 天 50 个 devops 工具”系列的旅程中,我们探索了 bash 和 python 等基本脚本语言,涵盖了基础和生产级示例。今天,我们将深入探讨以前未涉及的高级脚本编写场景。这些场景对于自动化复杂任务和提高 d…

    2025年12月13日
    000
  • 为什么你应该更多地使用 attrs

    介绍 python 的 attrs 库对于希望简化类创建和减少样板代码的开发人员来说是一个游戏规则改变者。这个库甚至受到 nasa 的信任。attrs 由 hynek schlawack 于 2015 年创建,因其能够自动生成特殊方法并提供干净、声明式的方式来定义类,而迅速成为 python 开发人…

    2025年12月13日
    000
  • python爬虫入门教程 pdf python爬虫实战入门教程pdf下载步骤

    下载 Python 爬虫入门教程 PDF 步骤:在浏览器中搜索教程文件,例如 “python 爬虫入门教程 pdf”。选择一个网站,例如 TutorialsPoint。点击网站上的 “Download PDF” 按钮。选择保存文件的目标位置并点击 &#…

    2025年12月13日
    000
  • python3.4爬虫教程 pdf

    Python 3.4 爬虫教程 PDF 可从 [Python爬虫教程](https://morvanzhou.github.io/tutorials/scraping) 和 [电子工业出版社](https://www.ep.com.cn/product/4735/3611000009) 下载。教程内…

    2025年12月13日
    000
  • 使用scrapy爬虫视频教程

    使用 Scrapy 爬取视频教程指南:安装 Scrapy创建项目定义爬虫(提取视频链接)处理结果(存储提取的数据) 如何使用 Scrapy 爬虫视频教程 简介 Scrapy 是一款流行的 Python 爬虫框架,可用于从网页提取数据。本教程将指导你使用 Scrapy 爬取视频教程。 安装 Scrap…

    2025年12月13日
    000
  • 小电影推荐码

    这个新项目是关于数据结构以及如何使用它们的。最近刚刚了解了“bfs”和“dfs”,所以做了一个使用两者的项目。它是寻找以某种方式相互关联的电影标题。下面我列出了终端的屏幕截图以及 git hub 上项目的链接。让我知道你们会怎么想。 https://github.com/Zoobob5/Movie-…

    2025年12月13日
    000
  • 将数据加载到 Neo4j 中

    在上一篇博客中,我们了解了如何使用 2 个插件 apoc 和图形数据科学库 – gds 在本地安装和设置 neo4j。在这篇博客中,我将获取一个玩具数据集(电子商务网站中的产品)并将其存储在 neo4j 中。   为 neo4j 分配足够的内存 在开始加载数据之前,如果您的用例中有大量数…

    2025年12月13日 好文分享
    000
  • python爬虫免费教程视频

    免费学习 Python 爬虫的途径包括:在线课程与教程(Coursera、Udemy、YouTube、DataCamp、Codecademy)书籍与文档(Python 爬虫手册、Scrapy、Beautiful Soup、Requests、Twisted 文档)社区与论坛(Stack Overflo…

    2025年12月13日
    000
  • python爬虫教程资源下载

    如何下载 Python 爬虫教程资源?这里有六种途径:1. 官方文档;2. 视频教程;3. 书籍;4. 在线课程;5. 开源项目;6. 博客和论坛。 Python 爬虫教程资源下载 如何下载 Python 爬虫教程资源? 1. 官方文档 [Python 官方爬虫教程](https://docs.py…

    2025年12月13日
    000
  • python爬虫代码教程网站

    Python 爬虫代码教程网站:教程点:提供全面教程,涵盖基础和高级概念。博客和文档:比如 Beautiful Soup 和 Scrapy 文档,以及 Python 爬虫博客,提供技巧、教程和示例代码。选择教程时考虑的因素:技能水平项目目标教学风格使用教程的提示:仔细阅读教程。练习示例代码。从简单项…

    2025年12月13日
    000
  • python爬虫实战入门教程pdf

    网络抓取是使用 Python 从网站自动提取数据的过程。Python 爬虫实战入门教程 PDF 提供了全面指南,涵盖网络抓取基础、BeautifulSoup 解析、Scrapy 构建、数据处理和项目示例。可通过官方网站、GitHub 或 Google Scholar 获取 PDF 教程。其他学习资源…

    2025年12月13日
    000
  • scrapy爬虫抓取视频教程

    使用 Scrapy 爬虫可抓取视频教程简介:安装 Scrapy。创建项目。创建爬虫,指定抓取域、起始 URL 和解析回调函数。运行爬虫,将其输出为 CSV 文件。 使用 Scrapy 爬虫抓取视频教程 简介 Scrapy 是一个强大的网络爬虫框架,可用于从网站提取数据。本指南将介绍如何使用 Scra…

    2025年12月13日
    000
  • 从带印记到干净:将带水印的图像转变为清晰的视觉效果

    您是否想知道如何使用python从图像中去除水印?很简单!如果您有兴趣,您应该了解 python 并具备 cnn 和 tensorflow dl 框架等计算机视觉模型的基本知识,以便遵循架构!在运行代码之前,请确保您阅读了要去除水印的图像的版权法。 遵循的步骤 – 创建一个新google…

    2025年12月13日
    000

发表回复

登录后才能评论
关注微信