Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
天分享一個股友比較關心的很實用的問題,同花順千股千評網站的評語提取,廢話不多說,直接上干貨。
首先我們先看下網址:http://www.iwencai.com/stocks/comments
別小瞧這個網址,你們是搜不到的,不信你試試。現在我們打開網址瞧瞧是什么寶貝。
同花順千股千評
接下來就是股友很關心的問題,就是怎么把網站內容取下來呢?別急,慢慢往下看。
加下來需要準備的工具:offcie的excel,一般人都有,然后復制下面的代碼到VBA編輯窗口,如下圖:
VBA編輯窗口
代碼我也不私藏了:代碼如下:
Sub qgqp()
Dim strText As String, n%, temp, r%, l%, brr, temp1, crr(1 To 4000, 1 To 13), g%, temp2
Sheets.Add after:=Sheets(Sheets.Count)
ActiveSheet.Name = Format(Date, "yyyy年m月d日")
brr = Array("id", "code", "name", "comment", "question", "created", "updated", "stockName", "latestPrices", "chg", "dde", "ddeUnit", "selfstockTimes")
With CreateObject("MSXML2.XMLHTTP")
For n = 1 To 103
.Open "POST", "http://www.iwencai.com/stocks/comments-read?per=30&page=" & n & "&plate=all HTTP/1.1", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.setRequestHeader "Referer", ""
.Send
strText = Convert(.responsetext)
temp = Split(strText, "{")
For r = 2 To UBound(temp)
g = g + 1
For l = 0 To UBound(brr) - 1
temp2 = Split(temp(r), Chr(34) & brr(l + 1) & Chr(34) & ":")(0)
temp1 = Split(temp2, Chr(34) & brr(l) & Chr(34) & ":")
crr(g, l + 1) = Replace(Replace(temp1(1), ",", ""), Chr(34), "")
Next
crr(g, 13) = Split(Split(temp(r), Chr(34) & brr(12) & Chr(34) & ":")(1), "}")(0)
Next
Next
End With
Cells.Clear
Range("a1").Resize(1, 13) = brr
Columns("A:B").NumberFormatLocal = "@"
Range("a2").Resize(3000, 13) = crr
MsgBox "OK"
End Sub
Function Convert(strText As String) As String
With CreateObject("MSScriptControl.ScriptControl")
.Language = "javascript"
Convert = .eval("('" & strText & "').replace(/\d+;/g,function(b){return String.fromCharCode(b.slice(2,b.length-1));});")
End With
End Function
運行代碼得到結果如下圖:
然后數據透視整理一下結果,可以直觀看到下面需求信息,真香。
上面的程序可能會殺毒軟件報毒,還有千萬不要外傳和使用頻率過高采取數據,服務器會豐IP,如果有幫助要低調,悠著點,要不然大家都看不了。
不過上面只是技術交流使用,大家不要做買賣依據,股市有風險,入市謹慎。
關注我,我會定期發布一些實用的經典EXCEL實戰案列,也許對你剛好有需要,而我及時雨的出現。
迭代器是 23 種設計模式中最常用的一種(之一),在 Python 中隨處可見它的身影,我們經常用到它,但是卻不一定意識到它的存在。在關于迭代器的系列文章中(鏈接見文末),我至少提到了 23 種生成迭代器的方法。有些方法是專門用于生成迭代器的,還有一些方法則是為了解決別的問題而“暗中”使用到迭代器。
在系統學習迭代器之前,我一直以為 range() 方法也是用于生成迭代器的,現在卻突然發現,它生成的只是可迭代對象,而并不是迭代器! (PS:Python2 中 range() 生成的是列表,本文基于Python3,生成的是可迭代對象)
于是,我有了這樣的疑問:為什么 range() 不生成迭代器呢?在查找答案的過程中,我發現自己對 range 類型的認識存在一些誤區。因此,本文將和大家全面地認識一下 range ,期待與你共同學習進步。
1、range() 是什么?
它的語法:range(start, stop [,step]) ;start 指的是計數起始值,默認是 0;stop 指的是計數結束值,但不包括 stop ;step 是步長,默認為 1,不可以為 0 。range() 方法生成一段左閉右開的整數范圍。
>>> a = range(5) # 即 range(0,5) >>> a range(0, 5) >>> len(a) 5 >>> for x in a: >>> print(x,end=" ") 0 1 2 3 4
對于 range() 函數,有幾個注意點:(1)它表示的是左閉右開區間;(2)它接收的參數必須是整數,可以是負數,但不能是浮點數等其它類型;(3)它是不可變的序列類型,可以進行判斷元素、查找元素、切片等操作,但不能修改元素;(4)它是可迭代對象,卻不是迭代器。
# (1)左閉右開 >>> for i in range(3, 6): >>> print(i,end=" ") 3 4 5 ? # (2)參數類型 >>> for i in range(-8, -2, 2): >>> print(i,end=" ") -8 -6 -4 >>> range(2.2) ---------------------------- TypeError Traceback (most recent call last) ... TypeError: 'float' object cannot be interpreted as an integer ? # (3)序列操作 >>> b = range(1,10) >>> b[0] 1 >>> b[:-3] range(1, 7) >>> b[0] = 2 TypeError Traceback (most recent call last) ... TypeError: 'range' object does not support item assignment ? # (4)不是迭代器 >>> hasattr(range(3),'__iter__') True >>> hasattr(range(3),'__next__') False >>> hasattr(iter(range(3)),'__next__') True
2、 為什么range()不生產迭代器?
可以獲得迭代器的內置方法很多,例如 zip() 、enumerate()、map()、filter() 和 reversed() 等等,但是像 range() 這樣僅僅得到的是可迭代對象的方法就絕無僅有了(若有反例,歡迎告知)。這就是我存在知識誤區的地方。
在 for-循環 遍歷時,可迭代對象與迭代器的性能是一樣的,即它們都是惰性求值的,在空間復雜度與時間復雜度上并無差異。我曾概括過兩者的差別是“一同兩不同”:相同的是都可惰性迭代,不同的是可迭代對象不支持自遍歷(即next()方法),而迭代器本身不支持切片(即__getitem__() 方法)。
雖然有這些差別,但很難得出結論說它們哪個更優。現在微妙之處就在于,為什么給 5 種內置方法都設計了迭代器,偏偏給 range() 方法設計的就是可迭代對象呢?把它們都統一起來,不是更好么?
事實上,Pyhton 為了規范性就干過不少這種事,例如,Python2 中有 range() 和 xrange() 兩種方法,而 Python3 就干掉了其中一種,還用了“李代桃僵”法。為什么不更規范點,令 range() 生成的是迭代器呢?
關于這個問題,我沒找到官方解釋,以下純屬個人觀點 。
zip() 等方法都需要接收確定的可迭代對象的參數,是對它們的一種再加工的過程,因此也希望馬上產出確定的結果來,所以 Python 開發者就設計了這個結果是迭代器。這樣還有一個好處,即當作為參數的可迭代對象發生變化的時候,作為結果的迭代器因為是消耗型的,不會被錯誤地使用。
而 range() 方法就不同了,它接收的參數不是可迭代對象,本身是一種初次加工的過程,所以設計它為可迭代對象,既可以直接使用,也可以用于其它再加工用途。例如,zip() 等方法就完全可以接收 range 類型的參數。
>>> for i in zip(range(1,6,2), range(2,7,2)): >>> print(i, end="") (1, 2)(3, 4)(5, 6)
也就是說,range() 方法作為一種初級生產者,它生產的原料本身就有很大用途,早早把它變為迭代器的話,無疑是一種畫蛇添足的行為。
對于這種解讀,你是否覺得有道理呢?歡迎就這個話題與我探討。
3、range 類型是什么?
以上是我對“為什么range()不產生迭代器”的一種解答。順著這個思路,我研究了一下它產生的 range 對象,一研究就發現,這個 range 對象也并不簡單。
首先奇怪的一點就是,它竟然是不可變序列!我從未注意過這一點。雖然說,我從未想過修改 range() 的值,但這一不可修改的特性還是令我驚訝。
翻看文檔,官方是這樣明確劃分的——有三種基本的序列類型:列表、元組和范圍(range)對象。(There are three basic sequence types: lists, tuples, and range objects.)
這我倒一直沒注意,原來 range 類型居然跟列表和元組是一樣地位的基礎序列!我一直記掛著字符串是不可變的序列類型,不曾想,這里還有一位不可變的序列類型呢。
那 range 序列跟其它序列類型有什么差異呢?
普通序列都支持的操作有 12 種,在《你真的知道Python的字符串是什么嗎?》這篇文章里提到過。range 序列只支持其中的 10 種,不支持進行加法拼接與乘法重復。
>>> range(2) + range(3) ----------------------------------------- TypeError Traceback (most recent call last) ... TypeError: unsupported operand type(s) for +: 'range' and 'range' ? >>> range(2)*2 ----------------------------------------- TypeError Traceback (most recent call last) ... TypeError: unsupported operand type(s) for *: 'range' and 'int'
那么問題來了:同樣是不可變序列,為什么字符串和元組就支持上述兩種操作,而偏偏 range 序列不支持呢?雖然不能直接修改不可變序列,但我們可以將它們拷貝到新的序列上進行操作啊,為何 range 對象連這都不支持呢?
且看官方文檔的解釋:
...due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern.
原因是 range 對象僅僅表示一個遵循著嚴格模式的序列,而重復與拼接通常會破壞這種模式...
問題的關鍵就在于 range 序列的 pattern,仔細想想,其實它表示的就是一個等差數列啊(喵,高中數學知識沒忘...),拼接兩個等差數列,或者重復拼接一個等差數列,想想確實不妥,這就是為啥 range 類型不支持這兩個操作的原因了。由此推論,其它修改動作也會破壞等差數列結構,所以統統不給修改就是了。
4、小結
回顧全文,我得到了兩個偏冷門的結論:range 是可迭代對象而不是迭代器;range 對象是不可變的等差序列。
若單純看結論的話,你也許沒有感觸,或許還會說這沒啥了不得啊。但如果我追問,為什么 range 不是迭代器呢,為什么 range 是不可變序列呢?對這倆問題,你是否還能答出個自圓其說的設計思想呢?(PS:我決定了,若有機會面試別人,我必要問這兩個問題的嘿~)
由于 range 對象這細微而有意思的特性,我覺得這篇文章寫得值了。本文是作為迭代器系列文章的一篇來寫的,所以對于迭代器的基礎知識介紹不多,歡迎查看之前的文章。另外,還有一種特殊的迭代器也值得單獨成文,那就是生成器了,敬請期待后續推文哦~
猜你想讀:
Python進階:迭代器與迭代器切片
Python進階:設計模式之迭代器模式
你真的知道Python的字符串是什么嗎?
官方文檔:http://t.cn/EGMzJt8
-----------------
本文原創并首發于微信公眾號【Python貓】,后臺回復“愛學習”,免費獲得20+本精選電子書。
20190107 update:有同學指出,range() 不是內置函數而是個類對象。查看文檔(https://docs.python.org/3/library/functions.html#func-range):Rather than being a function, range is actually an immutable sequence type, as documented in Ranges and Sequence Types — list, tuple, range.如此看來,官方確實不完全把它定義為函數。只是,文檔的大類是內置函數,這會引起很多誤會......
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。”當它接收到“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 <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小時內與您取得聯系。