深度学习入门:张量

0阶  标量  a = 1 2 3

1阶  向量  b = [1, 2, 3]

2阶  矩阵  c = [[1, 2, 3], [2, 3, 4 ]]

n阶  张量  d = [ [ …[ 元素 ]… ] ]

数据类型

tf.int, tf.float        tf.int 32, tf.float32, tf.float64

tf.bool                   tf.constant( [ True, False ] )

tf.string                 tf.constant( " Hello, world! " )

如何创建一个Tensor

1.  创建一个tensor

        tf.constant( 张量内容, dtype = 数据类型 (可选) )

import tensorflow as tf

a = tf.constant( [1, 5], dtype = tf.int64 )

 shape中的逗号隔开了几个数字,代表这个张量就是几维的。数字是几就有几个元素。

2.  numpy类型转换为Tensor

        tf.convert_to_tensor( 数据名, dtype=数据类型(可选))

import tensorflow as tf
import numpy as np

a = np.arange(0,5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print(a)
print(b)

3.  创建指定数值的Tensor

        创建全为0的张量                                        维度:

                tf.zeros( 维度 )                                        一维 直接写个数

        创建全为1的张量                                            二维 用 [行, 列]

                tf.zeros( 维度 )                                        多维 用 [n, m, j, k……]

        创建全为指定值得张量

                tf.fill( 维度, 指定值)

a = tf.zeros([2,3])
b = tf.ones(5)
c = tf.fill([2,2],10)

with tf.Session() as sess:
    print("a:")
    print(a)
    print(a.eval())
    print("b:")
    print(b)
    print(b.eval())
    print("c:")
    print(c)
    print(c.eval())
    

4.  生成随机Tensor 

生成正态分布的随机数,默认均值为0,标准差为1

        tf.random.normal( 维度,mean=均值,stddev=标准差)

生成截断式正态分布的随机数

        tf.random.truncate_normal( 维度,mean=均值,stddev=标准差)

在  tf.random.truncate_normal中如果随机生成数据的取值在(μ-2σ, μ+2σ)。

d = tf.random.normal([2,2], mean=0.5, stddev=1)
e = tf.random.truncated_normal([2,2], mean=0.5, stddev=1)

with tf.Session() as sess:
    print("d:")
    print(d)
    print(d.eval())
    print("e:")
    print(e)
    print(e.eval())

 生成均匀分随机数  [ minval, maxval ]

        tf.random.uniform( 维度,minval=最小值,maxval=最大值)

f = tf.random.uniform([3,3], minval=0, maxval=10)

with tf.Session() as sess:
    print("f:")
    print(f)
    print(f.eval())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值