人工智能实践——tensorflow基础

张量的定义

张量(tensor):多维数组 阶:张量的维数
维数 阶 名字 例子
0-D 0 量 标量 scalar s=1 2 3
1-D 1 量 向量 vector v=[1, 2, 3]
2-D 2 阵 矩阵 matrix m=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n-D n 量 张量 tensor t=[ [ […

张量可以表示0 阶到n阶数组(列表)

创建一个张量常量

tf.constant( 常量,dtype= 数据类型( 可选))

import tensorflow as tf
a=tf.constant([1,2],dtype=tf.int32)
print(a)
print(a.dtype)
print(a.shape)

输出结果:
<tf.Tensor([1,2],shape=(2,),dtype=int32)
<dtype: ‘int32’>

import tensorflow as tf
a=tf.constant([[[1,2,3]]],dtype=tf.int32)
print(a)
print(a.dtype)#类型
print(a.shape)
#维度。

输出结果:
tf.Tensor([[[1 2 3]]], shape=(1, 1, 3), dtype=int32)
<dtype: ‘int32’>
(1, 1, 3)

创建全为零的张量
tf. zeros( 维度)
创建全为一的张量
tf. ones( 维度)
创建全为某个指定数的张量
tf. fill( 维度,填充数据)

a = tf.zeros([2, 3])
b = tf.ones(1)
c = tf.fill([2, 2], 9)
print(a)
print(b)
print(c)

输出结果:
tf.Tensor([[0. 0. 0.]
[0. 0. 0.]], shape=(2, 3), dtype=float32)
tf.Tensor([1.], shape=(1,), dtype=float32)
tf.Tensor([[9 9]
[9 9]], shape=(2, 2), dtype=int32)

正态分布

 生成正态分布的数据,默认均值为0 ,标准差为1
tf. random.normal( 数据维度,mean= 均值,stddev= 标准差)

 生成截断式正态分布的数据
tf. random.truncated_normal( 数据维度,mean= 均值,stddev= 标准差)

import tensorflow as tf
import numpy as np
d = tf.random.normal([2, 2],mean=0.5, stddev=1)
print(d)
e = tf.random.truncated_normal([2, 2], mean=0.5, stddev=1)
print(e)

输出结果:
d: tf.Tensor(
[[-0.9323255 1.5851804]
[ 1.9090635 3.4960582]], shape=(2, 2), dtype=float32)
e: tf.Tensor(
[[ 0.04409307 -0.30970353]
[ 1.25547 -0.38355815]], shape=(2, 2), dtype=float32)

#随机数的生成都是生成非常多的数字,从中抽取规格,所以可能不完全均匀或者正态

均匀分布

import tensorflow as tf
import os
f = tf.random.uniform([2, 2], minval=0, maxval=1)
print("f:", f)

输出结果:
f: tf.Tensor(
[[0.66599214 0.13926649]
[0.43506563 0.751691 ]], shape=(2, 2), dtype=float32)

找最大值和最小值

import tensorflow as tf
import os
x1 = tf.constant([1., 2., 3.], dtype=tf.float64)
print("x1:", x1)
x2 =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值