Tensorflow2.0笔记 - 创建tensor

        tensor创建可以基于numpy,list或者tensorflow本身的API。

        笔记直接上代码:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

tf.__version__

#通过numpy创建tensor
tensor0 = tf.convert_to_tensor(np.ones([2,3]))
print(tensor0)
tensor1 = tf.convert_to_tensor(np.zeros([2,3]), dtype=tf.int32)
print(tensor1)

#通过list创建tensor
tensor2 = tf.convert_to_tensor([1,2,3])
print(tensor2)
tensor3 = tf.convert_to_tensor([[1,2,3],[4,5,6.]])
print(tensor3)

#通过tensorflow的API创建
tensor4 = tf.zeros([3,3])
print(tensor4)
tensor5 = tf.ones([2,5], dtype=tf.float32)
print(tensor5)
#zeros_like以传入的tensor的shape为模版,但是值为全0
#类似的还有ones_like
tensor6 = tf.zeros_like(tensor5)
#和tensor6 = tf.zeros(tensor5.shape)是一样的
print(tensor6)

#fill填充任意值
tensor7 = tf.fill([2,2], 1.5)
print(tensor7)

#随机正态分布
tensor8 = tf.random.normal([5,5], mean=1, stddev=1)
print(tensor8)
#带截断的随机正态分布
tensor9 = tf.random.truncated_normal([3,3], mean=0, stddev=1)
print(tensor9)

#均匀分布
tensor10 = tf.random.uniform([3,3], minval=-2, maxval=2)
print(tensor10)

#随机排列,shuffle
ids = tf.range(10)
ids = tf.random.shuffle(ids)
print(ids)
#下面假设trainData和trainLabel是训练数据和训练标签
#trainData包含10张28*28的图片,trainLabel是每张图片对应的标签
trainData = tf.random.normal([10, 28*28*1])
trainLabel = tf.random.uniform([10], minval=0, maxval=10, dtype=tf.int32)
print("TrainData:",trainData)
print("TrainLabel:", trainLabel)
#通过传入shuffle后的index,调用gather来打散训练数据和训练标签
#同时保证训练数据和训练标签都能用同一个下表索引到
trainData = tf.gather(trainData, ids)
trainLabel = tf.gather(trainLabel, ids)
print("Shuffled Train Data:", trainData)
print("Shuffled Train Label:", trainLabel)

  notebook运行结果截图:

 

相关推荐

  1. tensorflow中张量tensor

    2024-01-10 10:30:05       68 阅读
  2. tensorflow学习笔记(二)

    2024-01-10 10:30:05       20 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-10 10:30:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-10 10:30:05       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-10 10:30:05       82 阅读
  4. Python语言-面向对象

    2024-01-10 10:30:05       91 阅读

热门阅读

  1. 双机调度算法

    2024-01-10 10:30:05       63 阅读
  2. 力扣-135.分发糖果

    2024-01-10 10:30:05       49 阅读
  3. 基于长短期神经网络lstm的电子密度预测

    2024-01-10 10:30:05       57 阅读
  4. 可视化试题(二)

    2024-01-10 10:30:05       54 阅读
  5. 免费用chatGPT

    2024-01-10 10:30:05       67 阅读
  6. 第7章 DOM(下)

    2024-01-10 10:30:05       60 阅读
  7. AI真正的Killer App 仍然缺席

    2024-01-10 10:30:05       55 阅读
  8. 破解国企绩效管理中存在的三大难题

    2024-01-10 10:30:05       49 阅读