tensorflow(张量生成)

# -*- coding: utf-8 -*- 
import tensorflow as tf
import numpy as np
# 创建张量
a = tf.constant([1, 5], dtype=tf.int64)
print("a:", a)
print("a.dtype:", a.dtype)
print("a.shape:", a.shape)
a: tf.Tensor([1 5], shape=(2,), dtype=int64)
a.dtype: <dtype: 'int64'>
a.shape: (2,)
# 将np格式的数据转换为Tensor格式
a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print("a:", a)
print("b:", b)
a: [0 1 2 3 4]
b: tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)
a = tf.zeros([2, 3]) # 创建全为0的张量
b = tf.ones(4) # 创建全为1的张量
c = tf.fill([2, 2], 9) #创建全为指定值的张量
print("a:", a)
print("b:", b)
print("c:", c)
a: tf.Tensor(
[[0. 0. 0.]
 [0. 0. 0.]], shape=(2, 3), dtype=float32)
b: tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32)
c: tf.Tensor(
[[9 9]
 [9 9]], shape=(2, 2), dtype=int32)
d = tf.random.normal([2, 2], mean=0.5, stddev=1) # 生成正态分布的随机数,默认均值为0,标准差为1
print("d:", d)
e = tf.random.truncated_normal([2, 2], mean=0.5, stddev=1) #生成截断式正态分布,生成的数据取值在正负两倍标准差之内,数据更集中
print("e:", e)
d: tf.Tensor(
[[ 2.5829678  -1.2323483 ]
 [-0.6496475   0.18799412]], shape=(2, 2), dtype=float32)
e: tf.Tensor(
[[0.8986387  2.126217  ]
 [1.2121066  0.28844398]], shape=(2, 2), dtype=float32)
f = tf.random.uniform([2, 2], minval=0, maxval=1) #生成均匀分布的随机数, minval最小值,maxval最大值
print("f:", f)
f: tf.Tensor(
[[0.06484163 0.00596273]
 [0.8598033  0.8169972 ]], shape=(2, 2), dtype=float32)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值