如何用 TensorFlow 教機(jī)器人作曲?秘訣原來(lái)是這樣
今天想來(lái)看看 AI 是怎樣作曲的。
本文會(huì)用 TensorFlow 來(lái)寫(xiě)一個(gè)音樂(lè)生成器。
當(dāng)你對(duì)一個(gè)機(jī)器人說(shuō): 我想要一種能夠表達(dá)出希望和奇跡的歌曲時(shí),發(fā)生了什么呢?
計(jì)算機(jī)會(huì)首先把你的語(yǔ)音轉(zhuǎn)化成文字,并且提取出關(guān)鍵字,轉(zhuǎn)化成詞向量。然后會(huì)用一些打過(guò)標(biāo)簽的音樂(lè)的數(shù)據(jù),這些標(biāo)簽就是人類(lèi)的各種情感。接著通過(guò)在這些數(shù)據(jù)上面訓(xùn)練一個(gè)模型,模型訓(xùn)練好后就可以生成符合要求關(guān)鍵詞的音樂(lè)。程序最終的輸出結(jié)果就是一些和弦,他會(huì)選擇最貼近主人所要求的情感關(guān)鍵詞的一些和弦來(lái)輸出。當(dāng)然你不只是可以聽(tīng),也可以作為創(chuàng)作的參考,這樣就可以很容易地創(chuàng)作音樂(lè),即使你還沒(méi)有做到刻意練習(xí)1萬(wàn)小時(shí)。
機(jī)器學(xué)習(xí)其實(shí)是為了擴(kuò)展我們的大腦,擴(kuò)展我們的能力。
DeepMind 發(fā)表了一篇論文,叫做WaveNet, 這篇論文介紹了音樂(lè)生成和文字轉(zhuǎn)語(yǔ)音的藝術(shù)。
通常來(lái)講,語(yǔ)音生成模型是串聯(lián)。這意味著如果我們想從一些文字的樣本中來(lái)生成語(yǔ)音的話(huà),是需要非常大量的語(yǔ)音片段的數(shù)據(jù)庫(kù),通過(guò)截取它們的一部分,并且再重新組裝到一起,來(lái)組成一個(gè)完整的句子。
生成音樂(lè)也是同樣的道理,但是它有一個(gè)很大的難點(diǎn):就是當(dāng)你把一些靜止的組件組合到一起的時(shí)候,生成聲音需要很自然,并且還要有情感,這一點(diǎn)是非常難的。
一種理想的方式是,我們可以把所有生成音樂(lè)所需要的信息存到模型的參數(shù)里面。也就是那篇論文里講的事情。
我們并不需要把輸出結(jié)果傳給信號(hào)處理算法來(lái)得到語(yǔ)音信號(hào),而是直接處理語(yǔ)音信號(hào)的波。
他們用的模型是 CNN。這個(gè)模型的每一個(gè)隱藏層中,每個(gè)擴(kuò)張因子,可以互聯(lián),并呈指數(shù)型的增長(zhǎng)。每一步生成的樣本,都會(huì)被重新投入網(wǎng)絡(luò)中,并且用于產(chǎn)生下一步。
我們可以來(lái)看一下這個(gè)模型的圖。輸入的數(shù)據(jù),是一個(gè)單獨(dú)的節(jié)點(diǎn),它作為粗糙的音波,首先需要進(jìn)行一下預(yù)處理,以便于進(jìn)行下面的操作。
接著我們對(duì)它進(jìn)行編碼,來(lái)產(chǎn)生一個(gè) Tensor,這個(gè) Tensor 有一些 sample 和 channel。然后把它投入到 CNN 網(wǎng)絡(luò)的***層中。這一層會(huì)產(chǎn)生 channel 的數(shù)量,為了進(jìn)行更簡(jiǎn)單地處理。然后把所有輸出的結(jié)果組合在一起,并且增加它的維度。再把維度增加到原來(lái)的 channel 的數(shù)量。把這個(gè)結(jié)果投入到損失函數(shù)中,來(lái)衡量我們的模型訓(xùn)練的如何。***,這個(gè)結(jié)果會(huì)被再次投入到網(wǎng)絡(luò)中,來(lái)生成下一個(gè)時(shí)間點(diǎn)所需要的音波數(shù)據(jù)。重復(fù)這個(gè)過(guò)程就可以生成更多的語(yǔ)音。這個(gè)網(wǎng)絡(luò)很大,在他們的 GPU 集群上需要花費(fèi)九十分鐘,并且僅僅只能生成一秒的音頻。
接下來(lái)我們會(huì)用一個(gè)更簡(jiǎn)單的模型在 TensorFlow 上來(lái)實(shí)現(xiàn)一個(gè)音頻生成器。
1.引入packaGEs:
數(shù)據(jù)科學(xué)包 Numpy ,數(shù)據(jù)分析包 Pandas,tqdm 可以生成一個(gè)進(jìn)度條,顯示訓(xùn)練時(shí)的進(jìn)度。
- 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
我們會(huì)用到一種神經(jīng)網(wǎng)絡(luò)的模型 RBM-Restricted Boltzmann Machine 作為生成模型。
它是一個(gè)兩層網(wǎng)絡(luò):***層是可見(jiàn)的,第二層是隱藏層。同一層的節(jié)點(diǎn)之間沒(méi)有聯(lián)系,不同層之間的節(jié)點(diǎn)相互連接。每一個(gè)節(jié)點(diǎn)都要決定它是否需要將已經(jīng)接收到的數(shù)據(jù)發(fā)送到下一層,而這個(gè)決定是隨機(jī)的。
2.定義超參數(shù):
先定義需要模型生成的 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 ,可見(jiàn)層和隱藏層的大小。
- 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
訓(xùn)練次數(shù),批量處理的大小,還有學(xué)習(xí)率。
- 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
3.定義變量:
x 是投入網(wǎng)絡(luò)的數(shù)據(jù)
w 用來(lái)存儲(chǔ)權(quán)重矩陣,或者叫做兩層之間的關(guān)系
此外還需要兩種 bias,一個(gè)是隱藏層的 bh,一個(gè)是可見(jiàn)層的 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 weightMATrix 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 從輸入數(shù)據(jù) x 中建立樣本,以及隱藏層的樣本:
gibbs_sample 是一種可以從多重概率分布中提取樣本的算法。
它可以生成一個(gè)統(tǒng)計(jì)模型,其中,每一個(gè)狀態(tài)都依賴(lài)于前一個(gè)狀態(tài),并且隨機(jī)地生成符合分布的樣本。
- #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))
4.更新變量:
- size_bt = tf. CA
- st(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)]
5.運(yùn)行 Graph 算法圖:
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 每首歌,以便于相應(yīng)的向量表示可以更好地被用于訓(xùn)練模型。
- 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.接下來(lái)就來(lái)訓(xùn)練 RBM 模型,一次訓(xùn)練一個(gè)樣本
- for i in range(1, len(song), batch_size):
- tr_x = song[i:i+batch_size]
- sess.run(updt, feed_dict={x: tr_x})
模型完全訓(xùn)練好后,就可以用來(lái)生成 music 了。
3.需要訓(xùn)練 Gibbs chain
其中的 visible nodes 先初始化為0,來(lái)生成一些樣本。
然后把向量 reshape 成更好的格式來(lái) 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 來(lái)參數(shù)化地生成音波,
用 RBM 可以很容易地根據(jù)訓(xùn)練數(shù)據(jù)生成音頻樣本,
Gibbs 算法可以基于概率分布幫我們得到訓(xùn)練樣本。
***送上Siraj 的原始視頻和源代碼鏈接。