重塑数据集以正确大小
Posted
技术标签:
【中文标题】重塑数据集以正确大小【英文标题】:Reshaping dataset to correct size 【发布时间】:2020-12-11 10:02:03 【问题描述】:我正在尝试学习 tensorflow,并且正在尝试从 sklearn 导入手写数据集,但出现以下错误:
ValueError: Input 0 of layer conv2d is incompatible with the layer: : expected min_ndim=4, found ndim=3. Full shape received: [None, 1797, 64]
我的代码:
X,y = load_digits(return_X_y=True)
X = X/255.0
model = Sequential()
model.add(Conv2D(64,(3,3),input_shape=X.shape))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))
什么是正确的形状?
【问题讨论】:
【参考方案1】:Conv2D
层需要以下形状的输入:(num_examples, height, width, channels)
。您正在寻找Conv1D
层,因为您的输入形状(根据错误)的形状为:(num_examples, height, width)
。
【讨论】:
【参考方案2】:load_digits
返回一个展平的数组,因此您需要重新整形为 8x8 并解压。
import tensorflow as tf
from sklearn import datasets
from tensorflow.keras.layers import *
X,y = datasets.load_digits(return_X_y=True)
X = X/255.0
X = X.reshape(-1, 8, 8, 1)
model = tf.keras.Sequential()
model.add(Conv2D(64,(3,3),input_shape=X.shape[1:]))
model.add(Activation("relu"))
model.add(MaxPooling2D(pool_size=(2,2)))
model.build(input_shape=(8, 8, 1))
model(X)
<tf.Tensor: shape=(1797, 3, 3, 64), dtype=float32, numpy=
array([[[[0.00000000e+00, 0.00000000e+00, 1.79972278e-03, ...,
3.92661383e-03, 0.00000000e+00, 2.93043372e-03],
[3.34757613e-03, 0.00000000e+00, 0.00000000e+00, ...,
4.03874973e-03, 0.00000000e+00, 0.00000000e+00],
[5.52046159e-03, 1.12290974e-04, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]]]]
【讨论】:
以上是关于重塑数据集以正确大小的主要内容,如果未能解决你的问题,请参考以下文章