x = tf.reshape(x, shape=[-1, 28, 28, 1])的理解

Mnist中数据,输入n个样本,每个样本是784个列构成的向量。所以输入的是n*784的矩阵。但是输入到CNN中需要卷积,需要每个样本都是矩阵。

   x = tf.reshape(x, shape=[-1, 28, 28, 1])

newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
解释:如果等于-1的话,那么Numpy会根据剩下的维度计算出数组的另外一个shape属性值。

如何理解?举个栗子:

z = np.array([[1, 2, 3, 4],
	          [5, 6, 7, 8],
	          [9, 10, 11, 12],
	          [13, 14, 15, 16]])
Z = z.reshape([-1, 2, 2, 1])

在这里插入图片描述
最终输出结果:

[[[[ 1]
   [ 2]]
[[ 3]
   [ 4]]]
[[[ 5]
   [ 6]]
[[ 7]
   [ 8]]]
[[[ 9]
   [10]]
[[11]
   [12]]]
[[[13]
   [14]]
[[15]
   [16]]]]

这样做的目的是:将n个784个向量,变成n个28*28的
参考文章

  • 16
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
LeNet神经网络是一种经典的卷积神经网络,主要用于手写数字识别等任务。如果你要将LeNet神经网络应用于输入数据的reshape操作,可以按照以下步骤进行: 1. 导入必要的库和模块 ```python import tensorflow as tf from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten from tensorflow.keras import Input, Model ``` 2. 定义LeNet神经网络模型 ```python inputs = Input(shape=(28, 28, 1)) x = Conv2D(6, kernel_size=(5, 5), activation='relu', padding='valid')(inputs) x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x) x = Conv2D(16, kernel_size=(5, 5), activation='relu', padding='valid')(x) x = MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x) x = Flatten()(x) x = Dense(120, activation='relu')(x) x = Dense(84, activation='relu')(x) outputs = Dense(10, activation='softmax')(x) model = Model(inputs, outputs) ``` 3. 调用model.summary()函数查看模型结构,确认输入和输出的shape是否正确 ```python model.summary() ``` 4. 在训练过程中,可以使用tf.reshape()函数将输入数据reshape成需要的shape ```python train_images = tf.reshape(train_images, [-1, 28, 28, 1]) test_images = tf.reshape(test_images, [-1, 28, 28, 1]) ``` 其中,train_images和test_images是训练集和测试集的输入数据,shape为[样本数量, 图片高度, 图片宽度, 图像通道数],在LeNet神经网络中,输入数据的shape为[样本数量, 28, 28, 1]。因此,需要使用tf.reshape()函数将输入数据reshape成需要的shape
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值