2017-04-22 142 views
2

所以我試圖學習與凱拉斯的ANN,因爲我聽說Theano或TensorFlow更簡單。我有許多問題是第一個與輸入層有關的問題。Keras和輸入層

到目前爲止,我有這行代碼作爲輸入:

model.add(Dense(3 ,input_shape=(2,), batch_size=50 ,activation='relu')) 

現在我想添加到模型中的數據如下形狀:

Index(['stock_price', 'stock_volume', 'sentiment'], dtype='object') 
[[ 3.01440000e+02 7.87830000e+04 0.00000000e+00] 
[ 3.01440000e+02 7.87830000e+04 0.00000000e+00] 
[ 3.01440000e+02 7.87830000e+04 1.42857143e-01] 
[ 3.01440000e+02 7.87830000e+04 5.88235294e-02] 
[ 3.01440000e+02 7.87830000e+04 0.00000000e+00] 
[ 3.01440000e+02 7.87830000e+04 0.00000000e+00] 
[ 3.01440000e+02 7.87830000e+04 0.00000000e+00] 
[ 3.01440000e+02 7.87830000e+04 0.00000000e+00] 
[ 3.01440000e+02 7.87830000e+04 0.00000000e+00] 
[ 3.01440000e+02 7.87830000e+04 5.26315789e-02]] 

我要打一個模型,看看我能否找到股票價格和tweet情緒之間的相關性,我只是把數量放在那裏,因爲最終,我想看看它是否也能找到一個模式。

所以,我的第二個問題是運行我的輸入層與幾個不同的參數後,我得到這個問題,我不能解釋。所以,當我跑這條線:

model.add(Dense(3 ,input_shape=(2,), batch_size=50 ,activation='relu')) 

與以下行我得到這個輸出錯誤:

ValueError: Error when checking model input: expected dense_1_input to have shape (50, 2) but got array with shape (50, 3) 

但是,當我輸入形狀改變成請求「3」我得到這個錯誤:

ValueError: Error when checking model target: expected dense_2 to have shape (50, 1) but got array with shape (50, 302) 

爲什麼在錯誤信息中2變成'302'?

我可能忽略了一些真正的基本問題,因爲這是我嘗試實現的第一個神經網絡,因爲我以前只使用Weka的應用程序。

反正這裏是我的全部代碼的副本:

from keras.models import Sequential, Model 
from keras.layers import Dense, Activation, Input 
from keras.optimizers import SGD 
from keras.utils import np_utils 
import pymysql as mysql 
import pandas as pd 
import config 

import numpy 
import pprint 

model = Sequential() 
try: 
    sql = "SELECT stock_price, stock_volume, sentiment FROM tweets LIMIT 50" 
    con = mysql.connect(config.dbhost, config.dbuser, config.dbpassword, config.dbname, charset='utf8mb4', autocommit=True) 
    results = pd.read_sql(sql=sql, con=con, columns=['stock_price', 'stock_volume', 'sentiment']) 
finally: 
    con.close() 

npResults = results.as_matrix() 
cols = np_utils.to_categorical(results['stock_price'].values) 
data = results.values 

print(cols) 
# inputs: 
# 1st = stock price 
# 2nd = tweet sentiment 
# 3rd = volume 
model.add(Dense(3 ,input_shape=(3,), batch_size=50 ,activation='relu')) 
model.add(Dense(20, activation='linear')) 
sgd = SGD(lr=0.3, decay=0.01, momentum=0.2) 

model.compile(loss='sparse_categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) 

model.summary() 
model.fit(x=data, y=cols, epochs=100, batch_size=100, verbose=2) 

編輯:

這裏是所有的輸出我得到的FOM控制檯:

C:\Users\Def\Anaconda3\python.exe C:/Users/Def/Dropbox/Dissertation/ann.py 
Using Theano backend. 
C:\Users\Def\Dropbox\Dissertation 
[[ 0. 0. 0. ..., 0. 0. 1.] 
[ 0. 0. 0. ..., 0. 0. 1.] 
[ 0. 0. 0. ..., 0. 0. 1.] 
..., 
[ 0. 0. 0. ..., 0. 0. 1.] 
[ 0. 0. 0. ..., 0. 0. 1.] 
[ 0. 0. 0. ..., 0. 0. 1.]] 
_________________________________________________________________ 
Layer (type)     Output Shape    Param # 
================================================================= 
dense_1 (Dense)    (50, 3)     12   
_________________________________________________________________ 
dense_2 (Dense)    (50, 20)     80   
================================================================= 
Traceback (most recent call last): 
    File "C:/Users/Def/Dropbox/Dissertation/ann.py", line 38, in <module> 
    model.fit(x=data, y=cols, epochs=100, batch_size=100, verbose=2) 
    File "C:\Users\Def\Anaconda3\lib\site-packages\keras\models.py", line 845, in fit 
    initial_epoch=initial_epoch) 
    File "C:\Users\Def\Anaconda3\lib\site-packages\keras\engine\training.py", line 1405, in fit 
    batch_size=batch_size) 
    File "C:\Users\Def\Anaconda3\lib\site-packages\keras\engine\training.py", line 1299, in _standardize_user_data 
    exception_prefix='model target') 
    File "C:\Users\Def\Anaconda3\lib\site-packages\keras\engine\training.py", line 133, in _standardize_input_data 
    str(array.shape)) 
ValueError: Error when checking model target: expected dense_2 to have shape (50, 20) but got array with shape (50, 302) 
Total params: 92.0 
Trainable params: 92 
Non-trainable params: 0.0 
_________________________________________________________________ 

Process finished with exit code 1 
+0

首先,您應該定義這是迴歸還是分類問題,以及要預測的目標值及其維數。 –

回答

0

我認爲你正在使用錯誤的度量標準:sparse_categorical_crossentropy 是否有這樣的理由比較正常:categorical_crossentropy

當使用categorical_crossentropy時,應該使用單熱編碼方式(例如使用cols = np_utils.to_categorical(results['stock_price'].values))編碼目標。

另一方面,sparse_categorical_crossentropy使用基於整數的標籤。

因此,無論使用:

cols = np_utils.to_categorical(results['stock_price'].values) 

model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) 

和(NUM-類別)神經元

或使用一個輸出層:

cols = results['stock_price'].values.astype(np.int32) 

model.compile(loss='sparse_categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) 

和單神經元輸出層。

+0

輸出層只是一組正常的神經元?我不需要像輸入那樣的特殊圖層? IE我不需要設置輸出尺寸或輸出形狀?我問的原因是我仍然得到奇怪的「ValueError:錯誤時檢查模型目標:期望dense_2有形狀(50,20),但有陣列形狀(50,302)」錯誤 – Definity

+0

你不需要一個輸入層您已經指定了第一個密集圖層的input_shape。輸出圖層的#維度應該是類別的數量。你有幾個類別? – Pedia

+0

我有3個類別,我想要作爲輸出 – Definity