哈,各位大神門,還記得剛剛學習編程時候寫的第一個程序嗎,Hello world,今天我們就來整理整理各種編程語言下的“Hello world”
swift
C#
C語言
C++
Java
JavaScript
PHP
得剛接觸HTML的時候,有一些元素只會寫但是不明白其含義,這情況真是很尷尬。本節將來解析一下HTML文檔的主要的骨架標簽的含義。
一、Hello World
編寫第一段HTML代碼,在頁面上輸出文本Hello World
代碼如下:
<!--聲明文檔內容為html--> <!DOCTYPE html> <!--設置語言為英文--> <html lang="en"> <head> <!--設置文檔默認編碼--> <meta charset="UTF-8"> <!--網頁的title--> <title>系統首頁</title> </head> <body> <p>Hello World</p> </body> </html>
這是一段最簡單HTML代碼,但是其骨架完整。在瀏覽器中瀏覽效果如圖:
二、讀懂每一個標簽
一個符合規范的HTML文檔會包含DOCTYPE、html、head、body這些基本的文檔元素。當然即使沒有顯式的元素標簽,網頁也是可以顯示,但是不建議這么去做。
1、HTML5基本文檔結構
<!DOCTYPE html> <html lang="en"> <head></head> <body> </body> </html>
上述示例演示了HTML文檔骨架的4種文檔元素的使用方法。接下來,將逐一解讀。
<!DOCTYPE HTML>
!DOCTYPE 元素主要有兩個作用第一是告訴瀏覽器,它即將處理的是一份HTML文檔;第二是用來標記HTML的版本。通常這樣的聲明都在文檔的第一行。
<html></html>
html元素是文檔的根元素。
head></head>
head元素是文檔的頭部(通俗的理解),
在head元素中可以使用title元素和其他的元數據元素,也可以在head中引用js、css和定義js、css。
<body></body> body元素(容器)中是文檔的展示內容。
PS:小伙伴們真棒,已經寫出了第一個網頁。加油!
如果覺得我的文章對您有用,請點贊收藏。您的支持將鼓勵我繼續創作。
知識分享到這里就結束了,學習web前端的可以來我的群
群里每天都有對應資料學習:675498134
歡迎初學和進階中的小伙伴,一起學習,一起進步。
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_markup-b6ceec69a7c9cfd447d188648049f2a4.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?!碑斔邮盏健癐”的時候,它會預測“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 <HTML>Hello World!</HTML> [1., 0., 0.], [0., 1., 0.]]])#Turn next word into one-hot encodingnext_words=np.array( [[0., 1., 0.], # <HTML>Hello World!</HTML> [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”、“<HTML><center><H1>Hello World!</H1></center></HTML>”和“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", "<HTML><center><H1>Hello World!</H1></center></HTML>", "end"]for i in sentence[0]: print(vocabulary[np.argmax(i)], end=' ')
輸出結果
10 epochs:start start start
100 epochs:start <HTML><center><H1>Hello World!</H1></center></HTML> <HTML><center><H1>Hello World!</H1></center></HTML>
300 epochs:start <HTML><center><H1>Hello World!</H1></center></HTML> 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 login floyd 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='<START> ' + load_doc(data_dir+filename) + ' <END>' # Seperate all the words with a single space syntax=' '.join(syntax.split()) # Add a space after each comma syntax=syntax.replace(',', ' ,') text.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='<START> ' + load_doc(data_dir+filename) + ' <END>' #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='<START> ' # iterate over the whole length of the sequence print('\nPrediction---->\n\n<START> ', 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=='<END>': 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('\n\nReal---->\n\n' + 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/
*請認真填寫需求信息,我們會在24小時內與您取得聯系。