2017-06-17 66 views
2

我想運行一個簡單的自動編碼器,所有的訓練輸入是相同的。訓練數據特徵等於3,隱藏層有3個節點。我使用那個輸入來訓練自動編碼器,然後我試着再次預測它(編碼/解碼)(所以如果自動編碼器按原樣傳遞所有東西而不做任何改變,它應該可以工作)Keras autoencoder簡單的例子有一個奇怪的輸出

無論如何,情況並非如此,爲了理解原因,有點勉強。我不確定在我的代碼中,或者我對autoencdoer實現的理解中是否有問題。這裏是供參考的代碼。

P.S.我使用了epoches數量,訓練集中的示例數量,批量大小,訓練數據值在0-1之間,並記錄了損失值,但這也沒有幫助。

`

from keras.layers import Input, Dense 
from keras.models import Model 
import numpy as np 
# this is the size of our encoded representations 
encoding_dim = 3 

x_train=np.array([[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]) 
in= Input(shape=(3,)) 
encoded = Dense(encoding_dim, activation='relu')(in) 
decoded = Dense(3, activation='sigmoid')(encoded) 

# this model maps an input to its reconstruction 
autoencoder = Model(in, decoded) 
autoencoder.compile(optimizer='adadelta', loss='mse') 

autoencoder.fit(x_train, x_train, 
       epochs=100, 
       batch_size=4) 
autoencoder.predict(x_train) 

`

我得到的輸出應該是一樣的輸入(或至少接近),但我得到這個代替)

`Out[180]: 
array([[ 0.80265796, 0.89038897, 0.9100889 ], 
     [ 0.80265796, 0.89038897, 0.9100889 ], 
     [ 0.80265796, 0.89038897, 0.9100889 ], 
     ..., 
     [ 0.80265796, 0.89038897, 0.9100889 ], 
     [ 0.80265796, 0.89038897, 0.9100889 ], 
     [ 0.80265796, 0.89038897, 0.9100889 ]], dtype=float32)` 

任何幫助不勝感激,最有可能的是我明白了一些錯誤,所以希望這個問題不難回答。

回答

1

錯誤在這裏decoded = Dense(3, activation='sigmoid')(encoded)

你不應該使用sigmoid激活,因爲這將限制範圍內,輸出(0,1),更換sigmoidlinear或只是將其刪除,並可以添加多個時期,如訓練1000個時代。在這種背景下,我得到你所需要的

[[ 0.98220336 1.98066235 2.98398876] 
[ 0.98220336 1.98066235 2.98398876] 
[ 0.98220336 1.98066235 2.98398876] 
[ 0.98220336 1.98066235 2.98398876] 
[ 0.98220336 1.98066235 2.98398876] 
[ 0.98220336 1.98066235 2.98398876] 
[ 0.98220336 1.98066235 2.98398876] 
[ 0.98220336 1.98066235 2.98398876] 
[ 0.98220336 1.98066235 2.98398876]] 

此外,你應該使用其他名稱代替輸入in,因爲它是在Python :-)一個keyword

1

適用以下@danche建議之後是更新的代碼和結果,我增加了epocs = 10000

from keras.layers import Input, Dense 
from keras.models import Model 
import numpy as np 
# this is the size of our encoded representations 
encoding_dim = 3 

x_train=np.array([[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]) 
input = Input(shape=(3,)) 
encoded = Dense(encoding_dim, activation='relu')(input) 
decoded = Dense(3, activation='linear')(encoded) 

# this model maps an input to its reconstruction 
autoencoder = Model(input, decoded) 
autoencoder.compile(optimizer='adadelta', loss='mse') 

autoencoder.fit(x_train, x_train,epochs=10000,batch_size=4) 
print(autoencoder.predict(x_train)) 



Epoch 10000/10000 
8/8 [==============================] - 0s - loss: 2.4463e-04  
[[ 0.99124289 1.98534203 2.97887278] 
[ 0.99124289 1.98534203 2.97887278] 
[ 0.99124289 1.98534203 2.97887278] 
[ 0.99124289 1.98534203 2.97887278] 
[ 0.99124289 1.98534203 2.97887278] 
[ 0.99124289 1.98534203 2.97887278] 
[ 0.99124289 1.98534203 2.97887278] 
[ 0.99124289 1.98534203 2.97887278]] 
後得到的結果