0
雷鋒網按:本文作者楊熹,原文載于作者個人博客,雷鋒網已獲授權。
今天想來看看 AI 是怎樣作曲的。
本文會用 TensorFlow 來寫一個音樂生成器。
當你對一個機器人說:我想要一種能夠表達出希望和奇跡的歌曲時,發(fā)生了什么呢?
計算機會首先把你的語音轉化成文字,并且提取出關鍵字,轉化成詞向量。然后會用一些打過標簽的音樂的數據,這些標簽就是人類的各種情感。接著通過在這些數據上面訓練一個模型,模型訓練好后就可以生成符合要求關鍵詞的音樂。程序最終的輸出結果就是一些和弦,他會選擇最貼近主人所要求的情感關鍵詞的一些和弦來輸出。當然你不只是可以聽,也可以作為創(chuàng)作的參考,這樣就可以很容易地創(chuàng)作音樂,即使你還沒有做到刻意練習1萬小時。
機器學習其實是為了擴展我們的大腦,擴展我們的能力。
DeepMind 發(fā)表了一篇論文,叫做 WaveNet, 這篇論文介紹了音樂生成和文字轉語音的藝術。
通常來講,語音生成模型是串聯(lián)。這意味著如果我們想從一些文字的樣本中來生成語音的話,是需要非常大量的語音片段的數據庫,通過截取它們的一部分,并且再重新組裝到一起,來組成一個完整的句子。
生成音樂也是同樣的道理,但是它有一個很大的難點:就是當你把一些靜止的組件組合到一起的時候,生成聲音需要很自然,并且還要有情感,這一點是非常難的。
一種理想的方式是,我們可以把所有生成音樂所需要的信息存到模型的參數里面。也就是那篇論文里講的事情。
我們并不需要把輸出結果傳給信號處理算法來得到語音信號,而是直接處理語音信號的波。
他們用的模型是 CNN。這個模型的每一個隱藏層中,每個擴張因子,可以互聯(lián),并呈指數型的增長。每一步生成的樣本,都會被重新投入網絡中,并且用于產生下一步。
我們可以來看一下這個模型的圖。輸入的數據,是一個單獨的節(jié)點,它作為粗糙的音波,首先需要進行一下預處理,以便于進行下面的操作。
接著我們對它進行編碼,來產生一個 Tensor,這個 Tensor 有一些 sample 和 channel。然后把它投入到 CNN 網絡的第一層中。這一層會產生 channel 的數量,為了進行更簡單地處理。然后把所有輸出的結果組合在一起,并且增加它的維度。再把維度增加到原來的 channel 的數量。把這個結果投入到損失函數中,來衡量我們的模型訓練的如何。最后,這個結果會被再次投入到網絡中,來生成下一個時間點所需要的音波數據。重復這個過程就可以生成更多的語音。這個網絡很大,在他們的 GPU 集群上需要花費九十分鐘,并且僅僅只能生成一秒的音頻。
接下來我們會用一個更簡單的模型在 TensorFlow 上來實現(xiàn)一個音頻生成器。
數據科學包 Numpy ,數據分析包 Pandas,tqdm 可以生成一個進度條,顯示訓練時的進度。
import numpy as np
import pandas as pd
import msgpack
import glob
import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from tqdm import tqdm
import midi_manipulation
我們會用到一種神經網絡的模型 RBM-Restricted Boltzmann Machine 作為生成模型。
它是一個兩層網絡:第一層是可見的,第二層是隱藏層。同一層的節(jié)點之間沒有聯(lián)系,不同層之間的節(jié)點相互連接。每一個節(jié)點都要決定它是否需要將已經接收到的數據發(fā)送到下一層,而這個決定是隨機的。
先定義需要模型生成的 note 的 range
lowest_note = midi_manipulation.lowerBound #the index of the lowest note on the piano roll
highest_note = midi_manipulation.upperBound #the index of the highest note on the piano roll
note_range = highest_note-lowest_note #the note range
接著需要定義 timestep ,可見層和隱藏層的大小。
num_timesteps = 15 #This is the number of timesteps that we will create at a time
n_visible = 2*note_range*num_timesteps #This is the size of the visible layer.
n_hidden = 50 #This is the size of the hidden layer
訓練次數,批量處理的大小,還有學習率。
num_epochs = 200 #The number of training epochs that we are going to run. For each epoch we go through the entire data set.
batch_size = 100 #The number of training examples that we are going to send through the RBM at a time.
lr = tf.constant(0.005, tf.float32) #The learning rate of our model
x 是投入網絡的數據
w 用來存儲權重矩陣,或者叫做兩層之間的關系
此外還需要兩種 bias,一個是隱藏層的 bh,一個是可見層的 bv
x = tf.placeholder(tf.float32, [None, n_visible], name="x") #The placeholder variable that holds our data
W = tf.Variable(tf.random_normal([n_visible, n_hidden], 0.01), name="W") #The weight matrix that stores the edge weights
bh = tf.Variable(tf.zeros([1, n_hidden], tf.float32, name="bh")) #The bias vector for the hidden layer
bv = tf.Variable(tf.zeros([1, n_visible], tf.float32, name="bv")) #The bias vector for the visible layer
接著,用輔助方法 gibbs_sample 從輸入數據 x 中建立樣本,以及隱藏層的樣本:
gibbs_sample 是一種可以從多重概率分布中提取樣本的算法。
它可以生成一個統(tǒng)計模型,其中,每一個狀態(tài)都依賴于前一個狀態(tài),并且隨機地生成符合分布的樣本。
#The sample of x
x_sample = gibbs_sample(1)
#The sample of the hidden nodes, starting from the visible state of x
h = sample(tf.sigmoid(tf.matmul(x, W) + bh))
#The sample of the hidden nodes, starting from the visible state of x_sample
h_sample = sample(tf.sigmoid(tf.matmul(x_sample, W) + bh))
size_bt = tf.cast(tf.shape(x)[0], tf.float32)
W_adder = tf.mul(lr/size_bt, tf.sub(tf.matmul(tf.transpose(x), h), tf.matmul(tf.transpose(x_sample), h_sample)))
bv_adder = tf.mul(lr/size_bt, tf.reduce_sum(tf.sub(x, x_sample), 0, True))
bh_adder = tf.mul(lr/size_bt, tf.reduce_sum(tf.sub(h, h_sample), 0, True))
#When we do sess.run(updt), TensorFlow will run all 3 update steps
updt = [W.assign_add(W_adder), bv.assign_add(bv_adder), bh.assign_add(bh_adder)]
1.先初始化變量
with tf.Session() as sess:
#First, we train the model
#initialize the variables of the model
init = tf.initialize_all_variables()
sess.run(init)
首先需要 reshape 每首歌,以便于相應的向量表示可以更好地被用于訓練模型。
for epoch in tqdm(range(num_epochs)):
for song in songs:
#The songs are stored in a time x notes format. The size of each song is timesteps_in_song x 2*note_range
#Here we reshape the songs so that each training example is a vector with num_timesteps x 2*note_range elements
song = np.array(song)
song = song[:np.floor(song.shape[0]/num_timesteps)*num_timesteps]
song = np.reshape(song, [song.shape[0]/num_timesteps, song.shape[1]*num_timesteps])
2.接下來就來訓練 RBM 模型,一次訓練一個樣本
for i in range(1, len(song), batch_size):
tr_x = song[i:i+batch_size]
sess.run(updt, feed_dict={x: tr_x})
模型完全訓練好后,就可以用來生成 music 了。
3.需要訓練 Gibbs chain
其中的 visible nodes 先初始化為0,來生成一些樣本。
然后把向量 reshape 成更好的格式來 playback。
sample = gibbs_sample(1).eval(session=sess, feed_dict={x: np.zeros((10, n_visible))})
for i in range(sample.shape[0]):
if not any(sample[i,:]):
continue
#Here we reshape the vector to be time x notes, and then save the vector as a midi file
S = np.reshape(sample[i,:], (num_timesteps, 2*note_range))
4.最后,打印出生成的和弦
midi_manipulation.noteStateMatrixToMidi(S, "generated_chord_{}".format(i))1212
綜上,就是用 CNN 來參數化地生成音波,
用 RBM 可以很容易地根據訓練數據生成音頻樣本,
Gibbs 算法可以基于概率分布幫我們得到訓練樣本。
最后送上 Siraj 的原始視頻和源代碼鏈接:
視頻:https://www.youtube.com/watch?v=ZE7qWXX05T0&t=278s
源代碼:https://github.com/llSourcell/Music_Generator_Demo/blob/master/rbm_chords.py
從初級到高級,理論 + 實戰(zhàn),一站式深度了解 TensorFlow!
本課程面向深度學習開發(fā)者,講授如何利用 TensorFlow 解決圖像識別、文本分析等具體問題。課程跨度為 10 周,將從 TensorFlow 的原理與基礎實戰(zhàn)技巧開始,一步步教授學員如何在 TensorFlow 上搭建 CNN、自編碼、RNN、GAN 等模型,并最終掌握一整套基于 TensorFlow 做深度學習開發(fā)的專業(yè)技能。
兩名授課老師佟達、白發(fā)川身為 ThoughtWorks 的資深技術專家,具有豐富的大數據平臺搭建、深度學習系統(tǒng)開發(fā)項目經驗。
時間:每周二、四晚 20:00-21:00
開課時長:總學時 20 小時,分 10 周完成,每周 2 次,每次 1 小時
線上授課地址:http://www.mooc.ai/
雷鋒網相關文章:
在玩圖像分類和圖像分割?來挑戰(zhàn)基于 TensorFlow 的圖像注解生成!
教你從零開始在 TensorFlow 上搭建 RNN(完整代碼)!
雷峰網版權文章,未經授權禁止轉載。詳情見轉載須知。