【发布时间】:2021-07-07 13:02:12
【问题描述】:
我一直在为多类分类问题编写 keras 代码。我会暴露我的问题。
我在单个 csv 文件中有一个数据集,其中包含以下形式的行
1.45 -10.09 1.02 1 0 0 0
前 3 列代表来自加速度计的 X、Y、Z 加速度。最后 4 列代表类标签。我有 4 节课
[1 0 0 0][0 1 0 0][0 0 1 0][0 0 0 1]
每个向量都是一个类标签,对应于单个手势(握手、旋转手、举手、非先前手势)
我想要的是有一个 LSTM 回顾前面的 N 个步骤(比如说 20 个),将 N 个 3D 向量 [X,Y,Z] 作为输入并在每个序列的末尾(由这 20 个 3D向量)吐出该序列属于我拥有的四个类别中的任何一个的概率。
问题1:根据我的理解,模型应该是“多对一”,对吗? 问题2:如何使用 keras API for python 实现这样的网络?
我是 keras 编码的新手,到目前为止我所做的是这段代码(我在 colab 工作):
# load dataset
from google.colab import files
uploaded = files.upload()
dataframe = pd.read_csv(io.BytesIO(uploaded['data_new.csv']), header=None)
dataset = dataframe.values
X = dataset[:,0:3].astype(float)
Y = dataset[:,3:].astype(int)
print(X.shape)
print(Y.shape)
model = Sequential()
...
...
打印语句的输出是:
(48886, 3)
(48886, 4)
我还会在这里发布数据集的一些行:
1.45 -10.09 1.02 1 0 0 0
1.06 -10.13 1.06 1 0 0 0
1.22 -10.09 1.02 1 0 0 0
1.38 -10.05 1.06 1 0 0 0
1.03 -10.25 1.18 1 0 0 0
0.04 -10.17 1.11 1 0 0 0
0.55 -9.57 1.30 1 0 0 0
1.18 -9.38 1.26 1 0 0 0
2.36 -9.22 0.35 1 0 0 0
...
...
我必须以某种方式重塑输入吗?我真的卡住了,请帮帮我
编辑 我正在使用真实数据集尝试以下代码
dataframe = pd.read_csv(io.BytesIO(uploaded['data_new.csv']), header=None)
#dataframe = pandas.read_csv("iris.data", header=None)
dataset = dataframe.values
X = dataset[:,0:3].astype(float)
Y = dataset[:,3:].astype(int)
X_train = tf.expand_dims(X, axis=-1)
BATCH_SIZE = 20
EPOCHS = 2 # Used less epochs for testing purposes
model = tf.keras.Sequential()
model.add(tf.keras.layers.LSTM(100, input_shape=(X_train.shape[1], X_train.shape[2])))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(100, activation="relu"))
model.add(tf.keras.layers.Dense(4, activation="softmax"))
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
model.summary()
print("Fit the model on training data")
history = model.fit(X_train, Y, epochs=EPOCHS, batch_size=BATCH_SIZE, verbose=0)
sample_input = np.random.randint(0,100, size=(20, 3))
print(sample_input)
sample_input_reshaped = tf.expand_dims(sample_input, axis=1)
print(sample_input_reshaped.shape)
predictions = model.predict(sample_input_reshaped)
print('Model predictions', predictions)
我收到了这个错误
ValueError: Input 0 is incompatible with layer sequential_11: expected shape=(None, None, 1), found shape=(None, 1, 3)
【问题讨论】:
-
是的!确切地说:)如何编码?
标签: python tensorflow keras lstm tf.keras