keras报错: ValueError: Shapes (None, 1) and (None, 2) are incompatible

keras报错:ValueError:Shapes (None, 1)and (None,2)are incompatible

任务背景

使用 MLP 做时间序列的二分类问题,通过历史股价判断 未来天数 是涨还是跌。

错误提示

ValueError: Shapes (None, 1) and (None, 2) are incompatible

问题解决

将标签的数值 0,1 转化成 类别的 0,1

from tensorflow.keras.utils import to_categorical
y = to_categorical(dataset['binary_target'].values)

具体程序

import matplotlib.pylab as plt
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.layers import *
from tensorflow.keras.models import *
# read_data 
data = pd.read_csv('./AAPL.csv')
close_price = data.loc[:, 'Adj Close'].tolist()
close_price_diffs = data.loc[:, 'Adj Close'].pct_change()
# generate the dataset 
target = close_price_diffs.apply(lambda x: 1 if x > 0 else 0)
dataset = pd.DataFrame({'close_price': close_price, 'binary_target':target })
# scale the dataset 
scaler = MinMaxScaler()
X_sc = scaler.fit_transform(dataset['close_price'].values.reshape(-1,1))
# y = dataset['binary_target'].values  ## 会报错,因为不是类别
y = to_categorical(dataset['binary_target'].values)  ## 正确写法!!
X_train, X_test, y_train, y_test = train_test_split(X_sc, y, test_size=0.15, random_state=0)

# define the model 
model = Sequential()
model.add(Dense(64, input_dim=X_train.shape[1]))
model.add(BatchNormalization())
model.add(LeakyReLU())
model.add(Dense(2))
model.add(Activation('softmax'))

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=5, min_lr=0.000001, verbose=1)
model.compile(optimizer='rmsprop', 
              loss='categorical_crossentropy',
              metrics=['accuracy'])
# fit the  model 
history = model.fit(X_train, y_train, 
          epochs = 50, 
          batch_size = 128, 
          verbose=1, 
          validation_data=(X_test, y_test),
          shuffle=True,
          callbacks=[reduce_lr])
          
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
非常抱歉,我之前的回答有误导。根据您的数据形状,模型的输入应该是 `(2, 5, 1)` 而不是 `(2, 6, 1)`。请将代码中的 `X_train.reshape(2, 5, 1)` 和 `y_train.reshape(2, 5, 1)` 改为 `X_train.reshape(2, 3, 1)` 和 `y_train.reshape(2, 3, 1)`。 以下是修改后的代码: ```python import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import GRU, Dense from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score import matplotlib.pyplot as plt # 输入数据 data = np.array([[1, 4, 6, 7, 9, 13], [4, 7, 5, 8, 19, 26], [1, 5, 7, 245, 145, 11]]) # 将数据分为输入和输出序列 X_train = data[:2, :-1] y_train = data[:2, 1:] X_val = data[2:3, :-1] y_val = data[2:3, 1:] # 构建GRU模型 model = Sequential() model.add(GRU(32, input_shape=(3, 1))) # 输入序列长度为3 model.add(Dense(3)) # 编译并训练模型 model.compile(optimizer='adam', loss='mse') model.fit(X_train.reshape(2, 3, 1), y_train.reshape(2, 3, 1), epochs=100) # 预测验证集数据 predictions = model.predict(X_val.reshape(1, 3, 1)) # 计算指标 mse = mean_squared_error(y_val.reshape(-1), predictions.reshape(-1)) mae = mean_absolute_error(y_val.reshape(-1), predictions.reshape(-1)) rmse = np.sqrt(mse) r2 = r2_score(y_val.reshape(-1), predictions.reshape(-1)) # 绘制验证集和预测值 plt.plot(np.arange(2, 8), y_val.reshape(-1), label='Validation') plt.plot(np.arange(3, 9), predictions.reshape(-1), label='Prediction') plt.xlabel('Time Step') plt.ylabel('Value') plt.legend() plt.show() print("MSE:", mse) print("MAE:", mae) print("RMSE:", rmse) print("R2:", r2) ``` 再次非常抱歉给您带来的困扰,希望这次能够顺利运行。如果还有其他问题,请随时提问。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值