python - 为什么当我使用 model.predict 时,我在 keras 中得到全 1?

标签 python keras

我正在尝试使用 keras 包中的 LSTM。我将所有训练和测试数据标准化为 0 到 1 之间的范围。我将数组 reshape 为 3D 数组。但是当我运行查看结果时,我得到一个 1 数组,而不是 1 到 0 之间的缩放值。

这是我的代码:

Input = pd.read_csv('Input.csv')

for i in range(0, len(Input['Gold Price'])):
   Input['Gold Price'][i] = float(Input['Gold Price'][i].replace(',',''))
   Input['DJIA'][i] = float(Input['DJIA'][i].replace(',',''))

x_train = Input[['DJIA', 'Silver Price', 'Copper Price', 'US Dollar Index', 
'VIX']]
y_train = Input[['Gold Price']]

scaler = MinMaxScaler(feature_range=(0, 0.95))
scaler_x = scaler.fit(x_train)
scaler_y = scaler.fit(y_train)
x_scaled = scaler_x.transform(x_train)
y_scaled = scaler_y.transform(y_train)

x_scaled = np.reshape(x_scaled, (x_scaled.shape[0], 1, x_scaled.shape[1]))

model = Sequential()

model.add(LSTM(5, activation='relu', input_dim=5))
model.add(Dense(units=1, activation='softmax'))

model.compile(loss='mae',
          optimizer='adam',
          metrics=['accuracy'])

model.fit(x_scaled, y_scaled, epochs=5, batch_size=32)

Test = pd.read_csv('Test Prices Daily.csv')

for i in range(0, len(Test['DJIA'])):
    Test['DJIA'][i] = float(Test['DJIA'][i].replace(',',''))

x_test = Test[['DJIA', 'Silver Price', 'Copper Price', 'US Dollar Index', 
'VIX']]

scaler_x = scaler.fit(x_test)
x_scaled_test = scaler_x.transform(x_test)

x_scaled_test = np.reshape(x_scaled_test, (x_scaled_test.shape[0], 1, 
x_scaled_test.shape[1]))
prediction = model.predict(x_scaled_test, batch_size=128)

最佳答案

model.add(Dense(units=1, activation='softmax'))

是有问题的行。激活应该是 sigmoid。

原因是softmax由下式给出

softmax(x)_i = e^x_i/sum_i e^x_i

对输出向量进行归一化,使各分量之和为 1(即将其映射到单纯形上)。如果有 1 个分量输出,则它必须始终为 1。

我也有点惊讶地看到这一点:

loss='mae'

并且认为二元交叉熵是一个更好的选择,因为你的响应在 0 和 1 之间。我想这取决于将输出变量解释为函数近似或概率,这是我不知道的。

关于python - 为什么当我使用 model.predict 时,我在 keras 中得到全 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51445689/

相关文章:

python - 用于序列标记的 keras BLSTM

python - 神经网络回归预测所有测试样本的相同值

python - grid zorder 好像没有生效(matplotlib)

Python 引号异常中转义引号的异常

python - 从文本文件中获取整数并用python写入excel

python - Django.core.exceptions.ImproperlyConfigured : Error running functional_tests. py

tensorflow - Keras,models.add() 缺少 1 个必需的位置参数 : 'layer'

Python:从标准输入读取gzip

python - 自定义损失函数实现

tensorflow - 在序列模型中使用填充时,Keras 验证准确性是否有效/可靠?