您的位置:首頁>設計>正文

前端要完?人工智慧已經能實現自動編寫 HTML 和 CSS

本文轉載自:CSDN 資訊

【編者按】一個月前, 我們曾發表過一篇標題為《三年後, 人工智慧將徹底改變前端開發?》的文章, 其中介紹了一個彼時名列 GitHub 排行榜 TOP 1 的項目 —— Screenshot-to-code-in-Keras。

在這個專案中, 神經網路通過深度學習, 自動把設計稿變成 HTML 和 CSS 代碼, 同時其作者 Emil Wallner 表示, “三年後, 人工智慧將徹底改變前端開發”。

這個 Flag 一立, 即引起了國內外非常熱烈的討論, 有喜有憂, 有褒揚有反對。 對此, Emil Wallner 則以非常嚴謹的實踐撰寫了系列文章, 尤其是在《Turning Design Mockups Into Code With Deep Learning》一文中, 詳細分享了自己是如何根據 pix2code 等論文構建了一個強大的前端代碼生成模型, 並細講了其利用 LSTM 與 CNN 將設計原型編寫為 HTML 和 CSS 網站的過程。

以下為全文:

在未來三年內, 深度學習將改變前端開發, 它可以快速創建原型, 並降低軟體發展的門檻。

去年, 該領域取得了突破性的進展, 其中 Tony Beltramelli 發表了 pix2code 的論文[1], 而 Airbnb 則推出了sketch2code[2]。

目前, 前端開發自動化的最大障礙是計算能力。

但是, 現在我們可以使用深度學習的演算法, 以及合成的訓練資料, 探索人工前端開發的自動化。

本文中, 我們將展示如何訓練神經網路, 根據設計圖編寫基本的 HTML 和 CSS 代碼。 以下是該過程的簡要概述:

提供設計圖給經過訓練的神經網路

神經網路把設計圖轉化成 HTML 代碼

大圖請點:

https://blog.floydhub.com/generate_html_markupb6ceec69a7c9cfd447d188648049f2a4.gif

渲染畫面

我們將通過三次反覆運算建立這個神經網路。

首先, 我們建立一個簡化版, 掌握基礎結構。 第二個版本是 HTML, 我們將集中討論每個步驟的自動化, 並解釋神經網路的各層。 在最後一個版本——Boostrap 中, 我們將創建一個通用的模型來探索 LSTM 層。

你可以通過 Github[3] 和 FloydHub[4] 的 Jupyter notebook 訪問我們的代碼。 所有的 FloydHub notebook 都放在“floydhub”目錄下, 而 local 的東西都在“local”目錄下。

這些模型是根據 Beltramelli 的 pix2code 論文和 Jason Brownlee 的“圖像標注教程”[5]創建的。 代碼的編寫採用了 Python 和 Keras(TensorFlow 的上層框架)。

如果你剛剛接觸深度學習, 那麼我建議你先熟悉下 Python、反向傳播演算法、以及卷積神經網路。

你可以閱讀我之前發表的三篇文章:

開始學習深度學習的第一周[6]

通過程式設計探索深度學習發展史[7]

利用神經網路給黑白照片上色[8]

▌核心邏輯

我們的目標可以概括為:建立可以生成與設計圖相符的 HTML 及 CSS 代碼的神經網路。

在訓練神經網路的時候, 你可以給出幾個截圖以及相應的 HTML。

神經網路通過逐個預測與之匹配的 HTML 標籤進行學習。 在預測下一個標籤時, 神經網路會查看截圖以及到這個點為止的所有正確的 HTML 標籤。

下面的 Google Sheet 給出了一個簡單的訓練資料:

https://docs.google.com/spreadsheets/d/1xXwarcQZAHluorveZsACtXRdmNFbwGtN3WMNhcTdEyQ/edit?usp=sharing

當然, 還有其他方法[9]可以訓練神經網路, 但創建逐個單詞預測的模型是目前最普遍的做法, 所以在本教程中我們也使用這個方法。

請注意每次的預測都必須基於同一張截圖,所以如果神經網路需要預測 20 個單詞,那麼它需要查看同一張截圖 20 次。暫時先把神經網路的工作原理放到一邊,讓我們先瞭解一下神經網路的輸入和輸出。

讓我們先來看看“之前的 HTML 標籤”。假設我們需要訓練神經網路預測這樣一個句子:“I can code。”當它接收到“I”的時候,它會預測“can”。下一步它接收到“I can”,繼續預測“code”。也就是說,每一次神經網路都會接收所有之前的單詞,但是僅需預測下一個單詞。

神經網路根據資料創建特徵,它必須通過創建的特徵把輸入資料和輸出資料連接起來,它需要建立一種表現方式來理解截圖中的內容以及預測到的 HTML 語法。這個過程積累的知識可以用來預測下個標籤。

利用訓練好的模型開展實際應用與訓練模型的過程很相似。模型會按照同一張截圖逐個生成文本。所不同的是,你無需提供正確的 HTML 標籤,模型只接受迄今為止生成過的標籤,然後預測下一個標籤。預測從“start”標籤開始,當預測到“end”標籤或超過最大限制時終止。下面的 Google Sheet 給出了另一個例子:

https://docs.google.com/spreadsheets/d/1yneocsAb_w3-ZUdhwJ1odfsxR2kr-4e_c5FabQbNJrs/edit#gid=0

▌Hello World 版本

讓我們試著創建一個“hello world”的版本。我們給神經網路提供一個顯示“Hello World”的網頁截圖,並教它怎樣生成 HTML 代碼。

大圖請點:

https://blog.floydhub.com/hello_world_generation-039d78c27eb584fa639b89d564b94772.gif

首先,神經網路將設計圖轉化成一系列的圖元值,每個圖元包含三個通道(紅藍綠),數值為 0-255。

我在這裡使用 one-hot 編碼[10]來描述神經網路理解 HTML 代碼的方式。句子“I can code”的編碼如下圖所示:

上圖的例子中加入了“start”和“end”標籤。這些標籤可以提示神經網路從哪裡開始預測,到哪裡停止預測。

我們用句子作為輸入資料,第一個句子只包含第一個單詞,以後每次加入一個新單詞。而輸出資料始終只有一個單詞。

句子的邏輯與單詞相同,但它們還需要保證輸入資料具有相同的長度。單詞的上限是詞彙表的大小,而句子的上限則是句子的最大長度。如果句子的長度小於最大長度,就用空單詞補齊——空單詞就是全零的單詞。

如上圖所示,單詞是從右向左排列的,這樣可以強迫每個單詞在每輪訓練中改變位置。這樣模型就能學習單詞的順序,而非記住每個單詞的位置。

下圖是四次預測,每行代表一次預測。等式左側是用紅綠藍三個通道的數值表示的圖像,以及之前的單詞。括弧外面是每次的預測,最後一個紅方塊代表結束。

#Length of longest sentencemax_caption_len = 3#Size of vocabularyvocab_size = 3# Load one screenshot for each word and turn them into digitsimages = []for i in range(2): images.append(img_to_array(load_img('screenshot.jpg', target_size=(224, 224))))images = np.array(images, dtype=float)# Preprocess input for the VGG16 modelimages = preprocess_input(images)#Turn start tokens into one-hot encodinghtml_input = np.array( [[[0., 0., 0.], #start [0., 0., 0.], [1., 0., 0.]], [[0., 0., 0.], #start Hello World! [1., 0., 0.], [0., 1., 0.]]])#Turn next word into one-hot encodingnext_words = np.array( [[0., 1., 0.], # Hello World! [0., 0., 1.]]) # end# Load the VGG16 model trained on imagenet and output the classification featureVGG = VGG16(weights='imagenet', include_top=True)# Extract the features from the imagefeatures = VGG.predict(images)#Load the feature to the network, apply a dense layer, and repeat the vectorvgg_feature = Input(shape=(1000,))vgg_feature_dense = Dense(5)(vgg_feature)vgg_feature_repeat = RepeatVector(max_caption_len)(vgg_feature_dense)# Extract information from the input seqencelanguage_input = Input(shape=(vocab_size, vocab_size))language_model = LSTM(5, return_sequences=True)(language_input)# Concatenate the information from the image and the inputdecoder = concatenate([vgg_feature_repeat, language_model])# Extract information from the concatenated outputdecoder = LSTM(5, return_sequences=False)(decoder)# Predict which word comes nextdecoder_output = Dense(vocab_size, activation='softmax')(decoder)# Compile and run the neural networkmodel = Model(inputs=[vgg_feature, language_input], outputs=decoder_output)model.compile(loss='categorical_crossentropy', optimizer='rmsprop')# Train the neural networkmodel.fit([features, html_input], next_words, batch_size=2, shuffle=False, epochs=1000)

在 hello world 版本中,我們用到了 3 個 token,分別是“start”、“

Hello World!

”和“end”。

token 可以代表任何東西,可以是一個字元、單詞或者句子。選擇字元作為 token 的好處是所需的詞彙表較小,但是會限制神經網路的學習。選擇單詞作為 token 具有最好的性能。

接下來進行預測:

# Create an empty sentence and insert the start tokensentence = np.zeros((1, 3, 3)) # [[0,0,0], [0,0,0], [0,0,0]]start_token = [1., 0., 0.] # startsentence[0][2] = start_token # place start in empty sentence# Making the first prediction with the start tokensecond_word = model.predict([np.array([features[1]]), sentence])# Put the second word in the sentence and make the final predictionsentence[0][1] = start_tokensentence[0][2] = np.round(second_word)third_word = model.predict([np.array([features[1]]), sentence])# Place the start token and our two predictions in the sentencesentence[0][0] = start_tokensentence[0][1] = np.round(second_word)sentence[0][2] = np.round(third_word)# Transform our one-hot predictions into the final tokensvocabulary = ["start", "

Hello World!

", "end"]for i in sentence[0]: print(vocabulary[np.argmax(i)], end=' ')

輸出結果

10 epochs:start start start

100 epochs:start

Hello World!

Hello World!

300 epochs:start

Hello World!

end

在這之中,我犯過的錯誤

先做出可以運行的第一版,再收集資料。在這個項目的早期,我曾成功地下載了整個 Geocities 託管網站的一份舊的存檔,裡面包含了 3800 萬個網站。由於神經網路強大的潛力,我沒有考慮到歸納一個 10 萬大小詞彙表的巨大工作量。

處理 TB 級的資料需要好的硬體或巨大的耐心。在我的 Mac 遇到幾個難題後,我不得不使用強大的遠端伺服器。為了保證工作流程的順暢,需要做好心裡準備租用一台 8 CPU 和 1G 頻寬的礦機。

關鍵在於搞清楚輸入和輸出資料。輸入 X 是一張截圖和之前的 HTML 標籤。而輸出 Y 是下一個標籤。當我明白了輸入和輸出資料之後,理解其餘內容就很簡單了。試驗不同的架構也變得更加容易。

保持專注,不要被誘惑。因為這個專案涉及了深度學習的許多領域,很多地方讓我深陷其中不能自拔。我曾花了一周的時間從頭開始編寫 RNN,也曾經沉迷于嵌入向量空間,還陷入過極限實現方式的陷阱。

圖片轉換到代碼的網路只不過是偽裝的圖像標注模型。即使我明白這一點,但還是因為許多圖像標注方面的論文不夠炫酷而忽略了它們。掌握一些這方面的知識可以説明我們加速學習問題空間。

▌在 FloydHub 上運行代碼

FloydHub 是深度學習的訓練平臺。我在剛開始學習深度學習的時候發現了這個平臺,從那以後我一直用它訓練和管理我的深度學習實驗。你可以在 10 分鐘之內安裝並開始運行模型,它是在雲端 GPU 上運行模型的最佳選擇。

如果你沒用過 FloydHub,請參照官方的“2 分鐘安裝手冊”或我寫的“5 分鐘入門教程”[11]。

克隆代碼倉庫:

git clone https://github.com/emilwallner/Screenshot-to-code-in-Keras.git

登錄及初始化 FloydHub 的命令列工具:

cd Screenshot-to-code-in-Kerasfloyd loginfloyd init s2c

在 FloydHub 的雲端 GPU 機器上運行 Jupyter notebook:

floyd run --gpu --env tensorflow-1.4 --data emilwallner/datasets/imagetocode/2:data --mode jupyter

所有的 notebook 都保存在“FloydHub”目錄下,而 local 的東西都在“local”目錄下。運行之後,你可以在如下檔中找到第一個 notebook:

floydhub/Helloworld/helloworld.ipynb

如果你想瞭解詳細的命令參數,請參照我這篇帖子:

https://blog.floydhub.com/colorizing-b&w-photos-with-neural-networks/

▌HTML 版本

在這個版本中,我們將自動化 Hello World 模型中的部分步驟。本節我們將集中介紹如何讓模型處理任意多的輸入資料,以及建立神經網路中的關鍵部分。

這個版本還不能根據任意網站預測 HTML,但是我們將在此嘗試解決關鍵性的技術問題,向最終的成功邁進一大步。

概述

我們可以把之前的解說圖擴展為如下:

上圖中有兩個主要部分。首先是編碼部分。編碼部分負責建立圖像特徵和之前的標籤特徵。特徵是指神經網路創建的最小單位的資料,用於連接設計圖和 HTML 代碼。在編碼部分的最後,我們把圖像的特徵連接到之前的標籤的每個單詞。

另一個主要部分是解碼部分。解碼部分負責接收聚合後的設計圖和 HTML 代碼的特徵,並創建下一個標籤的特徵。這個特徵通過一個全連接神經網路來預測下一個標籤。

設計圖的特徵

由於我們需要給每個單詞添加一張截圖,所以這會成為訓練神經網路過程中的瓶頸。所以我們不直接使用圖片,而是從中提取生成標籤所必需的資訊。

提取的資訊經過編碼後保存在圖像特徵中。這項工作可以由事先訓練好的卷積神經網路(CNN)完成。該模型可以通過 ImageNet 上的資料進行訓練。

CNN 的最後一層是分類層,我們可以從前一層提取圖像特徵。

最終我們可以得到 1536 個 8x8 圖元的圖片作為特徵。儘管我們很難理解這些特徵的含義,但是神經網路可以從中提取元素的物件和位置。

HTML 標籤的特徵

在 hello world 版本中,我們採用了 one-hot 編碼表現 HTML 標籤。在這個版本中,我們將使用單詞嵌入(word embedding)作為輸入資訊,輸出依然用 one-hot 編碼。

我們繼續採用之前的方式分析句子,但是匹配每個 token 的方式有所變化。之前的 one-hot 編碼把每個單詞當成一個獨立的單元,而這裡我們把輸入資料中的每個單詞轉化成一系列數字,它們代表 HTML 標籤之間的關係。

上例中的單詞嵌入是 8 維的,而實際上根據詞彙表的大小,其維度會在 50 到 500 之間。

每個單詞的 8 個數位表示權重,與原始的神經網路很相似。它們表示單詞之間的關係(Mikolov 等,2013[12])。

以上就是我們建立 HTML 標籤特徵的過程。神經網路通過此特徵在輸入和輸出資料之間建 立聯繫。暫時先不用擔心具體的內容,我們會在下節中深入討論這個問題。

編碼部分

我們需要把單詞嵌入的結果輸入到 LSTM 中,並返回一系列標籤特徵,再把這些特徵送入 Time distributed dense 層——你可以認為這是擁有多個輸入和輸出的 dense 層。

同時,圖像特徵首先需要被展開(flatten),無論數值原來是什麼結構,它們都會被轉換成一個巨大的數值列表;然後經過 dense 層建立更高級的特徵;最後把這些特徵與 HTML 標籤的特徵連接起來。

這可能有點難理解,下面我們逐一分解開來看看。

HTML 標籤特徵

首先我們把單詞嵌入的結果輸入到 LSTM 層。如下圖所示,所有的句子都被填充到最大長度,即三個 token。

為了混合這些信號並找到更高層的模式,我們加入 TimeDistributed dense 層進一步處理 LSTM 層生成的 HTML 標籤特徵。TimeDistributed dense 層是擁有多個輸入和輸出的 dense 層。

圖像特徵

同時,我們需要處理圖像。我們把所有的特徵(小圖片)轉化成一個長陣列,其中包含的資訊保持不變,只是進行重組。

同樣,為了混合信號並提取更高層的資訊,我們添加一個 dense 層。由於輸入只有一個,所以我們可以使用普通的 dense 層。為了與 HTML 標籤特徵相連接,我們需要複製圖像特徵。

上述的例子中我們有三個 HTML 標籤特徵,因此最終圖像特徵的數量也同樣是三個。

連接圖像特徵和 HTML 標籤特徵

所有的句子經過填充後組成了三個特徵。因為我們已經準備好了圖像特徵,所以現在可以把圖像特徵分別添加到各自的 HTML 標籤特徵。

添加完成之後,我們得到了 3 個圖像-標籤特徵,這便是我們需要提供給解碼部分的輸入資訊。

解碼部分

接下來,我們使用圖像-標籤的結合特徵來預測下一個標籤。

在下面的例子中,我們使用三對圖形-標籤特徵,輸出下一個標籤的特徵。

請注意,LSTM 層的 sequence 值為 false,所以我們不需要返回輸入序列的長度,只需要預測一個特徵,也就是下一個標籤的特徵,其內包含了最終的預測資訊。

最終預測

dense 層的工作原理與傳統的前饋神經網路相似,它把下個標籤特徵的 512 個數字與 4 個最終預測連接起來。用我們的單詞表達就是:start、hello、world 和 end。

其中,dense 層的 softmax 啟動函數會生成 0-1 的概率分佈,所有預測值的總和等於 1。比如說詞彙表的預測可能是[0.1,0.1,0.1,0.7],那麼輸出的預測結果即為:第 4 個單詞是下一個標籤。然後,你可以把 one-hot 編碼[0,0,0,1]轉換為映射值,得出“end”。

# Load the images and preprocess them for inception-resnetimages = []all_filenames = listdir('images/')all_filenames.sort()for filename in all_filenames: images.append(img_to_array(load_img('images/'+filename, target_size=(299, 299))))images = np.array(images, dtype=float)images = preprocess_input(images)# Run the images through inception-resnet and extract the features without the classification layerIR2 = InceptionResNetV2(weights='imagenet', include_top=False)features = IR2.predict(images)# We will cap each input sequence to 100 tokensmax_caption_len = 100# Initialize the function that will create our vocabularytokenizer = Tokenizer(filters='', split=" ", lower=False)# Read a document and return a stringdef load_doc(filename): file = open(filename, 'r') text = file.read() file.close() return text# Load all the HTML filesX = []all_filenames = listdir('html/')all_filenames.sort()for filename in all_filenames:X.append(load_doc('html/'+filename))# Create the vocabulary from the html filestokenizer.fit_on_texts(X)# Add +1 to leave space for empty wordsvocab_size = len(tokenizer.word_index) + 1# Translate each word in text file to the matching vocabulary indexsequences = tokenizer.texts_to_sequences(X)# The longest HTML filemax_length = max(len(s) for s in sequences)# Intialize our final input to the modelX, y, image_data = list(), list(), list()for img_no, seq in enumerate(sequences): for i in range(1, len(seq)): # Add the entire sequence to the input and only keep the next word for the output in_seq, out_seq = seq[:i], seq[i] # If the sentence is shorter than max_length, fill it up with empty words in_seq = pad_sequences([in_seq], maxlen=max_length)[0] # Map the output to one-hot encoding out_seq = to_categorical([out_seq], num_classes=vocab_size)[0] # Add and image corresponding to the HTML file image_data.append(features[img_no]) # Cut the input sentence to 100 tokens, and add it to the input data X.append(in_seq[-100:]) y.append(out_seq)X, y, image_data = np.array(X), np.array(y), np.array(image_data)# Create the encoderimage_features = Input(shape=(8, 8, 1536,))image_flat = Flatten()(image_features)image_flat = Dense(128, activation='relu')(image_flat)ir2_out = RepeatVector(max_caption_len)(image_flat)language_input = Input(shape=(max_caption_len,))language_model = Embedding(vocab_size, 200, input_length=max_caption_len)(language_input)language_model = LSTM(256, return_sequences=True)(language_model)language_model = LSTM(256, return_sequences=True)(language_model)language_model = TimeDistributed(Dense(128, activation='relu'))(language_model)# Create the decoderdecoder = concatenate([ir2_out, language_model])decoder = LSTM(512, return_sequences=False)(decoder)decoder_output = Dense(vocab_size, activation='softmax')(decoder)# Compile the modelmodel = Model(inputs=[image_features, language_input], outputs=decoder_output)model.compile(loss='categorical_crossentropy', optimizer='rmsprop')# Train the neural networkmodel.fit([image_data, X], y, batch_size=64, shuffle=False, epochs=2)# map an integer to a worddef word_for_id(integer, tokenizer): for word, index in tokenizer.word_index.items(): if index == integer: return word return None# generate a description for an imagedef generate_desc(model, tokenizer, photo, max_length): # seed the generation process in_text = 'START' # iterate over the whole length of the sequence for i in range(900): # integer encode input sequence sequence = tokenizer.texts_to_sequences([in_text])[0][-100:] # pad input sequence = pad_sequences([sequence], maxlen=max_length) # predict next word yhat = model.predict([photo,sequence], verbose=0) # convert probability to integer yhat = np.argmax(yhat) # map integer to word word = word_for_id(yhat, tokenizer) # stop if we cannot map the word if word is None: break # append as input for generating the next word in_text += ' ' + word # Print the prediction print(' ' + word, end='') # stop if we predict the end of the sequence if word == 'END': break return# Load and image, preprocess it for IR2, extract features and generate the HTMLtest_image = img_to_array(load_img('images/87.jpg', target_size=(299, 299)))test_image = np.array(test_image, dtype=float)test_image = preprocess_input(test_image)test_features = IR2.predict(np.array([test_image]))generate_desc(model, tokenizer, np.array(test_features), 100)

輸出結果

生成網站的連結:

250 epochs: https://emilwallner.github.io/html/250_epochs/

350 epochs:https://emilwallner.github.io/html/350_epochs/

450 epochs:https://emilwallner.github.io/html/450_epochs/

550 epochs:https://emilwallner.github.io/html/450_epochs/

如果點擊上述連結看不到頁面的話,你可以選擇“查看原始程式碼”。下面是原網站的連結,僅供參考:

https://emilwallner.github.io/html/Original/

我犯過的錯誤

與 CNN 相比,LSTM 遠比我想像得複雜。為了更好的理解,我展開了所有的 LSTM。關於 RNN 你可以參考這個視頻(http://course.fast.ai/lessons/lesson6.html)。另外,在理解原理之前,請先搞清楚輸入和輸出特徵。

從零開始創建詞彙表比削減大型詞彙表更容易。詞彙表可以包括任何東西,如字體、div 大小、十六進位顏色、變數名以及普通單詞。

大多數的代碼庫可以很好地解析文本文檔,卻不能解析代碼。因為文檔中所有單詞都用空格分開,但是代碼不同,所以你得自己想辦法解析代碼。

用 Imagenet 訓練好的模型提取特徵也許不是個好主意。因為 Imagenet 很少有網頁的圖片,所以它的損失率比從零開始訓練的 pix2code 模型高 30%。如果使用網頁截圖訓練 inception-resnet 之類的模型,不知結果會怎樣。

▌Bootstrap 版本

在最後一個版本——Bootstrap 版本中,我們使用的資料集來自根據 pix2code 論文生成的 bootstrap 網站。通過使用 Twitter 的 bootstrap(https://getbootstrap.com/),我們可以結合 HTML 和 CSS,並減小詞彙表的大小。

我們可以提供一個它從未見過的截圖,訓練它生成相應的 HTML 代碼。我們還可以深入研究它學習這個截圖和 HTML 代碼的過程。

拋開 bootstrap 的 HTML 代碼,我們在這裡使用 17 個簡化的 token 訓練它,然後翻譯成 HTML 和 CSS。這個資料集[13]包括 1500 個測試截圖和 250 個驗證截圖。每個截圖上平均有 65 個 token,包含 96925 個訓練樣本。

通過修改 pix2code 論文的模型提供輸入資料,我們的模型可以預測網頁的組成,且準確率高達 97%(我們採用了 BLEU 4-ngram greedy search,稍後會詳細介紹)。

端到端的方法

圖像標注模型可以從事先訓練好的模型中提取特徵,但是經過幾次實驗後,我發現 pix2code 的端到端的方法可以更好地為我們的模型提取特徵,因為事先訓練好的模型並沒有用網頁數據訓練過,而且它本來的作用是分類。

在這個模型中,我們用羽量級的卷積神經網路替代了事先訓練好的圖像特徵。我們沒有採用 max-pooling 增加資訊密度,但我們增加了步長(stride),以確保前端元素的位置和顏色。

有兩個核心模型可以支援這個方法:卷積神經網路(CNN)和遞迴神經網路(RNN)。最常見的遞迴神經網路就是 LSTM,所以我選擇了 RNN。

關於 CNN 的教程有很多,我在別的文章裡有介紹。此處我主要講解 LSTM。

理解 LSTM 中的 timestep

LSTM 中最難理解的內容之一就是 timestep。原始的神經網路可以看作只有兩個 timestep。如果輸入是“Hello”(第一個 timestep),它會預測“World”(第二個 timestep),但它無法預測更多的 timestep。下面的例子中輸入有四個 timestep,每個詞一個。

LSTM 適用於包含 timestep 的輸入,這種神經網路專門處理有序的資訊。模型展開後你會發現,下行的每一步所持有的權重保持不變。另外,前一個輸出和新的輸入需要分別使用相應的權重。

接下來,輸入和輸出乘以權重之後相加,再通過啟動函數得到該 timestep 的輸出。由於權重不隨 timestep 變化,所以它們可以從多個輸入中獲得資訊,從而掌握單詞的順序。

下圖通過簡單圖例描述了一個 LSTM 中每個 timestep 的處理過程。

為了更好地理解這個邏輯,我建議你跟隨 Andrew Trask 的這篇精彩的教程[14],嘗試從頭創建一個 RNN。

理解 LSTM 層中的單元

LSTM 層中的單元(unit)數量決定了它的記憶能力,以及每個輸出特徵的大小。再次強調,特徵是一長列的數值,用於在層與層之間的資訊傳遞。

LSTM 層中的每個單元負責跟蹤語法中的不同資訊。下圖描述了一個單元的示例,其內保存了佈局行“div”的資訊。我們簡化了 HTML 代碼,並用於訓練 bootstrap 模型。

每個 LSTM 單元擁有一個單元狀態(cell state)。你可以把單元狀態看作單元的記憶。權重和啟動函數可以用各種方式改變狀態。因此 LSTM 層可以微調每個輸入所需要保存和丟棄的資訊。

向輸入傳遞輸出特徵的同時,還需傳遞單元狀態,LSTM 的每個單元都需要傳遞自己的單元狀態值。為了理解 LSTM 各部分的對話模式,我建議你可以閱讀:

Colah 的教程:

https://colah.github.io/posts/2015-08-Understanding-LSTMs/

Jayasiri 的 Numpy 實現:

http://blog.varunajayasiri.com/numpy_lstm.html

Karphay 的講座和文章:

https://www.youtube.com/watch?v=yCC09vCHzF8; https://karpathy.github.io/2015/05/21/rnn-effectiveness/

dir_name = 'resources/eval_light/'# Read a file and return a stringdef load_doc(filename): file = open(filename, 'r') text = file.read() file.close() return textdef load_data(data_dir): text = [] images = [] # Load all the files and order them all_filenames = listdir(data_dir) all_filenames.sort() for filename in (all_filenames): if filename[-3:] == "npz": # Load the images already prepared in arrays image = np.load(data_dir+filename) images.append(image['features']) else: # Load the boostrap tokens and rap them in a start and end tag syntax = ' ' + load_doc(data_dir+filename) + ' ' # Seperate all the words with a single space syntax = ' '.join(syntax.split()) # Add a space after each comma syntax = syntax.replace(',', ' ,') t ext.append(syntax) images = np.array(images, dtype=float) return images, texttrain_features, texts = load_data(dir_name)# Initialize the function to create the vocabularytokenizer = Tokenizer(filters='', split=" ", lower=False)# Create the vocabularytokenizer.fit_on_texts([load_doc('bootstrap.vocab')])# Add one spot for the empty word in the vocabularyvocab_size = len(tokenizer.word_index) + 1# Map the input sentences into the vocabulary indexestrain_sequences = tokenizer.texts_to_sequences(texts)# The longest set of boostrap tokensmax_sequence = max(len(s) for s in train_sequences)# Specify how many tokens to have in each input sentencemax_length = 48def preprocess_data(sequences, features): X, y, image_data = list(), list(), list() for img_no, seq in enumerate(sequences): for i in range(1, len(seq)): # Add the sentence until the current count(i) and add the current count to the output in_seq, out_seq = seq[:i], seq[i] # Pad all the input token sentences to max_sequence in_seq = pad_sequences([in_seq], maxlen=max_sequence)[0] # Turn the output into one-hot encoding out_seq = to_categorical([out_seq], num_classes=vocab_size)[0] # Add the corresponding image to the boostrap token file image_data.append(features[img_no]) # Cap the input sentence to 48 tokens and add it X.append(in_seq[-48:]) y.append(out_seq) return np.array(X), np.array(y), np.array(image_data)X, y, image_data = preprocess_data(train_sequences, train_features)#Create the encoderimage_model = Sequential()image_model.add(Conv2D(16, (3, 3), padding='valid', activation='relu', input_shape=(256, 256, 3,)))image_model.add(Conv2D(16, (3,3), activation='relu', padding='same', strides=2))image_model.add(Conv2D(32, (3,3), activation='relu', padding='same'))image_model.add(Conv2D(32, (3,3), activation='relu', padding='same', strides=2))image_model.add(Conv2D(64, (3,3), activation='relu', padding='same'))image_model.add(Conv2D(64, (3,3), activation='relu', padding='same', strides=2))image_model.add(Conv2D(128, (3,3), activation='relu', padding='same'))image_model.add(Flatten())image_model.add(Dense(1024, activation='relu'))image_model.add(Dropout(0.3))image_model.add(Dense(1024, activation='relu'))image_model.add(Dropout(0.3))image_model.add(RepeatVector(max_length))visual_input = Input(shape=(256, 256, 3,))encoded_image = image_model(visual_input)language_input = Input(shape=(max_length,))language_model = Embedding(vocab_size, 50, input_length=max_length, mask_zero=True)(language_input)language_model = LSTM(128, return_sequences=True)(language_model)language_model = LSTM(128, return_sequences=True)(language_model)#Create the decoderdecoder = concatenate([encoded_image, language_model])decoder = LSTM(512, return_sequences=True)(decoder)decoder = LSTM(512, return_sequences=False)(decoder)decoder = Dense(vocab_size, activation='softmax')(decoder)# Compile the modelmodel = Model(inputs=[visual_input, language_input], outputs=decoder)optimizer = RMSprop(lr=0.0001, clipvalue=1.0)model.compile(loss='categorical_crossentropy', optimizer=optimizer)#Save the model for every 2nd epochfilepath="org-weights-epoch-{epoch:04d}--val_loss-{val_loss:.4f}--loss-{loss:.4f}.hdf5"checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_weights_only=True, period=2)callbacks_list = [checkpoint]# Train the modelmodel.fit([image_data, X], y, batch_size=64, shuffle=False, validation_split=0.1, callbacks=callbacks_list, verbose=1, epochs=50)

測試準確度

很難找到合理的方式測量準確度。你可以逐個比較單詞,但如果預測結果中有一個單詞出現了錯位,那準確率可能就是 0%了;如果為了同步預測而刪除這個詞,那麼準確率又會變成 99/100。

我採用了 BLEU 分數,它是測試機器翻譯和圖像標記模型的最佳選擇。它將句子分成四個 n-grams,從 1 個單詞的序列逐步擴展為 4 個單詞。下例,預測結果中的“cat”實際上應該是“code”。

為了計算最終分數,首先需要讓每個 n-grams 的得分乘以 25%並求和,即(4/5) * 0.25 + (2/4) * 0.25 + (1/3) * 0.25 + (0/2) * 0.25 = 02 + 1.25 + 0.083 + 0 = 0.408;得出的總和需要乘以句子長度的懲罰因數。由於本例中預測句子的長度是正確的,因此這就是最終的分數。

增加 n-grams 的數量可以提高難度。4 個 n-grams 的模型最適合人類翻譯。為了進一步瞭解 BLEU,我建議你可以用下面的代碼運行幾個例子,並閱讀這篇 wiki 頁面[15]。

#Create a function to read a file and return its contentdef load_doc(filename): file = open(filename, 'r') text = file.read() file.close() return textdef load_data(data_dir): text = [] images = [] files_in_folder = os.listdir(data_dir) files_in_folder.sort() for filename in tqdm(files_in_folder): #Add an image if filename[-3:] == "npz": image = np.load(data_dir+filename) images.append(image['features']) else: # Add text and wrap it in a start and end tag syntax = ' ' + load_doc(data_dir+filename) + ' ' #Seperate each word with a space syntax = ' '.join(syntax.split()) #Add a space between each comma syntax = syntax.replace(',', ' ,') text.append(syntax) images = np.array(images, dtype=float) return images, text#Intialize the function to create the vocabularytokenizer = Tokenizer(filters='', split=" ", lower=False)#Create the vocabulary in a specific ordertokenizer.fit_on_texts([load_doc('bootstrap.vocab')])dir_name = '../../../../eval/'train_features, texts = load_data(dir_name)#load model and weightsjson_file = open('../../../../model.json', 'r')loaded_model_json = json_file.read()json_file.close()loaded_model = model_from_json(loaded_model_json)# load weights into new modelloaded_model.load_weights("../../../../weights.hdf5")print("Loaded model from disk")# map an integer to a worddef word_for_id(integer, tokenizer): for word, index in tokenizer.word_index.items(): if index == integer: return word return Noneprint(word_for_id(17, tokenizer))# generate a description for an imagedef generate_desc(model, tokenizer, photo, max_length): photo = np.array([photo]) # seed the generation process in_text = ' ' # iterate over the whole length of the sequence print(' Prediction----> ', end='') for i in range(150): # integer encode input sequence sequence = tokenizer.texts_to_sequences([in_text])[0] # pad input sequence = pad_sequences([sequence], maxlen=max_length) # predict next word yhat = loaded_model.predict([photo, sequence], verbose=0) # convert probability to integer yhat = argmax(yhat) # map integer to word word = word_for_id(yhat, tokenizer) # stop if we cannot map the word if word is None: break # append as input for generating the next word in_text += word + ' ' # stop if we predict the end of the sequence print(word + ' ', end='') if word == '': break return in_textmax_length = 48# evaluate the skill of the modeldef evaluate_model(model, descriptions, photos, tokenizer, max_length): actual, predicted = list(), list() # step over the whole set for i in range(len(texts)): yhat = generate_desc(model, tokenizer, photos[i], max_length) # store actual and predicted print(' Real----> ' + texts[i]) actual.append([texts[i].split()]) predicted.append(yhat.split()) # calculate BLEU score bleu = corpus_bleu(actual, predicted) return bleu, actual, predictedbleu, actual, predicted = evaluate_model(loaded_model, texts, train_features, tokenizer, max_length)#Compile the tokens into HTML and cssdsl_path = "compiler/assets/web-dsl-mapping.json"compiler = Compiler(dsl_path)compiled_website = compiler.compile(predicted[0], 'index.html')print(compiled_website )print(bleu)

輸出

輸出示例的連結

網站 1:

生成的網站:https://emilwallner.github.io/bootstrap/pred_1/

原網站:https://emilwallner.github.io/bootstrap/real_1/

網站 2:

生成的網站:https://emilwallner.github.io/bootstrap/pred_2/

原網站:https://emilwallner.github.io/bootstrap/real_2/

網站 3:

生成的網站:https://emilwallner.github.io/bootstrap/pred_3/

原網站:https://emilwallner.github.io/bootstrap/real_3/

網站 4:

生成的網站:https://emilwallner.github.io/bootstrap/pred_4/

原網站:https://emilwallner.github.io/bootstrap/real_4/

網站 5:

生成的網站:https://emilwallner.github.io/bootstrap/pred_5/

原網站:https://emilwallner.github.io/bootstrap/real_5/

我犯過的錯誤

學會理解模型的弱點,避免盲目測試模型。剛開始的時候,我隨便嘗試了一些東西,比如 batch normalization、bidirectional network,還試圖實現 attention。看了測試資料後發現這些並不能準確地預測顏色和位置,我開始意識到這是 CNN 的弱點。因此我放棄了 maxpooling,改為增加步長。結果測試損失從 0.12 降到了 0.02,BLEU 分數從 85%提高到了 97%。

只使用相關的事先訓練好的模型。在資料集很小的時候,我以為事先訓練好的圖像模型能夠提高效率。實驗結果表明,端到端的模型雖然更慢,訓練也需要更多的記憶體,但準確率能提高 30%。

在遠端伺服器上運行模型時要為一些差異做好準備。在我的 Mac 上運行時,檔是按照字母順序讀取的。但在遠端伺服器上卻是隨機讀取的。結果造成了截圖和代碼不匹配的問題。雖然依然能夠收斂,但在我修復了這個問題後,測試資料的準確率提高了 50%。

務必要理解庫函數。詞彙表中的空 token 需要包含空格。一開始我沒加空格,結果就漏了一個 token。直到看了幾次最終輸出結果,注意到它從來不會預測某個 token 的時候,我才發現了這個問題。檢查後發現那個 token 不在詞彙表裡。此外,要保證訓練和測試時使用的詞彙表的順序相同。

試驗時使用羽量級的模型。用 GRU 替換 LSTM 可以讓每個 epoch 的時間減少 30%,而且不會對性能有太大影響。

▌下一步

深度學習很適合應用在前端開發中,因為很容易生成資料,而且如今的深度學習演算法可以覆蓋絕大多數的邏輯。

其中一個最有意思的方面是在 LSTM 中使用 attention 機制[16]。它不僅能提高準確率,而且可以幫助我們觀察 CSS 在生成 HTML 代碼的時候,它的注意力在何處。

Attention 還是 HTML 代碼、樣式表、腳本甚至後臺之間溝通的關鍵因素。attention 層可以追蹤參數,説明神經網路在不同程式設計語言之間溝通。

但是短期內,最大的難題還在於找到一個可擴展的方法用於生成資料。這樣才能逐步加入字體、顏色、單詞以及動畫。

迄今為止,很多人都在努力實現繪製草圖並將其轉化為應用程式的範本。不出兩年,我們就能實現在紙上繪製應用程式,並在一秒內獲得相應的前端代碼。Airbnb 設計團隊[17]和 Uizard[18] 已經創建了兩個原型。

下面是一些值得嘗試的實驗。

▌實驗

Getting started:

運行所有的模型

嘗試不同的超參數

嘗試不同的 CNN 架構

加入 Bidirectional 的 LSTM 模型

使用不同的資料集實現模型[19](你可以通過 FloydHub 的參數“--data ”掛載這個資料集:emilwallner/datasets/100k-html:data)

高級實驗

創建能利用特定的語法穩定生成任意應用程式/網頁的生成器

生成應用程式模型的設計圖資料。將應用程式或網頁的截圖自動轉換成設計,並使用 GAN 產生變化。

通過 attention 層觀察每次預測時的圖像焦點,類似於這個模型:https://arxiv.org/abs/1502.03044

創建模組化方法的框架。比如一個模型負責編碼字體,一個負責顏色,另一個負責佈局,並利用解碼部分將它們結合在一起。你可以從靜態圖像特徵開始嘗試。

為神經網路提供簡單的 HTML 組成單元,訓練它利用 CSS 生成動畫。如果能加入 attention 模組,觀察輸入源的聚焦就更完美了。

最後,非常感謝 Tony Beltramelli 和 Jon Gold 提供的研究成果和想法,以及對各種問題的解答。謝謝 Jason Brownlee 貢獻他的 stellar Keras 教程(我在核心的 Keras 實現中加入了幾個他的教程中介紹的 snippets),謝謝 Beltramelli 提供的資料。還要謝謝 Qingping Hou、Charlie Harrington、 Sai Soundararaj、 Jannes Klaas、 Claudio Cabral、 Alain Demenet 和 Dylan Djian 審閱本篇文章。

相關連結

[1]pix2code 論文:https://arxiv.org/abs/1705.07962

[2]sketch2code:https://airbnb.design/sketching-interfaces/

[3]https://github.com/emilwallner/Screenshot-to-code-in-Keras/blob/master/README.md

[4]https://www.floydhub.com/emilwallner/projects/picturetocode

[5]https://machinelearningmastery.com/blog/page/2/

[6]https://blog.floydhub.com/my-first-weekend-of-deep-learning/

[7]https://blog.floydhub.com/coding-the-history-of-deep-learning/

[8]https://blog.floydhub.com/colorizing-b&w-photos-with-neural-networks/

[9]https://machinelearningmastery.com/deep-learning-caption-generation-models/

[10]https://machinelearningmastery.com/how-to-one-hot-encode-sequence-data-in-python/

[11]https://www.youtube.com/watch?v=byLQ9kgjTdQ&t=21s

[12]https://arxiv.org/abs/1301.3781

[13]https://github.com/tonybeltramelli/pix2code/tree/master/datasets

[14]https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/

[15]https://en.wikipedia.org/wiki/BLEU

[16]https://arxiv.org/pdf/1502.03044.pdf

[17]https://airbnb.design/sketching-interfaces/

[18]https://www.uizard.io/

[19]http://lstm.seas.harvard.edu/latex/

請注意每次的預測都必須基於同一張截圖,所以如果神經網路需要預測 20 個單詞,那麼它需要查看同一張截圖 20 次。暫時先把神經網路的工作原理放到一邊,讓我們先瞭解一下神經網路的輸入和輸出。

讓我們先來看看“之前的 HTML 標籤”。假設我們需要訓練神經網路預測這樣一個句子:“I can code。”當它接收到“I”的時候,它會預測“can”。下一步它接收到“I can”,繼續預測“code”。也就是說,每一次神經網路都會接收所有之前的單詞,但是僅需預測下一個單詞。

神經網路根據資料創建特徵,它必須通過創建的特徵把輸入資料和輸出資料連接起來,它需要建立一種表現方式來理解截圖中的內容以及預測到的 HTML 語法。這個過程積累的知識可以用來預測下個標籤。

利用訓練好的模型開展實際應用與訓練模型的過程很相似。模型會按照同一張截圖逐個生成文本。所不同的是,你無需提供正確的 HTML 標籤,模型只接受迄今為止生成過的標籤,然後預測下一個標籤。預測從“start”標籤開始,當預測到“end”標籤或超過最大限制時終止。下面的 Google Sheet 給出了另一個例子:

https://docs.google.com/spreadsheets/d/1yneocsAb_w3-ZUdhwJ1odfsxR2kr-4e_c5FabQbNJrs/edit#gid=0

▌Hello World 版本

讓我們試著創建一個“hello world”的版本。我們給神經網路提供一個顯示“Hello World”的網頁截圖,並教它怎樣生成 HTML 代碼。

大圖請點:

https://blog.floydhub.com/hello_world_generation-039d78c27eb584fa639b89d564b94772.gif

首先,神經網路將設計圖轉化成一系列的圖元值,每個圖元包含三個通道(紅藍綠),數值為 0-255。

我在這裡使用 one-hot 編碼[10]來描述神經網路理解 HTML 代碼的方式。句子“I can code”的編碼如下圖所示:

上圖的例子中加入了“start”和“end”標籤。這些標籤可以提示神經網路從哪裡開始預測,到哪裡停止預測。

我們用句子作為輸入資料,第一個句子只包含第一個單詞,以後每次加入一個新單詞。而輸出資料始終只有一個單詞。

句子的邏輯與單詞相同,但它們還需要保證輸入資料具有相同的長度。單詞的上限是詞彙表的大小,而句子的上限則是句子的最大長度。如果句子的長度小於最大長度,就用空單詞補齊——空單詞就是全零的單詞。

如上圖所示,單詞是從右向左排列的,這樣可以強迫每個單詞在每輪訓練中改變位置。這樣模型就能學習單詞的順序,而非記住每個單詞的位置。

下圖是四次預測,每行代表一次預測。等式左側是用紅綠藍三個通道的數值表示的圖像,以及之前的單詞。括弧外面是每次的預測,最後一個紅方塊代表結束。

#Length of longest sentencemax_caption_len = 3#Size of vocabularyvocab_size = 3# Load one screenshot for each word and turn them into digitsimages = []for i in range(2): images.append(img_to_array(load_img('screenshot.jpg', target_size=(224, 224))))images = np.array(images, dtype=float)# Preprocess input for the VGG16 modelimages = preprocess_input(images)#Turn start tokens into one-hot encodinghtml_input = np.array( [[[0., 0., 0.], #start [0., 0., 0.], [1., 0., 0.]], [[0., 0., 0.], #start Hello World! [1., 0., 0.], [0., 1., 0.]]])#Turn next word into one-hot encodingnext_words = np.array( [[0., 1., 0.], # Hello World! [0., 0., 1.]]) # end# Load the VGG16 model trained on imagenet and output the classification featureVGG = VGG16(weights='imagenet', include_top=True)# Extract the features from the imagefeatures = VGG.predict(images)#Load the feature to the network, apply a dense layer, and repeat the vectorvgg_feature = Input(shape=(1000,))vgg_feature_dense = Dense(5)(vgg_feature)vgg_feature_repeat = RepeatVector(max_caption_len)(vgg_feature_dense)# Extract information from the input seqencelanguage_input = Input(shape=(vocab_size, vocab_size))language_model = LSTM(5, return_sequences=True)(language_input)# Concatenate the information from the image and the inputdecoder = concatenate([vgg_feature_repeat, language_model])# Extract information from the concatenated outputdecoder = LSTM(5, return_sequences=False)(decoder)# Predict which word comes nextdecoder_output = Dense(vocab_size, activation='softmax')(decoder)# Compile and run the neural networkmodel = Model(inputs=[vgg_feature, language_input], outputs=decoder_output)model.compile(loss='categorical_crossentropy', optimizer='rmsprop')# Train the neural networkmodel.fit([features, html_input], next_words, batch_size=2, shuffle=False, epochs=1000)

在 hello world 版本中,我們用到了 3 個 token,分別是“start”、“

Hello World!

”和“end”。

token 可以代表任何東西,可以是一個字元、單詞或者句子。選擇字元作為 token 的好處是所需的詞彙表較小,但是會限制神經網路的學習。選擇單詞作為 token 具有最好的性能。

接下來進行預測:

# Create an empty sentence and insert the start tokensentence = np.zeros((1, 3, 3)) # [[0,0,0], [0,0,0], [0,0,0]]start_token = [1., 0., 0.] # startsentence[0][2] = start_token # place start in empty sentence# Making the first prediction with the start tokensecond_word = model.predict([np.array([features[1]]), sentence])# Put the second word in the sentence and make the final predictionsentence[0][1] = start_tokensentence[0][2] = np.round(second_word)third_word = model.predict([np.array([features[1]]), sentence])# Place the start token and our two predictions in the sentencesentence[0][0] = start_tokensentence[0][1] = np.round(second_word)sentence[0][2] = np.round(third_word)# Transform our one-hot predictions into the final tokensvocabulary = ["start", "

Hello World!

", "end"]for i in sentence[0]: print(vocabulary[np.argmax(i)], end=' ')

輸出結果

10 epochs:start start start

100 epochs:start

Hello World!

Hello World!

300 epochs:start

Hello World!

end

在這之中,我犯過的錯誤

先做出可以運行的第一版,再收集資料。在這個項目的早期,我曾成功地下載了整個 Geocities 託管網站的一份舊的存檔,裡面包含了 3800 萬個網站。由於神經網路強大的潛力,我沒有考慮到歸納一個 10 萬大小詞彙表的巨大工作量。

處理 TB 級的資料需要好的硬體或巨大的耐心。在我的 Mac 遇到幾個難題後,我不得不使用強大的遠端伺服器。為了保證工作流程的順暢,需要做好心裡準備租用一台 8 CPU 和 1G 頻寬的礦機。

關鍵在於搞清楚輸入和輸出資料。輸入 X 是一張截圖和之前的 HTML 標籤。而輸出 Y 是下一個標籤。當我明白了輸入和輸出資料之後,理解其餘內容就很簡單了。試驗不同的架構也變得更加容易。

保持專注,不要被誘惑。因為這個專案涉及了深度學習的許多領域,很多地方讓我深陷其中不能自拔。我曾花了一周的時間從頭開始編寫 RNN,也曾經沉迷于嵌入向量空間,還陷入過極限實現方式的陷阱。

圖片轉換到代碼的網路只不過是偽裝的圖像標注模型。即使我明白這一點,但還是因為許多圖像標注方面的論文不夠炫酷而忽略了它們。掌握一些這方面的知識可以説明我們加速學習問題空間。

▌在 FloydHub 上運行代碼

FloydHub 是深度學習的訓練平臺。我在剛開始學習深度學習的時候發現了這個平臺,從那以後我一直用它訓練和管理我的深度學習實驗。你可以在 10 分鐘之內安裝並開始運行模型,它是在雲端 GPU 上運行模型的最佳選擇。

如果你沒用過 FloydHub,請參照官方的“2 分鐘安裝手冊”或我寫的“5 分鐘入門教程”[11]。

克隆代碼倉庫:

git clone https://github.com/emilwallner/Screenshot-to-code-in-Keras.git

登錄及初始化 FloydHub 的命令列工具:

cd Screenshot-to-code-in-Kerasfloyd loginfloyd init s2c

在 FloydHub 的雲端 GPU 機器上運行 Jupyter notebook:

floyd run --gpu --env tensorflow-1.4 --data emilwallner/datasets/imagetocode/2:data --mode jupyter

所有的 notebook 都保存在“FloydHub”目錄下,而 local 的東西都在“local”目錄下。運行之後,你可以在如下檔中找到第一個 notebook:

floydhub/Helloworld/helloworld.ipynb

如果你想瞭解詳細的命令參數,請參照我這篇帖子:

https://blog.floydhub.com/colorizing-b&w-photos-with-neural-networks/

▌HTML 版本

在這個版本中,我們將自動化 Hello World 模型中的部分步驟。本節我們將集中介紹如何讓模型處理任意多的輸入資料,以及建立神經網路中的關鍵部分。

這個版本還不能根據任意網站預測 HTML,但是我們將在此嘗試解決關鍵性的技術問題,向最終的成功邁進一大步。

概述

我們可以把之前的解說圖擴展為如下:

上圖中有兩個主要部分。首先是編碼部分。編碼部分負責建立圖像特徵和之前的標籤特徵。特徵是指神經網路創建的最小單位的資料,用於連接設計圖和 HTML 代碼。在編碼部分的最後,我們把圖像的特徵連接到之前的標籤的每個單詞。

另一個主要部分是解碼部分。解碼部分負責接收聚合後的設計圖和 HTML 代碼的特徵,並創建下一個標籤的特徵。這個特徵通過一個全連接神經網路來預測下一個標籤。

設計圖的特徵

由於我們需要給每個單詞添加一張截圖,所以這會成為訓練神經網路過程中的瓶頸。所以我們不直接使用圖片,而是從中提取生成標籤所必需的資訊。

提取的資訊經過編碼後保存在圖像特徵中。這項工作可以由事先訓練好的卷積神經網路(CNN)完成。該模型可以通過 ImageNet 上的資料進行訓練。

CNN 的最後一層是分類層,我們可以從前一層提取圖像特徵。

最終我們可以得到 1536 個 8x8 圖元的圖片作為特徵。儘管我們很難理解這些特徵的含義,但是神經網路可以從中提取元素的物件和位置。

HTML 標籤的特徵

在 hello world 版本中,我們採用了 one-hot 編碼表現 HTML 標籤。在這個版本中,我們將使用單詞嵌入(word embedding)作為輸入資訊,輸出依然用 one-hot 編碼。

我們繼續採用之前的方式分析句子,但是匹配每個 token 的方式有所變化。之前的 one-hot 編碼把每個單詞當成一個獨立的單元,而這裡我們把輸入資料中的每個單詞轉化成一系列數字,它們代表 HTML 標籤之間的關係。

上例中的單詞嵌入是 8 維的,而實際上根據詞彙表的大小,其維度會在 50 到 500 之間。

每個單詞的 8 個數位表示權重,與原始的神經網路很相似。它們表示單詞之間的關係(Mikolov 等,2013[12])。

以上就是我們建立 HTML 標籤特徵的過程。神經網路通過此特徵在輸入和輸出資料之間建 立聯繫。暫時先不用擔心具體的內容,我們會在下節中深入討論這個問題。

編碼部分

我們需要把單詞嵌入的結果輸入到 LSTM 中,並返回一系列標籤特徵,再把這些特徵送入 Time distributed dense 層——你可以認為這是擁有多個輸入和輸出的 dense 層。

同時,圖像特徵首先需要被展開(flatten),無論數值原來是什麼結構,它們都會被轉換成一個巨大的數值列表;然後經過 dense 層建立更高級的特徵;最後把這些特徵與 HTML 標籤的特徵連接起來。

這可能有點難理解,下面我們逐一分解開來看看。

HTML 標籤特徵

首先我們把單詞嵌入的結果輸入到 LSTM 層。如下圖所示,所有的句子都被填充到最大長度,即三個 token。

為了混合這些信號並找到更高層的模式,我們加入 TimeDistributed dense 層進一步處理 LSTM 層生成的 HTML 標籤特徵。TimeDistributed dense 層是擁有多個輸入和輸出的 dense 層。

圖像特徵

同時,我們需要處理圖像。我們把所有的特徵(小圖片)轉化成一個長陣列,其中包含的資訊保持不變,只是進行重組。

同樣,為了混合信號並提取更高層的資訊,我們添加一個 dense 層。由於輸入只有一個,所以我們可以使用普通的 dense 層。為了與 HTML 標籤特徵相連接,我們需要複製圖像特徵。

上述的例子中我們有三個 HTML 標籤特徵,因此最終圖像特徵的數量也同樣是三個。

連接圖像特徵和 HTML 標籤特徵

所有的句子經過填充後組成了三個特徵。因為我們已經準備好了圖像特徵,所以現在可以把圖像特徵分別添加到各自的 HTML 標籤特徵。

添加完成之後,我們得到了 3 個圖像-標籤特徵,這便是我們需要提供給解碼部分的輸入資訊。

解碼部分

接下來,我們使用圖像-標籤的結合特徵來預測下一個標籤。

在下面的例子中,我們使用三對圖形-標籤特徵,輸出下一個標籤的特徵。

請注意,LSTM 層的 sequence 值為 false,所以我們不需要返回輸入序列的長度,只需要預測一個特徵,也就是下一個標籤的特徵,其內包含了最終的預測資訊。

最終預測

dense 層的工作原理與傳統的前饋神經網路相似,它把下個標籤特徵的 512 個數字與 4 個最終預測連接起來。用我們的單詞表達就是:start、hello、world 和 end。

其中,dense 層的 softmax 啟動函數會生成 0-1 的概率分佈,所有預測值的總和等於 1。比如說詞彙表的預測可能是[0.1,0.1,0.1,0.7],那麼輸出的預測結果即為:第 4 個單詞是下一個標籤。然後,你可以把 one-hot 編碼[0,0,0,1]轉換為映射值,得出“end”。

# Load the images and preprocess them for inception-resnetimages = []all_filenames = listdir('images/')all_filenames.sort()for filename in all_filenames: images.append(img_to_array(load_img('images/'+filename, target_size=(299, 299))))images = np.array(images, dtype=float)images = preprocess_input(images)# Run the images through inception-resnet and extract the features without the classification layerIR2 = InceptionResNetV2(weights='imagenet', include_top=False)features = IR2.predict(images)# We will cap each input sequence to 100 tokensmax_caption_len = 100# Initialize the function that will create our vocabularytokenizer = Tokenizer(filters='', split=" ", lower=False)# Read a document and return a stringdef load_doc(filename): file = open(filename, 'r') text = file.read() file.close() return text# Load all the HTML filesX = []all_filenames = listdir('html/')all_filenames.sort()for filename in all_filenames:X.append(load_doc('html/'+filename))# Create the vocabulary from the html filestokenizer.fit_on_texts(X)# Add +1 to leave space for empty wordsvocab_size = len(tokenizer.word_index) + 1# Translate each word in text file to the matching vocabulary indexsequences = tokenizer.texts_to_sequences(X)# The longest HTML filemax_length = max(len(s) for s in sequences)# Intialize our final input to the modelX, y, image_data = list(), list(), list()for img_no, seq in enumerate(sequences): for i in range(1, len(seq)): # Add the entire sequence to the input and only keep the next word for the output in_seq, out_seq = seq[:i], seq[i] # If the sentence is shorter than max_length, fill it up with empty words in_seq = pad_sequences([in_seq], maxlen=max_length)[0] # Map the output to one-hot encoding out_seq = to_categorical([out_seq], num_classes=vocab_size)[0] # Add and image corresponding to the HTML file image_data.append(features[img_no]) # Cut the input sentence to 100 tokens, and add it to the input data X.append(in_seq[-100:]) y.append(out_seq)X, y, image_data = np.array(X), np.array(y), np.array(image_data)# Create the encoderimage_features = Input(shape=(8, 8, 1536,))image_flat = Flatten()(image_features)image_flat = Dense(128, activation='relu')(image_flat)ir2_out = RepeatVector(max_caption_len)(image_flat)language_input = Input(shape=(max_caption_len,))language_model = Embedding(vocab_size, 200, input_length=max_caption_len)(language_input)language_model = LSTM(256, return_sequences=True)(language_model)language_model = LSTM(256, return_sequences=True)(language_model)language_model = TimeDistributed(Dense(128, activation='relu'))(language_model)# Create the decoderdecoder = concatenate([ir2_out, language_model])decoder = LSTM(512, return_sequences=False)(decoder)decoder_output = Dense(vocab_size, activation='softmax')(decoder)# Compile the modelmodel = Model(inputs=[image_features, language_input], outputs=decoder_output)model.compile(loss='categorical_crossentropy', optimizer='rmsprop')# Train the neural networkmodel.fit([image_data, X], y, batch_size=64, shuffle=False, epochs=2)# map an integer to a worddef word_for_id(integer, tokenizer): for word, index in tokenizer.word_index.items(): if index == integer: return word return None# generate a description for an imagedef generate_desc(model, tokenizer, photo, max_length): # seed the generation process in_text = 'START' # iterate over the whole length of the sequence for i in range(900): # integer encode input sequence sequence = tokenizer.texts_to_sequences([in_text])[0][-100:] # pad input sequence = pad_sequences([sequence], maxlen=max_length) # predict next word yhat = model.predict([photo,sequence], verbose=0) # convert probability to integer yhat = np.argmax(yhat) # map integer to word word = word_for_id(yhat, tokenizer) # stop if we cannot map the word if word is None: break # append as input for generating the next word in_text += ' ' + word # Print the prediction print(' ' + word, end='') # stop if we predict the end of the sequence if word == 'END': break return# Load and image, preprocess it for IR2, extract features and generate the HTMLtest_image = img_to_array(load_img('images/87.jpg', target_size=(299, 299)))test_image = np.array(test_image, dtype=float)test_image = preprocess_input(test_image)test_features = IR2.predict(np.array([test_image]))generate_desc(model, tokenizer, np.array(test_features), 100)

輸出結果

生成網站的連結:

250 epochs: https://emilwallner.github.io/html/250_epochs/

350 epochs:https://emilwallner.github.io/html/350_epochs/

450 epochs:https://emilwallner.github.io/html/450_epochs/

550 epochs:https://emilwallner.github.io/html/450_epochs/

如果點擊上述連結看不到頁面的話,你可以選擇“查看原始程式碼”。下面是原網站的連結,僅供參考:

https://emilwallner.github.io/html/Original/

我犯過的錯誤

與 CNN 相比,LSTM 遠比我想像得複雜。為了更好的理解,我展開了所有的 LSTM。關於 RNN 你可以參考這個視頻(http://course.fast.ai/lessons/lesson6.html)。另外,在理解原理之前,請先搞清楚輸入和輸出特徵。

從零開始創建詞彙表比削減大型詞彙表更容易。詞彙表可以包括任何東西,如字體、div 大小、十六進位顏色、變數名以及普通單詞。

大多數的代碼庫可以很好地解析文本文檔,卻不能解析代碼。因為文檔中所有單詞都用空格分開,但是代碼不同,所以你得自己想辦法解析代碼。

用 Imagenet 訓練好的模型提取特徵也許不是個好主意。因為 Imagenet 很少有網頁的圖片,所以它的損失率比從零開始訓練的 pix2code 模型高 30%。如果使用網頁截圖訓練 inception-resnet 之類的模型,不知結果會怎樣。

▌Bootstrap 版本

在最後一個版本——Bootstrap 版本中,我們使用的資料集來自根據 pix2code 論文生成的 bootstrap 網站。通過使用 Twitter 的 bootstrap(https://getbootstrap.com/),我們可以結合 HTML 和 CSS,並減小詞彙表的大小。

我們可以提供一個它從未見過的截圖,訓練它生成相應的 HTML 代碼。我們還可以深入研究它學習這個截圖和 HTML 代碼的過程。

拋開 bootstrap 的 HTML 代碼,我們在這裡使用 17 個簡化的 token 訓練它,然後翻譯成 HTML 和 CSS。這個資料集[13]包括 1500 個測試截圖和 250 個驗證截圖。每個截圖上平均有 65 個 token,包含 96925 個訓練樣本。

通過修改 pix2code 論文的模型提供輸入資料,我們的模型可以預測網頁的組成,且準確率高達 97%(我們採用了 BLEU 4-ngram greedy search,稍後會詳細介紹)。

端到端的方法

圖像標注模型可以從事先訓練好的模型中提取特徵,但是經過幾次實驗後,我發現 pix2code 的端到端的方法可以更好地為我們的模型提取特徵,因為事先訓練好的模型並沒有用網頁數據訓練過,而且它本來的作用是分類。

在這個模型中,我們用羽量級的卷積神經網路替代了事先訓練好的圖像特徵。我們沒有採用 max-pooling 增加資訊密度,但我們增加了步長(stride),以確保前端元素的位置和顏色。

有兩個核心模型可以支援這個方法:卷積神經網路(CNN)和遞迴神經網路(RNN)。最常見的遞迴神經網路就是 LSTM,所以我選擇了 RNN。

關於 CNN 的教程有很多,我在別的文章裡有介紹。此處我主要講解 LSTM。

理解 LSTM 中的 timestep

LSTM 中最難理解的內容之一就是 timestep。原始的神經網路可以看作只有兩個 timestep。如果輸入是“Hello”(第一個 timestep),它會預測“World”(第二個 timestep),但它無法預測更多的 timestep。下面的例子中輸入有四個 timestep,每個詞一個。

LSTM 適用於包含 timestep 的輸入,這種神經網路專門處理有序的資訊。模型展開後你會發現,下行的每一步所持有的權重保持不變。另外,前一個輸出和新的輸入需要分別使用相應的權重。

接下來,輸入和輸出乘以權重之後相加,再通過啟動函數得到該 timestep 的輸出。由於權重不隨 timestep 變化,所以它們可以從多個輸入中獲得資訊,從而掌握單詞的順序。

下圖通過簡單圖例描述了一個 LSTM 中每個 timestep 的處理過程。

為了更好地理解這個邏輯,我建議你跟隨 Andrew Trask 的這篇精彩的教程[14],嘗試從頭創建一個 RNN。

理解 LSTM 層中的單元

LSTM 層中的單元(unit)數量決定了它的記憶能力,以及每個輸出特徵的大小。再次強調,特徵是一長列的數值,用於在層與層之間的資訊傳遞。

LSTM 層中的每個單元負責跟蹤語法中的不同資訊。下圖描述了一個單元的示例,其內保存了佈局行“div”的資訊。我們簡化了 HTML 代碼,並用於訓練 bootstrap 模型。

每個 LSTM 單元擁有一個單元狀態(cell state)。你可以把單元狀態看作單元的記憶。權重和啟動函數可以用各種方式改變狀態。因此 LSTM 層可以微調每個輸入所需要保存和丟棄的資訊。

向輸入傳遞輸出特徵的同時,還需傳遞單元狀態,LSTM 的每個單元都需要傳遞自己的單元狀態值。為了理解 LSTM 各部分的對話模式,我建議你可以閱讀:

Colah 的教程:

https://colah.github.io/posts/2015-08-Understanding-LSTMs/

Jayasiri 的 Numpy 實現:

http://blog.varunajayasiri.com/numpy_lstm.html

Karphay 的講座和文章:

https://www.youtube.com/watch?v=yCC09vCHzF8; https://karpathy.github.io/2015/05/21/rnn-effectiveness/

dir_name = 'resources/eval_light/'# Read a file and return a stringdef load_doc(filename): file = open(filename, 'r') text = file.read() file.close() return textdef load_data(data_dir): text = [] images = [] # Load all the files and order them all_filenames = listdir(data_dir) all_filenames.sort() for filename in (all_filenames): if filename[-3:] == "npz": # Load the images already prepared in arrays image = np.load(data_dir+filename) images.append(image['features']) else: # Load the boostrap tokens and rap them in a start and end tag syntax = ' ' + load_doc(data_dir+filename) + ' ' # Seperate all the words with a single space syntax = ' '.join(syntax.split()) # Add a space after each comma syntax = syntax.replace(',', ' ,') t ext.append(syntax) images = np.array(images, dtype=float) return images, texttrain_features, texts = load_data(dir_name)# Initialize the function to create the vocabularytokenizer = Tokenizer(filters='', split=" ", lower=False)# Create the vocabularytokenizer.fit_on_texts([load_doc('bootstrap.vocab')])# Add one spot for the empty word in the vocabularyvocab_size = len(tokenizer.word_index) + 1# Map the input sentences into the vocabulary indexestrain_sequences = tokenizer.texts_to_sequences(texts)# The longest set of boostrap tokensmax_sequence = max(len(s) for s in train_sequences)# Specify how many tokens to have in each input sentencemax_length = 48def preprocess_data(sequences, features): X, y, image_data = list(), list(), list() for img_no, seq in enumerate(sequences): for i in range(1, len(seq)): # Add the sentence until the current count(i) and add the current count to the output in_seq, out_seq = seq[:i], seq[i] # Pad all the input token sentences to max_sequence in_seq = pad_sequences([in_seq], maxlen=max_sequence)[0] # Turn the output into one-hot encoding out_seq = to_categorical([out_seq], num_classes=vocab_size)[0] # Add the corresponding image to the boostrap token file image_data.append(features[img_no]) # Cap the input sentence to 48 tokens and add it X.append(in_seq[-48:]) y.append(out_seq) return np.array(X), np.array(y), np.array(image_data)X, y, image_data = preprocess_data(train_sequences, train_features)#Create the encoderimage_model = Sequential()image_model.add(Conv2D(16, (3, 3), padding='valid', activation='relu', input_shape=(256, 256, 3,)))image_model.add(Conv2D(16, (3,3), activation='relu', padding='same', strides=2))image_model.add(Conv2D(32, (3,3), activation='relu', padding='same'))image_model.add(Conv2D(32, (3,3), activation='relu', padding='same', strides=2))image_model.add(Conv2D(64, (3,3), activation='relu', padding='same'))image_model.add(Conv2D(64, (3,3), activation='relu', padding='same', strides=2))image_model.add(Conv2D(128, (3,3), activation='relu', padding='same'))image_model.add(Flatten())image_model.add(Dense(1024, activation='relu'))image_model.add(Dropout(0.3))image_model.add(Dense(1024, activation='relu'))image_model.add(Dropout(0.3))image_model.add(RepeatVector(max_length))visual_input = Input(shape=(256, 256, 3,))encoded_image = image_model(visual_input)language_input = Input(shape=(max_length,))language_model = Embedding(vocab_size, 50, input_length=max_length, mask_zero=True)(language_input)language_model = LSTM(128, return_sequences=True)(language_model)language_model = LSTM(128, return_sequences=True)(language_model)#Create the decoderdecoder = concatenate([encoded_image, language_model])decoder = LSTM(512, return_sequences=True)(decoder)decoder = LSTM(512, return_sequences=False)(decoder)decoder = Dense(vocab_size, activation='softmax')(decoder)# Compile the modelmodel = Model(inputs=[visual_input, language_input], outputs=decoder)optimizer = RMSprop(lr=0.0001, clipvalue=1.0)model.compile(loss='categorical_crossentropy', optimizer=optimizer)#Save the model for every 2nd epochfilepath="org-weights-epoch-{epoch:04d}--val_loss-{val_loss:.4f}--loss-{loss:.4f}.hdf5"checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_weights_only=True, period=2)callbacks_list = [checkpoint]# Train the modelmodel.fit([image_data, X], y, batch_size=64, shuffle=False, validation_split=0.1, callbacks=callbacks_list, verbose=1, epochs=50)

測試準確度

很難找到合理的方式測量準確度。你可以逐個比較單詞,但如果預測結果中有一個單詞出現了錯位,那準確率可能就是 0%了;如果為了同步預測而刪除這個詞,那麼準確率又會變成 99/100。

我採用了 BLEU 分數,它是測試機器翻譯和圖像標記模型的最佳選擇。它將句子分成四個 n-grams,從 1 個單詞的序列逐步擴展為 4 個單詞。下例,預測結果中的“cat”實際上應該是“code”。

為了計算最終分數,首先需要讓每個 n-grams 的得分乘以 25%並求和,即(4/5) * 0.25 + (2/4) * 0.25 + (1/3) * 0.25 + (0/2) * 0.25 = 02 + 1.25 + 0.083 + 0 = 0.408;得出的總和需要乘以句子長度的懲罰因數。由於本例中預測句子的長度是正確的,因此這就是最終的分數。

增加 n-grams 的數量可以提高難度。4 個 n-grams 的模型最適合人類翻譯。為了進一步瞭解 BLEU,我建議你可以用下面的代碼運行幾個例子,並閱讀這篇 wiki 頁面[15]。

#Create a function to read a file and return its contentdef load_doc(filename): file = open(filename, 'r') text = file.read() file.close() return textdef load_data(data_dir): text = [] images = [] files_in_folder = os.listdir(data_dir) files_in_folder.sort() for filename in tqdm(files_in_folder): #Add an image if filename[-3:] == "npz": image = np.load(data_dir+filename) images.append(image['features']) else: # Add text and wrap it in a start and end tag syntax = ' ' + load_doc(data_dir+filename) + ' ' #Seperate each word with a space syntax = ' '.join(syntax.split()) #Add a space between each comma syntax = syntax.replace(',', ' ,') text.append(syntax) images = np.array(images, dtype=float) return images, text#Intialize the function to create the vocabularytokenizer = Tokenizer(filters='', split=" ", lower=False)#Create the vocabulary in a specific ordertokenizer.fit_on_texts([load_doc('bootstrap.vocab')])dir_name = '../../../../eval/'train_features, texts = load_data(dir_name)#load model and weightsjson_file = open('../../../../model.json', 'r')loaded_model_json = json_file.read()json_file.close()loaded_model = model_from_json(loaded_model_json)# load weights into new modelloaded_model.load_weights("../../../../weights.hdf5")print("Loaded model from disk")# map an integer to a worddef word_for_id(integer, tokenizer): for word, index in tokenizer.word_index.items(): if index == integer: return word return Noneprint(word_for_id(17, tokenizer))# generate a description for an imagedef generate_desc(model, tokenizer, photo, max_length): photo = np.array([photo]) # seed the generation process in_text = ' ' # iterate over the whole length of the sequence print(' Prediction----> ', end='') for i in range(150): # integer encode input sequence sequence = tokenizer.texts_to_sequences([in_text])[0] # pad input sequence = pad_sequences([sequence], maxlen=max_length) # predict next word yhat = loaded_model.predict([photo, sequence], verbose=0) # convert probability to integer yhat = argmax(yhat) # map integer to word word = word_for_id(yhat, tokenizer) # stop if we cannot map the word if word is None: break # append as input for generating the next word in_text += word + ' ' # stop if we predict the end of the sequence print(word + ' ', end='') if word == '': break return in_textmax_length = 48# evaluate the skill of the modeldef evaluate_model(model, descriptions, photos, tokenizer, max_length): actual, predicted = list(), list() # step over the whole set for i in range(len(texts)): yhat = generate_desc(model, tokenizer, photos[i], max_length) # store actual and predicted print(' Real----> ' + texts[i]) actual.append([texts[i].split()]) predicted.append(yhat.split()) # calculate BLEU score bleu = corpus_bleu(actual, predicted) return bleu, actual, predictedbleu, actual, predicted = evaluate_model(loaded_model, texts, train_features, tokenizer, max_length)#Compile the tokens into HTML and cssdsl_path = "compiler/assets/web-dsl-mapping.json"compiler = Compiler(dsl_path)compiled_website = compiler.compile(predicted[0], 'index.html')print(compiled_website )print(bleu)

輸出

輸出示例的連結

網站 1:

生成的網站:https://emilwallner.github.io/bootstrap/pred_1/

原網站:https://emilwallner.github.io/bootstrap/real_1/

網站 2:

生成的網站:https://emilwallner.github.io/bootstrap/pred_2/

原網站:https://emilwallner.github.io/bootstrap/real_2/

網站 3:

生成的網站:https://emilwallner.github.io/bootstrap/pred_3/

原網站:https://emilwallner.github.io/bootstrap/real_3/

網站 4:

生成的網站:https://emilwallner.github.io/bootstrap/pred_4/

原網站:https://emilwallner.github.io/bootstrap/real_4/

網站 5:

生成的網站:https://emilwallner.github.io/bootstrap/pred_5/

原網站:https://emilwallner.github.io/bootstrap/real_5/

我犯過的錯誤

學會理解模型的弱點,避免盲目測試模型。剛開始的時候,我隨便嘗試了一些東西,比如 batch normalization、bidirectional network,還試圖實現 attention。看了測試資料後發現這些並不能準確地預測顏色和位置,我開始意識到這是 CNN 的弱點。因此我放棄了 maxpooling,改為增加步長。結果測試損失從 0.12 降到了 0.02,BLEU 分數從 85%提高到了 97%。

只使用相關的事先訓練好的模型。在資料集很小的時候,我以為事先訓練好的圖像模型能夠提高效率。實驗結果表明,端到端的模型雖然更慢,訓練也需要更多的記憶體,但準確率能提高 30%。

在遠端伺服器上運行模型時要為一些差異做好準備。在我的 Mac 上運行時,檔是按照字母順序讀取的。但在遠端伺服器上卻是隨機讀取的。結果造成了截圖和代碼不匹配的問題。雖然依然能夠收斂,但在我修復了這個問題後,測試資料的準確率提高了 50%。

務必要理解庫函數。詞彙表中的空 token 需要包含空格。一開始我沒加空格,結果就漏了一個 token。直到看了幾次最終輸出結果,注意到它從來不會預測某個 token 的時候,我才發現了這個問題。檢查後發現那個 token 不在詞彙表裡。此外,要保證訓練和測試時使用的詞彙表的順序相同。

試驗時使用羽量級的模型。用 GRU 替換 LSTM 可以讓每個 epoch 的時間減少 30%,而且不會對性能有太大影響。

▌下一步

深度學習很適合應用在前端開發中,因為很容易生成資料,而且如今的深度學習演算法可以覆蓋絕大多數的邏輯。

其中一個最有意思的方面是在 LSTM 中使用 attention 機制[16]。它不僅能提高準確率,而且可以幫助我們觀察 CSS 在生成 HTML 代碼的時候,它的注意力在何處。

Attention 還是 HTML 代碼、樣式表、腳本甚至後臺之間溝通的關鍵因素。attention 層可以追蹤參數,説明神經網路在不同程式設計語言之間溝通。

但是短期內,最大的難題還在於找到一個可擴展的方法用於生成資料。這樣才能逐步加入字體、顏色、單詞以及動畫。

迄今為止,很多人都在努力實現繪製草圖並將其轉化為應用程式的範本。不出兩年,我們就能實現在紙上繪製應用程式,並在一秒內獲得相應的前端代碼。Airbnb 設計團隊[17]和 Uizard[18] 已經創建了兩個原型。

下面是一些值得嘗試的實驗。

▌實驗

Getting started:

運行所有的模型

嘗試不同的超參數

嘗試不同的 CNN 架構

加入 Bidirectional 的 LSTM 模型

使用不同的資料集實現模型[19](你可以通過 FloydHub 的參數“--data ”掛載這個資料集:emilwallner/datasets/100k-html:data)

高級實驗

創建能利用特定的語法穩定生成任意應用程式/網頁的生成器

生成應用程式模型的設計圖資料。將應用程式或網頁的截圖自動轉換成設計,並使用 GAN 產生變化。

通過 attention 層觀察每次預測時的圖像焦點,類似於這個模型:https://arxiv.org/abs/1502.03044

創建模組化方法的框架。比如一個模型負責編碼字體,一個負責顏色,另一個負責佈局,並利用解碼部分將它們結合在一起。你可以從靜態圖像特徵開始嘗試。

為神經網路提供簡單的 HTML 組成單元,訓練它利用 CSS 生成動畫。如果能加入 attention 模組,觀察輸入源的聚焦就更完美了。

最後,非常感謝 Tony Beltramelli 和 Jon Gold 提供的研究成果和想法,以及對各種問題的解答。謝謝 Jason Brownlee 貢獻他的 stellar Keras 教程(我在核心的 Keras 實現中加入了幾個他的教程中介紹的 snippets),謝謝 Beltramelli 提供的資料。還要謝謝 Qingping Hou、Charlie Harrington、 Sai Soundararaj、 Jannes Klaas、 Claudio Cabral、 Alain Demenet 和 Dylan Djian 審閱本篇文章。

相關連結

[1]pix2code 論文:https://arxiv.org/abs/1705.07962

[2]sketch2code:https://airbnb.design/sketching-interfaces/

[3]https://github.com/emilwallner/Screenshot-to-code-in-Keras/blob/master/README.md

[4]https://www.floydhub.com/emilwallner/projects/picturetocode

[5]https://machinelearningmastery.com/blog/page/2/

[6]https://blog.floydhub.com/my-first-weekend-of-deep-learning/

[7]https://blog.floydhub.com/coding-the-history-of-deep-learning/

[8]https://blog.floydhub.com/colorizing-b&w-photos-with-neural-networks/

[9]https://machinelearningmastery.com/deep-learning-caption-generation-models/

[10]https://machinelearningmastery.com/how-to-one-hot-encode-sequence-data-in-python/

[11]https://www.youtube.com/watch?v=byLQ9kgjTdQ&t=21s

[12]https://arxiv.org/abs/1301.3781

[13]https://github.com/tonybeltramelli/pix2code/tree/master/datasets

[14]https://iamtrask.github.io/2015/11/15/anyone-can-code-lstm/

[15]https://en.wikipedia.org/wiki/BLEU

[16]https://arxiv.org/pdf/1502.03044.pdf

[17]https://airbnb.design/sketching-interfaces/

[18]https://www.uizard.io/

[19]http://lstm.seas.harvard.edu/latex/

Next Article
喜欢就按个赞吧!!!
点击关闭提示