开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 471

xiongying/Paddle

forked from PaddlePaddle/Paddle
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
develop
分支 (296)
标签 (62)
develop
fix_tensor_type
release/2.3
dingjiaweiww-patch-1
revert-41065-revert-40993-mv_ele_floordiv_pow
revert-41068-revert-40790-phi_new
prv-onednn-2.5
fix_rnn_docs
add_some_yaml_config
move_slice_to_pten
enable_eager_model_test
move_yolo_box_to_phi
move_sgd_to_phi
move_embedding_to_phi
release/2.2
incubate/infrt
release/1.8
ascendrelease
release/2.1
release/2.0
v2.2.2
v2.2.1
v2.2.0
v2.2.0-bak0
v2.2.0-rc0
v2.1.3
v2.1.2
v2.1.1
v2.1.0
v2.1.0-rc0
v2.0.2
v2.0.1
v2.0.0
v2.0.0-rc1
v2.0.0-rc0
v1.8.5
v2.0.0-beta0
v1.8.4
v1.8.3
v1.8.2
develop
分支 (296)
标签 (62)
develop
fix_tensor_type
release/2.3
dingjiaweiww-patch-1
revert-41065-revert-40993-mv_ele_floordiv_pow
revert-41068-revert-40790-phi_new
prv-onednn-2.5
fix_rnn_docs
add_some_yaml_config
move_slice_to_pten
enable_eager_model_test
move_yolo_box_to_phi
move_sgd_to_phi
move_embedding_to_phi
release/2.2
incubate/infrt
release/1.8
ascendrelease
release/2.1
release/2.0
v2.2.2
v2.2.1
v2.2.0
v2.2.0-bak0
v2.2.0-rc0
v2.1.3
v2.1.2
v2.1.1
v2.1.0
v2.1.0-rc0
v2.0.2
v2.0.1
v2.0.0
v2.0.0-rc1
v2.0.0-rc0
v1.8.5
v2.0.0-beta0
v1.8.4
v1.8.3
v1.8.2
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
develop
分支 (296)
标签 (62)
develop
fix_tensor_type
release/2.3
dingjiaweiww-patch-1
revert-41065-revert-40993-mv_ele_floordiv_pow
revert-41068-revert-40790-phi_new
prv-onednn-2.5
fix_rnn_docs
add_some_yaml_config
move_slice_to_pten
enable_eager_model_test
move_yolo_box_to_phi
move_sgd_to_phi
move_embedding_to_phi
release/2.2
incubate/infrt
release/1.8
ascendrelease
release/2.1
release/2.0
v2.2.2
v2.2.1
v2.2.0
v2.2.0-bak0
v2.2.0-rc0
v2.1.3
v2.1.2
v2.1.1
v2.1.0
v2.1.0-rc0
v2.0.2
v2.0.1
v2.0.0
v2.0.0-rc1
v2.0.0-rc0
v1.8.5
v2.0.0-beta0
v1.8.4
v1.8.3
v1.8.2
input.py 11.97 KB
一键复制 编辑 原始数据 按行查看 历史
0x45f 提交于 2022年03月17日 10:27 +08:00 . Refine io for test_mnist.py (#40496)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import six
import paddle
from paddle.fluid import core, Variable
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.data_feeder import check_type
from paddle.fluid.framework import convert_np_dtype_to_dtype_
from paddle.fluid.framework import static_only
__all__ = []
@static_only
def data(name, shape, dtype=None, lod_level=0):
"""
**Data Layer**
This function creates a variable on the global block. The global variable
can be accessed by all the following operators in the graph. The variable
is a placeholder that could be fed with input, such as Executor can feed
input into the variable. When `dtype` is None, the dtype
will get from the global dtype by `paddle.get_default_dtype()`.
Args:
name (str): The name/alias of the variable, see :ref:`api_guide_Name`
for more details.
shape (list|tuple): List|Tuple of integers declaring the shape. You can
set "None" or -1 at a dimension to indicate the dimension can be of any
size. For example, it is useful to set changeable batch size as "None" or -1.
dtype (np.dtype|str, optional): The type of the data. Supported
dtype: bool, float16, float32, float64, int8, int16, int32, int64,
uint8. Default: None. When `dtype` is not set, the dtype will get
from the global dtype by `paddle.get_default_dtype()`.
lod_level (int, optional): The LoD level of the LoDTensor. Usually users
don't have to set this value. For more details about when and how to
use LoD level, see :ref:`user_guide_lod_tensor` . Default: 0.
Returns:
Variable: The global variable that gives access to the data.
Examples:
.. code-block:: python
import numpy as np
import paddle
paddle.enable_static()
# Creates a variable with fixed size [3, 2, 1]
# User can only feed data of the same shape to x
# the dtype is not set, so it will set "float32" by
# paddle.get_default_dtype(). You can use paddle.get_default_dtype() to
# change the global dtype
x = paddle.static.data(name='x', shape=[3, 2, 1])
# Creates a variable with changeable batch size -1.
# Users can feed data of any batch size into y,
# but size of each data sample has to be [2, 1]
y = paddle.static.data(name='y', shape=[-1, 2, 1], dtype='float32')
z = x + y
# In this example, we will feed x and y with np-ndarray "1"
# and fetch z, like implementing "1 + 1 = 2" in PaddlePaddle
feed_data = np.ones(shape=[3, 2, 1], dtype=np.float32)
exe = paddle.static.Executor(paddle.framework.CPUPlace())
out = exe.run(paddle.static.default_main_program(),
feed={
'x': feed_data,
'y': feed_data
},
fetch_list=[z.name])
# np-ndarray of shape=[3, 2, 1], dtype=float32, whose elements are 2
print(out)
"""
helper = LayerHelper('data', **locals())
check_type(name, 'name', (six.binary_type, six.text_type), 'data')
check_type(shape, 'shape', (list, tuple), 'data')
shape = list(shape)
for i in six.moves.range(len(shape)):
if shape[i] is None:
shape[i] = -1
if dtype:
return helper.create_global_variable(
name=name,
shape=shape,
dtype=dtype,
type=core.VarDesc.VarType.LOD_TENSOR,
stop_gradient=True,
lod_level=lod_level,
is_data=True,
need_check_feed=True)
else:
return helper.create_global_variable(
name=name,
shape=shape,
dtype=paddle.get_default_dtype(),
type=core.VarDesc.VarType.LOD_TENSOR,
stop_gradient=True,
lod_level=lod_level,
is_data=True,
need_check_feed=True)
class InputSpec(object):
"""
InputSpec describes the signature information of the model input, such as ``shape`` , ``dtype`` , ``name`` .
This interface is often used to specify input tensor information of models in high-level API.
It's also used to specify the tensor information for each input parameter of the forward function
decorated by `@paddle.jit.to_static`.
Args:
shape (tuple(integers)|list[integers]): List|Tuple of integers
declaring the shape. You can set "None" or -1 at a dimension
to indicate the dimension can be of any size. For example,
it is useful to set changeable batch size as "None" or -1.
dtype (np.dtype|str, optional): The type of the data. Supported
dtype: bool, float16, float32, float64, int8, int16, int32, int64,
uint8. Default: float32.
name (str): The name/alias of the variable, see :ref:`api_guide_Name`
for more details.
Examples:
.. code-block:: python
from paddle.static import InputSpec
input = InputSpec([None, 784], 'float32', 'x')
label = InputSpec([None, 1], 'int64', 'label')
print(input) # InputSpec(shape=(-1, 784), dtype=VarType.FP32, name=x)
print(label) # InputSpec(shape=(-1, 1), dtype=VarType.INT64, name=label)
"""
def __init__(self, shape, dtype='float32', name=None):
# replace `None` in shape with -1
self.shape = self._verify(shape)
# convert dtype into united represention
if dtype is not None:
if not isinstance(dtype, core.VarDesc.VarType):
dtype = convert_np_dtype_to_dtype_(dtype)
self.dtype = dtype
self.name = name
def _create_feed_layer(self):
return data(self.name, shape=self.shape, dtype=self.dtype)
def __repr__(self):
return '{}(shape={}, dtype={}, name={})'.format(
type(self).__name__, self.shape, self.dtype, self.name)
@classmethod
def from_tensor(cls, tensor, name=None):
"""
Generates a InputSpec based on the description of input tensor.
Args:
tensor(Tensor): the source tensor to generate a InputSpec instance
Returns:
A InputSpec instance generated from Tensor.
Examples:
.. code-block:: python
import numpy as np
import paddle
from paddle.static import InputSpec
paddle.disable_static()
x = paddle.to_tensor(np.ones([2, 2], np.float32))
x_spec = InputSpec.from_tensor(x, name='x')
print(x_spec) # InputSpec(shape=(2, 2), dtype=VarType.FP32, name=x)
"""
if isinstance(tensor, (Variable, core.VarBase, core.eager.Tensor)):
return cls(tensor.shape, tensor.dtype, name or tensor.name)
else:
raise ValueError(
"Input `tensor` should be a Tensor, but received {}.".format(
type(tensor).__name__))
@classmethod
def from_numpy(cls, ndarray, name=None):
"""
Generates a InputSpec based on the description of input np.ndarray.
Args:
tensor(Tensor): the source numpy ndarray to generate a InputSpec instance
Returns:
A InputSpec instance generated from Tensor.
Examples:
.. code-block:: python
import numpy as np
from paddle.static import InputSpec
x = np.ones([2, 2], np.float32)
x_spec = InputSpec.from_numpy(x, name='x')
print(x_spec) # InputSpec(shape=(2, 2), dtype=VarType.FP32, name=x)
"""
return cls(ndarray.shape, ndarray.dtype, name)
def batch(self, batch_size):
"""
Inserts `batch_size` in front of the `shape`.
Args:
batch_size(int): the inserted integer value of batch size.
Returns:
The original InputSpec instance by inserting `batch_size` in front of `shape`.
Examples:
.. code-block:: python
from paddle.static import InputSpec
x_spec = InputSpec(shape=[64], dtype='float32', name='x')
x_spec.batch(4)
print(x_spec) # InputSpec(shape=(4, 64), dtype=VarType.FP32, name=x)
"""
if isinstance(batch_size, (list, tuple)):
if len(batch_size) != 1:
raise ValueError(
"Length of batch_size: {} shall be 1, but received {}.".
format(batch_size, len(batch_size)))
batch_size = batch_size[1]
elif not isinstance(batch_size, six.integer_types):
raise TypeError("type(batch_size) shall be `int`, but received {}.".
format(type(batch_size).__name__))
new_shape = [batch_size] + list(self.shape)
self.shape = tuple(new_shape)
return self
def unbatch(self):
"""
Removes the first element of `shape`.
Returns:
The original InputSpec instance by removing the first element of `shape` .
Examples:
.. code-block:: python
from paddle.static import InputSpec
x_spec = InputSpec(shape=[4, 64], dtype='float32', name='x')
x_spec.unbatch()
print(x_spec) # InputSpec(shape=(64,), dtype=VarType.FP32, name=x)
"""
if len(self.shape) == 0:
raise ValueError(
"Not support to unbatch a InputSpec when len(shape) == 0.")
self.shape = self._verify(self.shape[1:])
return self
def _verify(self, shape):
"""
Verifies the input shape and modifies `None` into `-1`.
"""
if not isinstance(shape, (list, tuple)):
raise TypeError(
"Type of `shape` in InputSpec should be one of (tuple, list), but received {}.".
format(type(shape).__name__))
if len(shape) == 0:
raise ValueError(
"`shape` in InputSpec should contain at least 1 element, but received {}.".
format(shape))
for i, ele in enumerate(shape):
if ele is not None:
if not isinstance(ele, six.integer_types):
raise ValueError(
"shape[{}] should be an `int`, but received `{}`:{}.".
format(i, type(ele).__name__, ele))
if ele is None or ele < -1:
shape[i] = -1
return tuple(shape)
def __hash__(self):
# Note(Aurelius84): `name` is not considered as a field to compute hashkey.
# Because it's no need to generate a new program in following cases while using
# @paddle.jit.to_static.
#
# Case 1:
# foo(x_var)
# foo(y_var)
# x_var and y_var hold same shape and dtype, they should share a same program.
#
#
# Case 2:
# foo(x_var)
# foo(x_np) # x_np is a numpy.ndarray.
# x_var and x_np hold same shape and dtype, they should also share a same program.
return hash((tuple(self.shape), self.dtype))
def __eq__(self, other):
slots = ['shape', 'dtype', 'name']
return (type(self) is type(other) and all(
getattr(self, attr) == getattr(other, attr) for attr in slots))
def __ne__(self, other):
return not self == other
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

PaddlePaddle (PArallel Distributed Deep LEarning 并行分布式深度学习)是百度研发的深度学习平台,具有易用,高效,灵活和可伸缩等特点,为百度内部多项产品提供深度学习算法支持
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/VisionDeveloper/Paddle.git
git@gitee.com:VisionDeveloper/Paddle.git
VisionDeveloper
Paddle
Paddle
develop
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /