我正在编写一个神经网络,以梅尔频率系数作为输入,然后运行模型。我的数据集包含 100 个样本 - 每个样本都是与系数对应的 12 个值的数组。将这些数据拆分为训练集和测试集后,我创建了与数组对应的 X 输入和与标签对应的 y 输入。
Data array containing the coefficients
这是我的数据的一个小样本,其中包含 X_train 数组中的 5 个元素:
['[107.59366 -14.153783 24.799461 -8.244417 20.95272\n -4.375943 12.77285 -0.92922235 3.9418116 7.3581047\n -0.30066165 5.4417 65]' '[96.49664 2.0689797 21.557552 -32.827045 7.348135 -23.513977\n 7.9406714 -16.218931 10.594619 -21.4381 0.594381 0.590303030303030303030444444444444444444-1104-1104-1104-1104-1104-1104-1104-1104-1104-1104-1104-1104-1104-1104-1104 -55695] '[105.98041 -2.0483367 12.276348 -27.334534 6.8239 -23.019623\n 7.5176797 -21.884727 11.349695 '[ 7.73094559e+01 1.91073620e+00 6.72225571e+00 -2.74525508e-02\n 6.60858107e+00 5.99264860e-01 1.96265772e-01 -3.94772577e+0 0\n 7.46383286e+00 5.42239428e+00 1.21432066e -01 2.44894314e+00]']
当我创建神经网络时,我想使用 12 个系数作为网络的输入。为此,我需要使用包含这些数组的 X_train 数据集的每一行作为输入。但是,当我尝试将数组索引视为输入时,在尝试拟合模型时会出现形状错误。我的模型如下:
def build_model_graph():
model = Sequential()
model.add(Input(shape=(12,)))
model.add(Dense(12))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('relu'))
model.add(Dense(num_labels))
model.add(Activation('softmax'))
# Compile the model
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')
return model
在这里,我想使用 X_train 数组的每一行作为与形状(12,)相对应的输入。当我使用这样的东西时:
num_epochs = 50
num_batch_size = 32
model.fit(x_train, y_train, batch_size=num_batch_size, epochs=num_epochs,
validation_data=(x_test, y_test), verbose=1)
我收到一个对我来说有意义的形状错误。 仅供引用,错误如下:
ValueError: Exception encountered when calling layer "sequential_20" (type Sequential).
Input 0 of layer "dense_54" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)
但我不太确定如何提取 X_train 每个索引处存在的 12 个系数的数组,然后在模型输入中使用它。索引 x_train 和 y_train 也不起作用。如果有人能指出我相关的方向,那将非常有帮助。谢谢!
编辑:我的数据框代码如下:
clapdf = pd.read_csv("clapsdf.csv")
clapdf.drop('Unnamed: 0', inplace=True, axis=1)
clapdf.head()
nonclapdf = pd.read_csv("nonclapsdf.csv")
nonclapdf.drop('Unnamed: 0', inplace=True, axis=1)
sound_df = clapdf.append(nonclapdf)
sound_df.head()
d=sound_data.tolist()
df=pd.DataFrame(data=d)
data = df[0].to_numpy()
print("Before-->", data.shape)
dat = np.array([np.array(d) for d in data])
print('After-->', dat.shape)
这里,形状保持不变,因为 80 个样本中每个样本的值不是以逗号分隔的格式,而是以系列的形式。
最佳答案
如果您的数据如下所示:
samples = 2
features = 12
x_train = tf.random.normal((samples, 1, features))
tf.Tensor(
[[[-2.5988803 -0.629626 -0.8306641 -0.78226614 0.88989156
-0.3851106 -0.66053045 1.0571191 -0.59061646 -1.1602987
0.69124466 -0.04354193]]
[[-0.86917496 2.2923143 -0.05498986 -0.09578358 0.85037625
-0.54679644 -1.2213608 -1.3766612 0.35416105 -0.57801914
-0.3699728 0.7884727 ]]], shape=(2, 1, 12), dtype=float32)
您必须将其 reshape 为 (2, 12)
才能使您的模型适合输入形状 (batch_size, 12)
:
import tensorflow as tf
def build_model_graph():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Input(shape=(12,)))
model.add(tf.keras.layers.Dense(12))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Dense(10))
model.add(tf.keras.layers.Activation('relu'))
model.add(tf.keras.layers.Dense(2))
model.add(tf.keras.layers.Activation('softmax'))
# Compile the model
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')
return model
model = build_model_graph()
samples = 2
features = 12
x_train = tf.random.normal((samples, 1, features))
x_train = tf.reshape(x_train, (samples, features))
y = tf.random.uniform((samples, 1), maxval=2, dtype=tf.int32)
y_train = tf.keras.utils.to_categorical(y, 2)
model.fit(x_train, y_train, batch_size=1, epochs=2)
此外,如果您打算使用categorical_crossentropy
,您通常需要将标签转换为 one-hot 编码向量。
y_train
看起来像这样:
[[0. 1.]
[1. 0.]]
更新 1: 如果您的数据来自数据框,请尝试如下操作:
import numpy as np
import pandas as pd
d = {'features': [[0.18525402, 0.92130125, 0.2296906, 0.75818471, 0.69813222, 0.47147329,
0.03560711, 0.06583931, 0.90921289, 0.76002148, 0.50413995, 0.36099004],
[0.18525402, 0.92130125, 0.2296906, 0.75818471, 0.69813222, 0.47147329,
0.03560711, 0.06583931, 0.90921289, 0.76002148, 0.50413995, 0.36099004]]}
df = pd.DataFrame(data=d)
data = df['features'].to_numpy()
print('Before -->', data.shape)
data = np.array([np.array(d) for d in data])
print('After -->', data.shape)
Before --> (2,)
After --> (2, 12)
关于python - 使用数组输入神经网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70362733/