Implementation of the public convert_to_tensor.
(value,
dtype=None,
name=None,
as_ref=False,
preferred_dtype=None,
ctx=None,
accepted_result_types=(Tensor,))
| 1247 | |
| 1248 | |
| 1249 | def internal_convert_to_tensor(value, |
| 1250 | dtype=None, |
| 1251 | name=None, |
| 1252 | as_ref=False, |
| 1253 | preferred_dtype=None, |
| 1254 | ctx=None, |
| 1255 | accepted_result_types=(Tensor,)): |
| 1256 | """Implementation of the public convert_to_tensor.""" |
| 1257 | if isinstance(value, EagerTensor): |
| 1258 | if ctx is None: |
| 1259 | ctx = context.context() |
| 1260 | if not ctx.executing_eagerly(): |
| 1261 | graph = get_default_graph() |
| 1262 | if not graph.building_function: |
| 1263 | raise RuntimeError("Attempting to capture an EagerTensor without " |
| 1264 | "building a function.") |
| 1265 | return graph.capture(value, name=name) |
| 1266 | |
| 1267 | if dtype is not None: |
| 1268 | dtype = dtypes.as_dtype(dtype) |
| 1269 | if isinstance(value, Tensor): |
| 1270 | if dtype is not None and not dtype.is_compatible_with(value.dtype): |
| 1271 | raise ValueError( |
| 1272 | "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" % |
| 1273 | (dtype.name, value.dtype.name, value)) |
| 1274 | return value |
| 1275 | |
| 1276 | if preferred_dtype is not None: |
| 1277 | preferred_dtype = dtypes.as_dtype(preferred_dtype) |
| 1278 | for base_type, conversion_func in tensor_conversion_registry.get(type(value)): |
| 1279 | # If dtype is None but preferred_dtype is not None, we try to |
| 1280 | # cast to preferred_dtype first. |
| 1281 | ret = None |
| 1282 | if dtype is None and preferred_dtype is not None: |
| 1283 | try: |
| 1284 | ret = conversion_func( |
| 1285 | value, dtype=preferred_dtype, name=name, as_ref=as_ref) |
| 1286 | except (TypeError, ValueError): |
| 1287 | # Could not coerce the conversion to use the preferred dtype. |
| 1288 | pass |
| 1289 | else: |
| 1290 | if (ret is not NotImplemented and |
| 1291 | ret.dtype.base_dtype != preferred_dtype.base_dtype): |
| 1292 | raise TypeError("convert_to_tensor did not convert to " |
| 1293 | "the preferred dtype: %s vs %s " % |
| 1294 | (ret.dtype.base_dtype, preferred_dtype.base_dtype)) |
| 1295 | |
| 1296 | if ret is None: |
| 1297 | ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) |
| 1298 | |
| 1299 | if ret is NotImplemented: |
| 1300 | continue |
| 1301 | |
| 1302 | if not isinstance(ret, accepted_result_types): |
| 1303 | raise RuntimeError( |
| 1304 | "%sConversion function %r for type %s returned non-Tensor: %r" % |
| 1305 | (_error_prefix(name), conversion_func, base_type, ret)) |
| 1306 | if dtype and not dtype.is_compatible_with(ret.dtype): |
no test coverage detected