Buckets:

rtrm's picture
download
raw
110 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Дообучение модели для классификации музыки&quot;,&quot;local&quot;:&quot;дообучение-модели-для-классификации-музыки&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Набор данных&quot;,&quot;local&quot;:&quot;набор-данных&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Выбор предварительно обученной модели для классификации звука&quot;,&quot;local&quot;:&quot;выбор-предварительно-обученной-модели-для-классификации-звука&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;От аудио к машинному обучению&quot;,&quot;local&quot;:&quot;от-аудио-к-машинному-обучению&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Предварительная обработка данных&quot;,&quot;local&quot;:&quot;предварительная-обработка-данных&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Дообучение модели&quot;,&quot;local&quot;:&quot;дообучение-модели&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Поделиться моделью&quot;,&quot;local&quot;:&quot;поделиться-моделью&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Заключение&quot;,&quot;local&quot;:&quot;заключение&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}">
<link href="/docs/audio-course/pr_227/ru/_app/immutable/assets/0.e3b0c442.css" rel="modulepreload">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/entry/start.fc7d9a04.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/scheduler.cd324960.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/singletons.d714c243.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/index.a0c12d66.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/paths.6249493e.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/entry/app.0acf0b9e.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/preload-helper.6b80c356.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/index.d5c3adcc.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/nodes/0.0a1f9128.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/each.e59479a4.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/nodes/24.37dd0d22.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/Tip.889bec11.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/MermaidChart.svelte_svelte_type_style_lang.b3ee0d86.js">
<link rel="modulepreload" href="/docs/audio-course/pr_227/ru/_app/immutable/chunks/CodeBlock.6bf7b79a.js"><!-- HEAD_svelte-u9bgzb_START --><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Дообучение модели для классификации музыки&quot;,&quot;local&quot;:&quot;дообучение-модели-для-классификации-музыки&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Набор данных&quot;,&quot;local&quot;:&quot;набор-данных&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Выбор предварительно обученной модели для классификации звука&quot;,&quot;local&quot;:&quot;выбор-предварительно-обученной-модели-для-классификации-звука&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;От аудио к машинному обучению&quot;,&quot;local&quot;:&quot;от-аудио-к-машинному-обучению&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Предварительная обработка данных&quot;,&quot;local&quot;:&quot;предварительная-обработка-данных&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Дообучение модели&quot;,&quot;local&quot;:&quot;дообучение-модели&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Поделиться моделью&quot;,&quot;local&quot;:&quot;поделиться-моделью&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Заключение&quot;,&quot;local&quot;:&quot;заключение&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"><!-- HEAD_svelte-u9bgzb_END --> <p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: right; margin-left: 10px; display: inline-flex; position: relative; z-index: 10;"><div class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 max-sm:gap-0.5 h-6 max-sm:h-5 px-2 max-sm:px-1.5 text-[11px] max-sm:text-[9px] font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0"><svg class="w-3 h-3 max-sm:w-2.5 max-sm:h-2.5" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg></span> <span>Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-6 max-sm:h-5 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible w-3 h-3 max-sm:w-2.5 max-sm:h-2.5 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg></button></div> </div> <h1 class="relative group"><a id="дообучение-модели-для-классификации-музыки" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#дообучение-модели-для-классификации-музыки"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Дообучение модели для классификации музыки</span></h1> <p data-svelte-h="svelte-1wn76oa">В этом разделе мы представим пошаговое руководство по дообучению модели трансформера, использующей только кодеровщик,
для классификации музыки. Для демонстрации мы будем использовать облегченную модель и достаточно небольшой набор данных, что означает,
что код может быть запущен на любом GPU потребительского класса, включая GPU T4 16GB, предоставляемый в рамках бесплатного уровня Google Colab.
В разделе приведены различные советы, которые можно попробовать при использовании GPU меньшего размера и возникновении проблем с нехваткой памяти.</p> <h2 class="relative group"><a id="набор-данных" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#набор-данных"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Набор данных</span></h2> <p data-svelte-h="svelte-1o2x5ik">Для обучения нашей модели мы будем использовать набор данных <a href="https://huggingface.co/datasets/marsyas/gtzan" rel="nofollow">GTZAN</a>, который представляет собой
популярный набор данных из 1000 песен для классификации музыкальных жанров. Каждая песня представляет собой 30-секундный клип из одного из 10
музыкальных жанров - от диско до металла. Мы можем получить аудиофайлы и соответствующие им метки из Hugging Face Hub с помощью функции
<code>load_dataset()</code> из 🤗 Datasets:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> load_dataset
gtzan = load_dataset(<span class="hljs-string">&quot;marsyas/gtzan&quot;</span>, <span class="hljs-string">&quot;all&quot;</span>)
gtzan<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-title function_ invoke__">Dataset</span>({
<span class="hljs-attr">features</span>: [<span class="hljs-string">&#x27;file&#x27;</span>, <span class="hljs-string">&#x27;audio&#x27;</span>, <span class="hljs-string">&#x27;genre&#x27;</span>],
<span class="hljs-attr">num_rows</span>: <span class="hljs-number">999</span>
})<!-- HTML_TAG_END --></pre></div> <blockquote class="warning"><p data-svelte-h="svelte-775hp5">Одна из записей в GTZAN повреждена, поэтому она была удалена из набора данных. Поэтому мы имеем 999 примеров
вместо 1000.</p></blockquote> <p data-svelte-h="svelte-1pvazgx">GTZAN не предоставляет предопределенного валидационного набора, поэтому нам придется создать его самостоятельно.
Набор данных сбалансирован по жанрам, поэтому мы можем использовать метод <code>train_test_split()</code> для быстрого
создания разбиения в пропорции 90/10 следующим образом:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->gtzan = gtzan.train_test_split(seed=<span class="hljs-number">42</span>, shuffle=<span class="hljs-literal">True</span>, test_size=<span class="hljs-number">0.1</span>)
gtzan<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->DatasetDict({
train: <span class="hljs-built_in">Dataset</span>({
features: [<span class="hljs-string">&#x27;file&#x27;</span>, <span class="hljs-string">&#x27;audio&#x27;</span>, <span class="hljs-string">&#x27;genre&#x27;</span>],
num_rows: <span class="hljs-number">899</span>
})
test: <span class="hljs-built_in">Dataset</span>({
features: [<span class="hljs-string">&#x27;file&#x27;</span>, <span class="hljs-string">&#x27;audio&#x27;</span>, <span class="hljs-string">&#x27;genre&#x27;</span>],
num_rows: <span class="hljs-number">100</span>
})
})<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-lucyoo">Отлично, теперь, когда у нас есть обучающий и тестовый наборы, давайте посмотрим на один из аудиофайлов:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->gtzan[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">0</span>]<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->{
<span class="hljs-string">&quot;file&quot;</span>: <span class="hljs-string">&quot;~/.cache/huggingface/datasets/downloads/extracted/fa06ce46130d3467683100aca945d6deafb642315765a784456e1d81c94715a8/genres/pop/pop.00098.wav&quot;</span>,
<span class="hljs-string">&quot;audio&quot;</span>: {
<span class="hljs-string">&quot;path&quot;</span>: <span class="hljs-string">&quot;~/.cache/huggingface/datasets/downloads/extracted/fa06ce46130d3467683100aca945d6deafb642315765a784456e1d81c94715a8/genres/pop/pop.00098.wav&quot;</span>,
<span class="hljs-string">&quot;array&quot;</span>: array(
[
<span class="hljs-number">0.10720825</span>,
<span class="hljs-number">0.16122437</span>,
<span class="hljs-number">0.28585815</span>,
...,
<span class="hljs-number">-0.22924805</span>,
<span class="hljs-number">-0.20629883</span>,
<span class="hljs-number">-0.11334229</span>,
],
d<span class="hljs-keyword">type</span>=float32,
),
<span class="hljs-string">&quot;sampling_rate&quot;</span>: <span class="hljs-number">22050</span>,
},
<span class="hljs-string">&quot;genre&quot;</span>: <span class="hljs-number">7</span>,
}<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1x2mzu">Как мы видели в <a href="../chapter1/audio_data">Разделе 1</a>, аудиофайлы представлены в виде одномерных массивов NumPy,
где значение массива представляет собой амплитуду на заданном временном интервале. Для этих композиций частота дискретизации
составляет 22 050 Гц, то есть в секунду дискретизируется 22 050 значений амплитуды. Это необходимо учитывать при использовании
предварительно обученной модели с другой частотой дискретизации, самостоятельно преобразуя частоты дискретизации для обеспечения
их соответствия. Мы также видим, что жанр представлен в виде целого числа, или <em>class label</em>, то есть в том формате, в котором модель
будет делать свои предсказания. Воспользуемся методом <code>int2str()</code> функции <code>genre</code> для преобразования этих целых чисел в человекочитаемые имена:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->id2label_fn = gtzan[<span class="hljs-string">&quot;train&quot;</span>].features[<span class="hljs-string">&quot;genre&quot;</span>].int2str
id2label_fn(gtzan[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&quot;genre&quot;</span>])<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-symbol">&#x27;pop</span>&#x27;<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-vze5ek">Эта метка выглядит корректно, поскольку совпадает с именем аудиофайла. Теперь рассмотрим еще несколько примеров на примере Gradio для создания простого
интерфейса с API <code>Blocks</code>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> gradio <span class="hljs-keyword">as</span> gr
<span class="hljs-keyword">def</span> <span class="hljs-title function_">generate_audio</span>():
example = gtzan[<span class="hljs-string">&quot;train&quot;</span>].shuffle()[<span class="hljs-number">0</span>]
audio = example[<span class="hljs-string">&quot;audio&quot;</span>]
<span class="hljs-keyword">return</span> (
audio[<span class="hljs-string">&quot;sampling_rate&quot;</span>],
audio[<span class="hljs-string">&quot;array&quot;</span>],
), id2label_fn(example[<span class="hljs-string">&quot;genre&quot;</span>])
<span class="hljs-keyword">with</span> gr.Blocks() <span class="hljs-keyword">as</span> demo:
<span class="hljs-keyword">with</span> gr.Column():
<span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">4</span>):
audio, label = generate_audio()
output = gr.Audio(audio, label=label)
demo.launch(debug=<span class="hljs-literal">True</span>)<!-- HTML_TAG_END --></pre></div> <iframe src="https://course-demos-gtzan-samples.hf.space" frameborder="0" height="450" title="Gradio app" class="container p-0 flex-grow space-iframe" allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; document-domain; encrypted-media; fullscreen; geolocation; gyroscope; layout-animations; legacy-image-formats; magnetometer; microphone; midi; oversized-images; payment; picture-in-picture; publickey-credentials-get; sync-xhr; usb; vr ; wake-lock; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-downloads"></iframe> <p data-svelte-h="svelte-1yru15l">Из этих образцов мы, конечно, можем услышать разницу между жанрами, но может ли это сделать трансформер? Давайте обучим модель,
чтобы выяснить это! Для начала нам нужно найти подходящую для этой задачи предварительно обученную модель. Посмотрим, как это можно сделать.</p> <h2 class="relative group"><a id="выбор-предварительно-обученной-модели-для-классификации-звука" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#выбор-предварительно-обученной-модели-для-классификации-звука"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Выбор предварительно обученной модели для классификации звука</span></h2> <p data-svelte-h="svelte-1a2uy54">Для начала выберем подходящую предварительно обученную модель для классификации звука. В этой области предварительное обучение обычно проводится
на больших объемах немаркированных аудиоданных, используя такие наборы данных, как <a href="https://huggingface.co/datasets/librispeech_asr" rel="nofollow">LibriSpeech</a>
и <a href="https://huggingface.co/datasets/facebook/voxpopuli" rel="nofollow">Voxpopuli</a>. Лучший способ найти эти модели на Hugging Face Hub - использовать фильтр
“Audio Classification”, как описано в предыдущем разделе. Хотя такие модели, как Wav2Vec2 и HuBERT, очень популярны, мы будем использовать модель
под названием <em>DistilHuBERT</em>. Это гораздо более компактная (или <em>дистиллированная</em>) версия модели <a href="https://huggingface.co/docs/transformers/model_doc/hubert" rel="nofollow">HuBERT</a>,
которая обучается примерно на 73% быстрее, сохраняя при этом большую часть производительности.</p> <iframe src="https://autoevaluate-leaderboards.hf.space" frameborder="0" height="450" title="Gradio app" class="container p-0 flex-grow space-iframe" allow="accelerometer; ambient-light-sensor; autoplay; battery; camera; document-domain; encrypted-media; fullscreen; geolocation; gyroscope; layout-animations; legacy-image-formats; magnetometer; microphone; midi; oversized-images; payment; picture-in-picture; publickey-credentials-get; sync-xhr; usb; vr ; wake-lock; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-downloads"></iframe> <h2 class="relative group"><a id="от-аудио-к-машинному-обучению" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#от-аудио-к-машинному-обучению"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>От аудио к машинному обучению</span></h2> <h2 class="relative group"><a id="предварительная-обработка-данных" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#предварительная-обработка-данных"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Предварительная обработка данных</span></h2> <p data-svelte-h="svelte-o69lfv">Подобно токенизации в NLP, аудио- и речевые модели требуют, чтобы входные данные были закодированы в формате, который модель может обрабатывать.
В 🤗 Transformers преобразование звука во входной формат осуществляется с помощью <em>feature extractor</em> модели. Подобно токенизаторам, 🤗 Transformers
предоставляет удобный класс <code>AutoFeatureExtractor</code>, который может автоматически выбирать нужный экстрактор признаков для заданной модели. Для того
чтобы увидеть, как мы можем обрабатывать наши аудиофайлы, давайте начнем с инстанцирования экстрактора признаков для DistilHuBERT из предварительно
обученной контрольной точки:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoFeatureExtractor
model_id = <span class="hljs-string">&quot;ntu-spml/distilhubert&quot;</span>
feature_extractor = AutoFeatureExtractor.from_pretrained(
model_id, do_normalize=<span class="hljs-literal">True</span>, return_attention_mask=<span class="hljs-literal">True</span>
)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1nerkzy">Поскольку частота дискретизации модели и набора данных различна, перед передачей аудиофайла в программу извлечения признаков его необходимо
передискретизировать до 16 000 Гц. Для этого сначала нужно получить частоту дискретизации модели от экстрактора признаков:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->sampling_rate = feature_extractor.sampling_rate
sampling_rate<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->16000<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-144v3gc">Далее мы проводим повторную выборку набора данных, используя метод <code>cast_column()</code> и функцию <code>Audio</code> из 🤗 Datasets:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> datasets <span class="hljs-keyword">import</span> Audio
gtzan = gtzan.cast_column(<span class="hljs-string">&quot;audio&quot;</span>, Audio(sampling_rate=sampling_rate))<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-ild5sp">Теперь мы можем проверить первый сэмпл train-split нашего набора данных, чтобы убедиться, что он действительно находится
на частоте 16 000 Гц. При загрузке каждого сэмпла Datasets производит повторную дискретизацию аудиофайла “на лету”:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->gtzan[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">0</span>]<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->{
<span class="hljs-string">&quot;file&quot;</span>: <span class="hljs-string">&quot;~/.cache/huggingface/datasets/downloads/extracted/fa06ce46130d3467683100aca945d6deafb642315765a784456e1d81c94715a8/genres/pop/pop.00098.wav&quot;</span>,
<span class="hljs-string">&quot;audio&quot;</span>: {
<span class="hljs-string">&quot;path&quot;</span>: <span class="hljs-string">&quot;~/.cache/huggingface/datasets/downloads/extracted/fa06ce46130d3467683100aca945d6deafb642315765a784456e1d81c94715a8/genres/pop/pop.00098.wav&quot;</span>,
<span class="hljs-string">&quot;array&quot;</span>: array(
[
<span class="hljs-number">0.0873509</span>,
<span class="hljs-number">0.20183384</span>,
<span class="hljs-number">0.4790867</span>,
...,
<span class="hljs-number">-0.18743178</span>,
<span class="hljs-number">-0.23294401</span>,
<span class="hljs-number">-0.13517427</span>,
],
d<span class="hljs-keyword">type</span>=float32,
),
<span class="hljs-string">&quot;sampling_rate&quot;</span>: <span class="hljs-number">16000</span>,
},
<span class="hljs-string">&quot;genre&quot;</span>: <span class="hljs-number">7</span>,
}<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1espqj5">Отлично! Мы видим, что частота дискретизации была понижена до 16 кГц. Значения массива также отличаются, так как теперь на каждые 1,5 значения
амплитуды приходится примерно одно значение, которое мы имели раньше.</p> <p data-svelte-h="svelte-1533kvk">Отличительной особенностью моделей типа Wav2Vec2 и HuBERT является то, что они принимают на вход массив float, соответствующий исходной форме
речевого сигнала. В отличие от других моделей, например Whisper, в которых мы предварительно обрабатываем исходную форму звукового сигнала
до формата спектрограммы.</p> <p data-svelte-h="svelte-1nkdnts">Мы уже упоминали, что аудиоданные представлены в виде одномерного массива, поэтому они уже имеют правильный формат для чтения моделью
(набор непрерывных входов с дискретными временными шагами). Чтож, что именно делает экстрактор признаков?</p> <p data-svelte-h="svelte-1ilvnli">Итак, аудиоданные имеют правильный формат, но мы не наложили никаких ограничений на значения, которые они могут принимать. Для оптимальной работы
нашей модели необходимо, чтобы все входные данные находились в одном и том же динамическом диапазоне. Это позволит получить одинаковый диапазон активаций
и градиентов для наших образцов, что поможет обеспечить стабильность и сходимость в процессе обучения.</p> <p data-svelte-h="svelte-bjrgv">Для этого мы <em>нормализуем</em> наши аудиоданные, приводя каждую выборку к нулевому среднему и единичной дисперсии - этот процесс называется
<em>масштабированием признаков</em>. Именно эту нормализацию и выполняет наш экстрактор признаков!</p> <p data-svelte-h="svelte-1cang2c">Мы можем посмотреть, как работает экстрактор признаков, применив его к нашему первому аудиосэмплу. Сначала вычислим среднее значение и дисперсию
наших исходных аудиоданных:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
sample = gtzan[<span class="hljs-string">&quot;train&quot;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&quot;audio&quot;</span>]
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;Mean: <span class="hljs-subst">{np.mean(sample[<span class="hljs-string">&#x27;array&#x27;</span>]):<span class="hljs-number">.3</span>}</span>, Variance: <span class="hljs-subst">{np.var(sample[<span class="hljs-string">&#x27;array&#x27;</span>]):<span class="hljs-number">.3</span>}</span>&quot;</span>)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-attribute">Mean</span>: <span class="hljs-number">0</span>.<span class="hljs-number">000185</span>, Variance: <span class="hljs-number">0</span>.<span class="hljs-number">0493</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-bdmd7b">Видно, что среднее значение уже близко к нулю, но дисперсия ближе к 0,05. Если бы дисперсия для выборки была больше, это могло бы
вызвать проблемы с нашей моделью, так как динамический диапазон аудиоданных был бы очень мал и, следовательно, трудноразделим. Применим экстрактор
признаков и посмотрим, что получится на выходе:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->inputs = feature_extractor(sample[<span class="hljs-string">&quot;array&quot;</span>], sampling_rate=sample[<span class="hljs-string">&quot;sampling_rate&quot;</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;inputs keys: <span class="hljs-subst">{<span class="hljs-built_in">list</span>(inputs.keys())}</span>&quot;</span>)
<span class="hljs-built_in">print</span>(
<span class="hljs-string">f&quot;Mean: <span class="hljs-subst">{np.mean(inputs[<span class="hljs-string">&#x27;input_values&#x27;</span>]):<span class="hljs-number">.3</span>}</span>, Variance: <span class="hljs-subst">{np.var(inputs[<span class="hljs-string">&#x27;input_values&#x27;</span>]):<span class="hljs-number">.3</span>}</span>&quot;</span>
)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-attribute">inputs</span> keys:<span class="hljs-meta"> [&#x27;input_values&#x27;, &#x27;attention_mask&#x27;]</span>
<span class="hljs-attribute">Mean</span>: -<span class="hljs-number">4</span>.<span class="hljs-number">53</span>e-<span class="hljs-number">09</span>, Variance: <span class="hljs-number">1</span>.<span class="hljs-number">0</span><!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-dtx73j">Отлично! Наш экстрактор признаков возвращает словарь, состоящий из двух массивов: <code>input_values</code> and <code>attention_mask</code>. <code>input_values</code>
это предварительно обработанные входные аудиоданные, которые мы передадим в модель HuBERT. <a href="https://huggingface.co/docs/transformers/glossary#attention-mask" rel="nofollow"><code>attention_mask</code></a>
используется, когда мы обрабатываем <em>batch</em> аудиовходов одновременно - она используется для того, чтобы сообщить модели, где
у нас есть входы разной длины.</p> <p data-svelte-h="svelte-u78uom">Мы видим, что среднее значение теперь очень сильно приближается к нулю, а дисперсия - к единице! Именно в таком виде мы хотим получить
наши аудиосэмплы перед подачей их в модель HuBERT.</p> <blockquote class="warning"><p data-svelte-h="svelte-5u7qtl">Обратите внимание, как мы передали частоту дискретизации наших аудиоданных нашему экстрактору признаков. Это хорошая практика, так как
экстрактор признаков выполняет проверку под капотом, чтобы убедиться, что частота дискретизации наших аудиоданных соответствует частоте
дискретизации, ожидаемой моделью. Если частота дискретизации аудиоданных не совпадает с частотой дискретизации нашей модели, то необходимо
увеличить или уменьшить частоту дискретизации аудиоданных до нужной.</p></blockquote> <p data-svelte-h="svelte-jgv1ot">Отлично, теперь мы знаем, как обрабатывать наши ресэмплированные аудиофайлы, осталось определить функцию, которую мы можем применить ко всем
примерам в наборе данных. Поскольку мы ожидаем, что длина аудиоклипов будет составлять 30 секунд, мы также будем обрезать все более длинные клипы,
используя аргументы <code>max_length</code> и <code>truncation</code> в экстракторе признаков следующим образом:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->max_duration = <span class="hljs-number">30.0</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">preprocess_function</span>(<span class="hljs-params">examples</span>):
audio_arrays = [x[<span class="hljs-string">&quot;array&quot;</span>] <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> examples[<span class="hljs-string">&quot;audio&quot;</span>]]
inputs = feature_extractor(
audio_arrays,
sampling_rate=feature_extractor.sampling_rate,
max_length=<span class="hljs-built_in">int</span>(feature_extractor.sampling_rate * max_duration),
truncation=<span class="hljs-literal">True</span>,
return_attention_mask=<span class="hljs-literal">True</span>,
)
<span class="hljs-keyword">return</span> inputs<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1osq08i">Определив эту функцию, мы можем применить ее к набору данных с помощью метода <a href="https://huggingface.co/docs/datasets/v2.14.0/en/package_reference/main_classes#datasets.Dataset.map" rel="nofollow"><code>map()</code></a>.
Метод <code>.map()</code> поддерживает работу с пакетами сэмплов, что мы и сделаем, установив <code>batched=True</code>. По умолчанию размер
пакета составляет 1000, но мы уменьшим его до 100, чтобы пиковая оперативная память оставалась в разумных пределах для бесплатного уровня Google Colab:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->gtzan_encoded = gtzan.<span class="hljs-built_in">map</span>(
preprocess_function,
remove_columns=[<span class="hljs-string">&quot;audio&quot;</span>, <span class="hljs-string">&quot;file&quot;</span>],
batched=<span class="hljs-literal">True</span>,
batch_size=<span class="hljs-number">100</span>,
num_proc=<span class="hljs-number">1</span>,
)
gtzan_encoded<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->DatasetDict({
train: <span class="hljs-built_in">Dataset</span>({
features: [<span class="hljs-string">&#x27;genre&#x27;</span>, <span class="hljs-string">&#x27;input_values&#x27;</span>,<span class="hljs-string">&#x27;attention_mask&#x27;</span>],
num_rows: <span class="hljs-number">899</span>
})
test: <span class="hljs-built_in">Dataset</span>({
features: [<span class="hljs-string">&#x27;genre&#x27;</span>, <span class="hljs-string">&#x27;input_values&#x27;</span>,<span class="hljs-string">&#x27;attention_mask&#x27;</span>],
num_rows: <span class="hljs-number">100</span>
})
})<!-- HTML_TAG_END --></pre></div> <blockquote class="warning">Если при выполнении приведенного выше кода оперативная память устройства будет исчерпана, можно настроить параметры пакетной обработки,
чтобы уменьшить пиковое потребление оперативной памяти. В частности, можно модифицировать следующие два аргумента:
* `batch_size`: по умолчанию 1000, но выше было установлено значение 100. Попробуйте еще раз уменьшить в 2 раза до 50
* `writer_batch_size`: по умолчанию равен 1000. Попробуйте уменьшить его до 500, а если это не сработает, то уменьшите его еще раз в 2 раза до 250</blockquote> <p data-svelte-h="svelte-u8vr1o">Для упрощения обучения мы удалили из набора данных столбцы <code>audio</code> и <code>file</code>. Столбец <code>input_values</code> содержит закодированные аудиофайлы,
<code>attention_mask</code> - двоичную маску из значений 0/1, указывающую на то, куда мы добавили входной аудиосигнал, а столбец <code>genre</code> - соответствующие
метки (или цели). Для того чтобы <code>Trainer</code> мог обрабатывать метки классов, необходимо переименовать колонку <code>genre</code> в <code>label</code>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->gtzan_encoded = gtzan_encoded.rename_column(<span class="hljs-string">&quot;genre&quot;</span>, <span class="hljs-string">&quot;label&quot;</span>)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-kjj8ln">Наконец, нам необходимо получить отображения меток из набора данных. Это отображение позволит нам перейти от целочисленных идентификаторов (например, <code>7</code>)
к человекочитаемым меткам классов (например, <code>&quot;поп&quot;</code>) и обратно. Таким образом, мы можем преобразовать целочисленное предсказание id нашей модели в человекочитаемый формат,
что позволит нам использовать модель в любом последующем приложении. Для этого можно использовать метод <code>int2str()</code> следующим образом:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->id2label = {
<span class="hljs-built_in">str</span>(i): id2label_fn(i)
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(gtzan_encoded[<span class="hljs-string">&quot;train&quot;</span>].features[<span class="hljs-string">&quot;label&quot;</span>].names))
}
label2id = {v: k <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> id2label.items()}
id2label[<span class="hljs-string">&quot;7&quot;</span>]<!-- HTML_TAG_END --></pre></div> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-symbol">&#x27;pop</span>&#x27;<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1cjirp7">Итак, у нас есть набор данных, готовый к обучению! Давайте рассмотрим, как можно обучить модель на этом наборе данных.</p> <h2 class="relative group"><a id="дообучение-модели" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#дообучение-модели"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Дообучение модели</span></h2> <p data-svelte-h="svelte-1pzfvz0">Для дообучения модели мы воспользуемся классом <code>Trainer</code> из раздела 🤗 Transformers. Как мы уже видели в других
главах, <code>Trainer</code> - это высокоуровневый API, предназначенный для работы с наиболее распространенными сценариями обучения.
В данном случае мы будем использовать <code>Trainer</code> для дообучения модели на GTZAN. Для этого сначала нужно загрузить модель для данной задачи.
Для этого мы можем использовать класс <code>AutoModelForAudioClassification</code>, который автоматически добавит соответствующую классификационную голову
в нашу предварительно обученную модель DistilHuBERT. Давайте перейдем к инстанцированию модели:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForAudioClassification
num_labels = <span class="hljs-built_in">len</span>(id2label)
model = AutoModelForAudioClassification.from_pretrained(
model_id,
num_labels=num_labels,
label2id=label2id,
id2label=id2label,
)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1nmut3e">Мы настоятельно рекомендуем во время тренировок загружать контрольные точки моделей непосредственно на <a href="https://huggingface.co/" rel="nofollow">Hugging Face Hub</a>.
Hugging Face Hub предоставляет:</p> <ul data-svelte-h="svelte-uneh2j"><li>Встроенный контроль версий: вы можете быть уверены, что ни одна контрольная точка модели не будет потеряна в процессе обучения.</li> <li>Журналы Tensorboard: отслеживание важных показателей в процессе обучения.</li> <li>Карты моделей: документирование того, что делает модель, и предполагаемых вариантов ее использования.</li> <li>Сообщество: простой способ обмена информацией и сотрудничества с сообществом! 🤗</li></ul> <p data-svelte-h="svelte-1qq1ju9">Связать ноутбук с Hugging Face Hub очень просто - для этого достаточно ввести аутентификационный токен при появлении соответствующего запроса.
Найдите свой токен аутентификации <a href="https://huggingface.co/settings/tokens" rel="nofollow">здесь</a>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> huggingface_hub <span class="hljs-keyword">import</span> notebook_login
notebook_login()<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->Login successful
Your token has been saved to /root/.huggingface/token<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1a45kub">Следующим шагом является определение аргументов обучения, включая размер пакета, шаги накопления градиента, количество
эпох обучения и скорость обучения:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> TrainingArguments
model_name = model_id.split(<span class="hljs-string">&quot;/&quot;</span>)[-<span class="hljs-number">1</span>]
batch_size = <span class="hljs-number">8</span>
gradient_accumulation_steps = <span class="hljs-number">1</span>
num_train_epochs = <span class="hljs-number">10</span>
training_args = TrainingArguments(
<span class="hljs-string">f&quot;<span class="hljs-subst">{model_name}</span>-finetuned-gtzan&quot;</span>,
evaluation_strategy=<span class="hljs-string">&quot;epoch&quot;</span>,
save_strategy=<span class="hljs-string">&quot;epoch&quot;</span>,
learning_rate=<span class="hljs-number">5e-5</span>,
per_device_train_batch_size=batch_size,
gradient_accumulation_steps=gradient_accumulation_steps,
per_device_eval_batch_size=batch_size,
num_train_epochs=num_train_epochs,
warmup_ratio=<span class="hljs-number">0.1</span>,
logging_steps=<span class="hljs-number">5</span>,
load_best_model_at_end=<span class="hljs-literal">True</span>,
metric_for_best_model=<span class="hljs-string">&quot;accuracy&quot;</span>,
fp16=<span class="hljs-literal">True</span>,
push_to_hub=<span class="hljs-literal">True</span>,
)<!-- HTML_TAG_END --></pre></div> <blockquote class="warning">Здесь мы установили значение `push_to_hub=True`, чтобы включить автоматическую загрузку настроенных контрольных точек во время обучения.
Если вы не хотите, чтобы ваши контрольные точки загружались на Hugging Face Hub, вы можете установить значение `False`.</blockquote> <p data-svelte-h="svelte-14zk2p8">Последнее, что нам необходимо сделать, это определить метрики. Поскольку набор данных сбалансирован, в качестве метрики мы будем использовать
accuracy и загружать ее с помощью библиотеки 🤗 Evaluate:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">import</span> evaluate
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
metric = evaluate.load(<span class="hljs-string">&quot;accuracy&quot;</span>)
<span class="hljs-keyword">def</span> <span class="hljs-title function_">compute_metrics</span>(<span class="hljs-params">eval_pred</span>):
<span class="hljs-string">&quot;&quot;&quot;Computes accuracy on a batch of predictions&quot;&quot;&quot;</span>
predictions = np.argmax(eval_pred.predictions, axis=<span class="hljs-number">1</span>)
<span class="hljs-keyword">return</span> metric.compute(predictions=predictions, references=eval_pred.label_ids)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-1e9dprm">Теперь у нас есть все необходимые компоненты! Давайте инстанцируем <code>Trainer</code> и обучим модель:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> Trainer
trainer = Trainer(
model,
training_args,
train_dataset=gtzan_encoded[<span class="hljs-string">&quot;train&quot;</span>],
eval_dataset=gtzan_encoded[<span class="hljs-string">&quot;test&quot;</span>],
tokenizer=feature_extractor,
compute_metrics=compute_metrics,
)
trainer.train()<!-- HTML_TAG_END --></pre></div> <blockquote class="warning">В зависимости от используемого графического процессора, при запуске обучения возможно возникновение ошибки CUDA `&quot;out-of-memory&quot;`.
В этом случае можно уменьшать `batch_size` постепенно в 2 раза, а для компенсации использовать [`gradient_accumulation_steps`](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.gradient_accumulation_steps)</blockquote> <p data-svelte-h="svelte-1mvdyro"><strong>Output:</strong></p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->|<span class="hljs-string"> Training Loss </span>|<span class="hljs-string"> Epoch </span>|<span class="hljs-string"> Step </span>|<span class="hljs-string"> Validation Loss </span>|<span class="hljs-string"> Accuracy </span>|
|<span class="hljs-string">:-------------:</span>|<span class="hljs-string">:-----:</span>|<span class="hljs-string">:----:</span>|<span class="hljs-string">:---------------:</span>|<span class="hljs-string">:--------:</span>|
|<span class="hljs-string"> 1.7297 </span>|<span class="hljs-string"> 1.0 </span>|<span class="hljs-string"> 113 </span>|<span class="hljs-string"> 1.8011 </span>|<span class="hljs-string"> 0.44 </span>|
|<span class="hljs-string"> 1.24 </span>|<span class="hljs-string"> 2.0 </span>|<span class="hljs-string"> 226 </span>|<span class="hljs-string"> 1.3045 </span>|<span class="hljs-string"> 0.64 </span>|
|<span class="hljs-string"> 0.9805 </span>|<span class="hljs-string"> 3.0 </span>|<span class="hljs-string"> 339 </span>|<span class="hljs-string"> 0.9888 </span>|<span class="hljs-string"> 0.7 </span>|
|<span class="hljs-string"> 0.6853 </span>|<span class="hljs-string"> 4.0 </span>|<span class="hljs-string"> 452 </span>|<span class="hljs-string"> 0.7508 </span>|<span class="hljs-string"> 0.79 </span>|
|<span class="hljs-string"> 0.4502 </span>|<span class="hljs-string"> 5.0 </span>|<span class="hljs-string"> 565 </span>|<span class="hljs-string"> 0.6224 </span>|<span class="hljs-string"> 0.81 </span>|
|<span class="hljs-string"> 0.3015 </span>|<span class="hljs-string"> 6.0 </span>|<span class="hljs-string"> 678 </span>|<span class="hljs-string"> 0.5411 </span>|<span class="hljs-string"> 0.83 </span>|
|<span class="hljs-string"> 0.2244 </span>|<span class="hljs-string"> 7.0 </span>|<span class="hljs-string"> 791 </span>|<span class="hljs-string"> 0.6293 </span>|<span class="hljs-string"> 0.78 </span>|
|<span class="hljs-string"> 0.3108 </span>|<span class="hljs-string"> 8.0 </span>|<span class="hljs-string"> 904 </span>|<span class="hljs-string"> 0.5857 </span>|<span class="hljs-string"> 0.81 </span>|
|<span class="hljs-string"> 0.1644 </span>|<span class="hljs-string"> 9.0 </span>|<span class="hljs-string"> 1017 </span>|<span class="hljs-string"> 0.5355 </span>|<span class="hljs-string"> 0.83 </span>|
|<span class="hljs-string"> 0.1198 </span>|<span class="hljs-string"> 10.0 </span>|<span class="hljs-string"> 1130 </span>|<span class="hljs-string"> 0.5716 </span>|<span class="hljs-string"> 0.82 </span>|<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-cpfaw0">Обучение займет примерно 1 час в зависимости от вашего GPU или выделенного для Google Colab. Наша лучшая доля верных ответов
составляет 83% - неплохо для 10 эпох с 899 примерами обучающих данных! Конечно, мы могли бы улучшить этот результат,
тренируясь на большем количестве эпох, используя методы регуляризации, такие как <em>dropout</em>, или разбивая каждый аудиопример
на сегменты по 30 и 15 секунд, чтобы использовать более эффективную стратегию предварительной обработки данных.</p> <p data-svelte-h="svelte-1rsw2y7">Большой вопрос, как это соотносится с другими системами классификации музыки 🤔
Для этого мы можем просмотреть <a href="https://huggingface.co/spaces/autoevaluate/leaderboards?dataset=marsyas%2Fgtzan&only_verified=0&task=audio-classification&config=all&split=train&metric=accuracy" rel="nofollow">autoevaluate leaderboard</a>,
таблицу лидеров, которая классифицирует модели по языку и набору данных, а затем ранжирует их по accuracy.</p> <p data-svelte-h="svelte-1c0oob5">Мы можем автоматически отправить нашу контрольную точку в таблицу лидеров при передаче результатов обучения в
Hugging Face Hub - для этого достаточно задать соответствующие аргументы ключевых слов (kwargs). Вы можете изменить эти значения
в соответствии с набором данных, языком и названием модели:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->kwargs = {
<span class="hljs-string">&quot;dataset_tags&quot;</span>: <span class="hljs-string">&quot;marsyas/gtzan&quot;</span>,
<span class="hljs-string">&quot;dataset&quot;</span>: <span class="hljs-string">&quot;GTZAN&quot;</span>,
<span class="hljs-string">&quot;model_name&quot;</span>: <span class="hljs-string">f&quot;<span class="hljs-subst">{model_name}</span>-finetuned-gtzan&quot;</span>,
<span class="hljs-string">&quot;finetuned_from&quot;</span>: model_id,
<span class="hljs-string">&quot;tasks&quot;</span>: <span class="hljs-string">&quot;audio-classification&quot;</span>,
}<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-8rdxg2">Теперь результаты обучения можно загрузить в Hugging Face Hub. Для этого выполните команду <code>.push_to_hub</code>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START -->trainer.push_to_hub(**kwargs)<!-- HTML_TAG_END --></pre></div> <p data-svelte-h="svelte-d6ovka">При этом журналы обучения и веса моделей будут сохранены под именем <code>&quot;your-username/distilhubert-finetuned-gtzan&quot;</code>. Для примера
посмотрите загрузку по адресу <a href="https://huggingface.co/sanchit-gandhi/distilhubert-finetuned-gtzan" rel="nofollow"><code>&quot;sanchit-gandhi/distilhubert-finetuned-gtzan&quot;</code></a>.</p> <h2 class="relative group"><a id="поделиться-моделью" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#поделиться-моделью"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Поделиться моделью</span></h2> <p data-svelte-h="svelte-1no1mlt">Теперь вы можете поделиться этой моделью со всеми желающими, воспользовавшись ссылкой на Hub. Они могут загрузить его с идентификатором <code>&quot;your-username/distilhubert-finetuned-gtzan&quot;</code>
непосредственно в <code>pipeline()</code>. Например, для загрузки точно настроенной контрольной точки <a href="https://huggingface.co/sanchit-gandhi/distilhubert-finetuned-gtzan" rel="nofollow"><code>&quot;sanchit-gandhi/distilhubert-finetuned-gtzan&quot;</code></a>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg class="" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg> <div class="absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0"><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent; "></div> Copied</div></button></div> <pre class=""><!-- HTML_TAG_START --><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline
pipe = pipeline(
<span class="hljs-string">&quot;audio-classification&quot;</span>, model=<span class="hljs-string">&quot;sanchit-gandhi/distilhubert-finetuned-gtzan&quot;</span>
)<!-- HTML_TAG_END --></pre></div> <h2 class="relative group"><a id="заключение" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#заключение"><span><svg class="" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg></span></a> <span>Заключение</span></h2> <p data-svelte-h="svelte-h7sf2d">В этом разделе мы рассмотрели пошаговое руководство по тонкой настройке модели DistilHuBERT для классификации музыки. Хотя мы
сосредоточились на задаче классификации музыки и на наборе данных GTZAN, представленные здесь шаги применимы в более общем случае
к любой задаче классификации звука - тот же сценарий может быть использован для задач классификации звука разговорного языка,
таких как выделение ключевых слов или идентификация языка. Вам просто нужно поменять набор данных на тот, который соответствует
интересующей вас задаче! Если вы заинтересованы в тонкой настройке других моделей Hugging Face Hub для классификации звука,
мы рекомендуем вам ознакомиться с другими <a href="https://github.com/huggingface/transformers/tree/main/examples/pytorch/audio-classification" rel="nofollow">примерами</a>
в 🤗 репозитории Transformers.</p> <p data-svelte-h="svelte-17a7zxh">В следующем разделе мы возьмем модель, которую вы только что отладили, и создадим демонстрационный образец классификации музыки, который
вы сможете опубликовать на Hugging Face Hub.</p> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/audio-transformers-course/blob/main/chapters/ru/chapter4/fine-tuning.mdx" target="_blank"><svg class="mr-1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M31,16l-7,7l-1.41-1.41L28.17,16l-5.58-5.59L24,9l7,7z"></path><path d="M1,16l7-7l1.41,1.41L3.83,16l5.58,5.59L8,23l-7-7z"></path><path d="M12.419,25.484L17.639,6.552l1.932,0.518L14.351,26.002z"></path></svg> <span data-svelte-h="svelte-zjs2n5"><span class="underline">Update</span> on GitHub</span></a> <p></p>
<script>
{
__sveltekit_1nifglt = {
assets: "/docs/audio-course/pr_227/ru",
base: "/docs/audio-course/pr_227/ru",
env: {}
};
const element = document.currentScript.parentElement;
const data = [null,null];
Promise.all([
import("/docs/audio-course/pr_227/ru/_app/immutable/entry/start.fc7d9a04.js"),
import("/docs/audio-course/pr_227/ru/_app/immutable/entry/app.0acf0b9e.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 24],
data,
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
110 kB
·
Xet hash:
cd05972422b353b87e8a06c3933ed2b725df04d0661acc039393d85745514006

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.