【Tensorflow】技巧(1):tf.shape和get_shape()的区别

本文通过实例对比了TensorFlow中tf.shape和get_shape()的功能。tf.shape返回的是一个tensor,需要通过sess.run()获取具体值;而get_shape()直接返回一个tuple,无法放入sess.run()中运行。

tensorflow中的tf.shape和get_shape()都可以用来获取尺寸,那两者的区别是什么呢?先看下面一段代码:

<span style="color:#6633ff">import tensorflow as tf
 
a = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]])
 
with tf.Session() as sess:
    a_shape = tf.shape(a)
    a_getshape = a.get_shape()
    print(a_shape)
    print(a_getshape)</span>
输出:

可以看到,tf.shape(a)的输出是一个tensor,而,a.get_shape()的输出却是一个元组tuple。

二、

而要获得tensor的值,需要将其放在sess.run()中,再看:

<span style="color:#6633ff">print(sess.run(a_shape))
    print(sess.run(a_shape[0]))
    print(sess.run(a_shape[1]))</span>
输出:

相反,tuple的值不能放在sess.run()中,否则会报错。

<span style="color:#6633ff">print(a_getshape[0])
    print(a_getshape[1])</span>
输出:


--------------------- 
作者:heiheiya 
来源:优快云 
原文:https://blog.youkuaiyun.com/heiheiya/article/details/80729133 
版权声明:本文为博主原创文章,转载请附上博文链接!

``` !mkdir -p ~/.keras/datasets !cp work/mnist.npz ~/.keras/datasets/ import warnings warnings.filterwarnings("ignore") from keras.datasets import mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() print(f"训练数据形状: {train_images.shape}") print(f"训练标签长度: {len(train_labels)}") print(f"测试数据形状: {test_images.shape}") print(f"测试标签长度: {len(test_labels)}") from keras import models from keras import layers # 构建神经网络模型 network = models.Sequential() network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,))) # 隐藏层:512个神经元,激活函数为ReLU network.add(layers.Dense(10, activation='softmax')) # 输出层:10个分类,激活函数为Softmax # 编译模型 network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # 数据预处理 train_images = train_images.reshape((60000, 28 * 28)) # 将图像展平成一维向量 train_images = train_images.astype('float32') / 255 # 归一化到[0,1] test_images = test_images.reshape((10000, 28 * 28)) test_images = test_images.astype('float32') / 255 # 标签编码 from keras.utils import to_categorical train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) # 训练模型 network.fit(train_images, train_labels, epochs=5, batch_size=128) # 测试模型性能 test_loss, test_acc = network.evaluate(test_images, test_labels) print('Test accuracy:', test_acc)```W0402 08:09:22.415642 140410418362176 deprecation.py:323] From /opt/conda/lib/python3.6/site-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where W0402 08:09:22.484165 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:986: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead. W0402 08:09:22.495126 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:973: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead. W0402 08:09:22.537523 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:2741: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead. W0402 08:09:22.546429 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:174: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead. W0402 08:09:22.548026 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:181: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead. W0402 08:09:22.566734 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:190: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead. W0402 08:09:22.567799 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:199: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead. W0402 08:09:22.613820 140410418362176 module_wrapper.py:139] From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:206: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead.
最新发布
04-03
从您的代码来看,您正在尝试通过Keras框架完成手写数字识别任务,并加载了MNIST数据集作为输入数据源。以下是关于上述代码的详细解释: ### 主要功能解读 1. **创建目录并复制文件** ```bash !mkdir -p ~/.keras/datasets !cp work/mnist.npz ~/.keras/datasets/ ``` 这两行命令用于手动将`mnist.npz`文件存储到`.keras/datasets/`路径下,以便后续使用Keras自动加载该数据。 2. **警告过滤** ```python import warnings warnings.filterwarnings("ignore") ``` 此部分忽略运行过程中可能出现的所有警告信息,目的是减少干扰日志输出。 3. **加载MNIST数据集** ```python from keras.datasets import mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() ``` 使用Keras内置的数据集模块加载MNIST数据集,分为训练集测试集两个部分: - `train_images`: 包含6万张28x28的手写数字图片; - `train_labels`: 对应于每张图片的实际类别(0~9)。 4. **构建神经网络模型** 神经网络由以下结构组成: - 输入层:接收展平后的图像数据,大小为`(28*28,)`即784维度; - 隐藏层:一层包含512个神经元的全连接层,激活函数选择`ReLU`; - 输出层:一层包含10个神经元的全连接层,对应十个分类结果(0~9),激活函数选用`Softmax`. 模型编译选项包括优化器、损失函数以及评估指标的选择: - 优化器选择了RMSProp算法,这是一种自适应学习率的优化策略; - 损失函数采用了交叉熵(`categorical_crossentropy`) 来衡量预测值与真实值之间的差距; - 性能评价采用准确率(`accuracy`)作为标准。 5. **数据预处理** 图像被转换为浮点数类型的向量形式并且归一化至区间[0,1]: ```python train_images = train_images.reshape((60000, 28 * 28)).astype('float32') / 255 ``` 6. **标签编码** 标签经过One-Hot编码转为适合分类的形式: ```python from keras.utils import to_categorical train_labels = to_categorical(train_labels) ``` 7. **模型训练与测试** 最终利用训练好的模型对测试样本进行验证,打印出相应的准确度得分。 --- #### 关键注意事项及解决办法 - 抑制警告的问题是由TensorFlow版本升级引发的历史兼容性提示造成的;如果您想消除这些冗余消息,可以考虑更新依赖库或直接切换到较新的API规范上工作。 例如对于类似`tf.assign_add`, 可改用推荐的新版等价替代项:`tf.compat.v1.assign_add`. 此外,在实际应用当中还需注意硬件资源是否足够支撑大规模深度学习实验运算需求等问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值