Tensorflow基础操作

目录

1.张量(Tensor)

2.创建Tensor

2.1 tf.zero()

2.2 tf.zeros_like()

2.3 tf.ones()

​编辑

2.4 fill(),设置shape并初试化shape中的值

​编辑

2.5 normal()

2.6.tf.constant()

3.将numpy或list转为Tensor

3.1 a = tf.convert_to_tensor(b)

4.将list中元素逐个转换为Tensor对象然后依次放入Dataset中

5.Dense()

6.Conv2D():卷积

​编辑


下载安装:

链接:https://pan.baidu.com/s/107V18x6wqaXWerwj8hxMKA?pwd=2022 
提取码:2022 

1.张量(Tensor)

3                                       # 这个 0 阶张量就是标量,shape=[]
[1., 2., 3.]                            # 这个 1 阶张量就是向量,shape=[3]
[[1., 2., 3.], [4., 5., 6.]]            # 这个 2 阶张量就是二维数组,shape=[2, 3]
[[[1., 2., 3.]], [[7., 8., 9.]]]        # 这个 3 阶张量就是三维数组,shape=[2, 1, 3]

2.创建Tensor

2.1 tf.zero()

import tensorflow as tf

tensor1 = tf.zeros([])
tensor2 = tf.zeros([1]) #参数表示shape()
tensor3 = tf.zeros([2,2])

print(tensor1)
print(tensor2)
print(tensor3)

"""
tf.Tensor(0.0, shape=(), dtype=float32)
tf.Tensor([0.], shape=(1,), dtype=float32)
tf.Tensor(
[[0. 0.]
 [0. 0.]], shape=(2, 2), dtype=float32)
"""

2.2 tf.zeros_like()

2.3 tf.ones()

2.4 fill(),设置shape并初试化shape中的值

import tensorflow as tf

a = tf.fill([2,2],0)
b = tf.fill([2,2,2],9)
print(a)
print(b)
"""
tf.Tensor(
[[0 0]
 [0 0]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[[9 9]
  [9 9]]

 [[9 9]
  [9 9]]], shape=(2, 2, 2), dtype=int32)
"""

2.5 normal()

2.6.tf.constant()

3.将numpy或list转为Tensor

3.1 a = tf.convert_to_tensor(b)

例如: 

import numpy as np
import tensorflow as tf

numpy1 = np.ones([2,3])
numpy2 = np.zeros([2,3])
list = [1,2]

tensor1 = tf.convert_to_tensor(np.ones([2,3]))  #将numpy数据转化为Tensor数据
tensor2 = tf.convert_to_tensor(list) #list转Tensor

print("numpy的数据类型:",np.ones([2,3]))
print("numpy转Tensor:",tensor1)
print("list转Tensor:",tensor2)

4.将list中元素逐个转换为Tensor对象然后依次放入Dataset中

import tensorflow as tf
# 传入list,将list中元素逐个转换为Tensor对象然后依次放入Dataset中
x1 = [0, 1, 2, 3, 4]
x2 = [[0, 1], [2, 3], [4, 5]]
ds1 = tf.data.Dataset.from_tensor_slices(x1)
ds2 = tf.data.Dataset.from_tensor_slices(x2)
for step, m in enumerate(ds1):
    print(m)  # tf.Tensor(0, shape=(), dtype=int32)...
for step, m in enumerate(ds2):
    print(m)  # tf.Tensor([0 1], shape=(2,), dtype=int32)...

# 传入tuple。这种形式适合整合特征和标签。
xx = [[0, 1], [2, 3], [4, 5]]
yy = [11, 22, 33]
ds11 = tf.data.Dataset.from_tensor_slices((xx, yy))
for step, (ds11_xx, ds11_yy) in enumerate(ds11):
    print(ds11_xx)  # tf.Tensor([0 1], shape=(2,), dtype=int32)...
    print(ds11_yy)  # tf.Tensor(11, shape=(), dtype=int32)...

5.Dense()

6.Conv2D():卷积

import tensorflow as tf
from keras.applications.densenet import layers

x = tf.random.normal((4,32,32,3))
net = layers.Conv2D(16,kernel_size=3)
print(net(x).shape)

"""
(4, 30, 30, 16)
"""

 
 

猜你喜欢

转载自blog.csdn.net/m0_55196097/article/details/126109939