[英]How do I reshape a 2d array into a 3d array for a neural network
我有一个数据集,我在其中应用train_test_split
。 X的形状:
print(X_train.shape)
print(X_test.shape)
Output:
(1945, 10000)
(487, 10000)
由于 X 是 numpy 数组,因此需要将其转换为图像(3D),以便稍后应用神经网络。 于是,我申请了:
X_train_3d = X_train.reshape(X_train.shape[0],100,100).astype('float32') # X_train.shape[1] = 10000 ;
# where 10000 = 100*100;
X_test_3d = X_test.reshape(X_test.shape[0],100,100).astype('float32')
print(X_train_3d.shape)
print(X_test_3d.shape)
所以,我得到了我的预期结果:
(1945, 100, 100)
(487, 100, 100)
我这样构建神经网络:
model = keras.Sequential([
keras.layers.Flatten(input_shape=(100, 100)), # width, height of image 100,100
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(39) # total number of target = 39
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(X_train_3d, y_train, epochs=10)
现在,我正在使用数据集并尝试应用类似的逻辑。 拆分后:
print(X_train.shape)
print(X_test.shape)
Output:
(1945, 1800)
(487, 1800)
现在,我不明白如何定义重塑,如:
X_train_3d = X_train.reshape(X_train.shape[0],?,?).astype('float32')
因为 1800 的平方根不是 integer。 如何将其转换为 3d,以便我能够像以前一样构建神经网络。
进行此运行的唯一方法是没有 CNN。 然后,你就不必重塑。 推测性重塑只会产生随机像素。
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
X = np.random.randint(0, 256, (1945, 1800)) # fake data
y = np.random.randint(0, 38, 1945)
model = Sequential([
Dense(128, activation='relu', input_shape=(1800,)),
Dense(39)])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True), metrics=['accuracy'])
hist = model.fit(X, y, epochs=10)
理想情况下,你会修复你的数据,然后你可以运行一个 CNN,这是最好的 model。 CNN 保持像素之间的 2D 关系,所以它会很棒,但是如果你不知道正确的形状,你的像素之间就没有关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.