forget tf1! tensorflow2的数据类型,tensor属性参数以及创建方法

本文介绍了TensorFlow2中的数据类型,包括constant、Tensor的device和check属性,讨论了Tensor的类型转换,并详细阐述了如何创建Tensor,如从numpy或list创建,使用tf.ones、zeros、fill,以及随机分布如正态、均匀分布等方法。同时,文章还涵盖了Scalar、Vector和Matrix的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tensorflow2

import tensorflow as tf
import numpy as np

tensorflow数据类型

constant(可修改)

a = tf.constant(1)
print(a)
a = tf.constant(2)
print(a)
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.constant(1.)
<tf.Tensor: shape=(), dtype=float32, numpy=1.0>
tf.constant(2.2, dtype=tf.double)
<tf.Tensor: shape=(), dtype=float64, numpy=2.2>
tf.constant([True, False])
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, False])>
tf.constant('hello tf')
<tf.Tensor: shape=(), dtype=string, numpy=b'hello tf'>

Tensor Property

device

tf.test.is_gpu_available()
WARNING:tensorflow:From <ipython-input-7-17bb7203622b>:1: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.





True
tf.config.list_physical_devices('GPU')
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
with tf.device('cpu'):
    a = tf.constant([1])
with tf.device('gpu'):
    b = tf.range(4)
    
print(a.device)
print(b.device)

aa = a.gpu()
print(aa.device)

bb = b.cpu()
print(bb.device)
/job:localhost/replica:0/task:0/device:CPU:0
/job:localhost/replica:0/task:0/device:GPU:0
WARNING:tensorflow:From <ipython-input-9-b0029145c942>:9: _EagerTensorBase.gpu (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.identity instead.
/job:localhost/replica:0/task:0/device:GPU:0
WARNING:tensorflow:From <ipython-input-9-b0029145c942>:12: _EagerTensorBase.cpu (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.identity instead.
/job:localhost/replica:0/task:0/device:CPU:0

check

x = tf.range(4)<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值