有些数据包含A,B,C。应根据A和B值预测C值。
数据被拆分和缩放。
没有卷积层的模型。
from keras.models import Sequential
from keras.layers import Dense, Conv1D
features_count = len(X_train.columns)
model = Sequential([
Dense(64, input_shape=(features_count,)),
Activation('relu'),
Dense(32),
Activation('softmax'),
Dense(1),
])
model.compile(optimizer="adam", loss='mse')
model.fit(X_train.values, y_train.values, epochs=10, batch_size=1, verbose=1)
model.evaluate(X_test, y_test, batch_size=1)
结果:1.0033315420150757
添加了Conv1D:
model = Sequential([
Conv1D(filters=256, kernel_size=5, padding='same', activation='relu', input_shape=(features_count,)),
Dense(64),
Activation('relu'),
Dense(32),
Activation('softmax'),
Dense(1),
])
结果:输入0与层conv1d_3不兼容:预期的ndim = 3,找到的ndim = 2
input_shape=(features_count,)
被替换为
input_shape=(features_count,1)
结果:检查输入时出错:预期conv1d_4_input具有3个维,但数组的形状为(3,2)
以这种方式添加卷积层有什么问题?如何在Keras模型中添加卷积层?
答案 0 :(得分:1)
Conv1D需要2D数据,因为它可以沿第二维对第一维应用卷积。因此,您的输入数据必须具有形状(批大小1、2)。但是,密集层需要1D,因此在Conv1D和密集之间需要添加一个Flatten层以将数据转换为1D。
from keras.models import Sequential
from keras.layers import Dense, Conv1D, Activation, Flatten
import numpy as np
X_train = np.array([[-1.0,-1.0], [1.0, -1.0], [1.0,1.0]])
y_train = np.array([[1.0], [-1.0], [0.0]])
X_test = np.array([[1.0,-1.0], [1.0, -1.0]])
y_test = np.array([[1.0], [-1.0]])
features_count = 2
model = Sequential([
Conv1D(filters=256, kernel_size=5, padding='same', activation='relu', input_shape=(1,features_count)),
Flatten(),
Dense(64),
Activation('relu'),
Dense(32),
Activation('softmax'),
Dense(1),
])
X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1])
X_test = X_test.reshape(X_test.shape[0], 1, X_test.shape[1])
model.compile(optimizer="adam", loss='mse')
model.fit(X_train, y_train, epochs=10, batch_size=1, verbose=1)
model.evaluate(X_test, y_test, batch_size=1)
结果:1.00140380859375
希望这对您有所帮助。