tensorflow低阶api基础编程

tf常量

import tensorflow as tf
import numpy as np
#tf常量的定义
a=tf.constant(7)
#tf常量的值
print(a.numpy())
#python中tf常量输出
print(a)


#结果
7
tf.Tensor(7, shape=(), dtype=int32)

tf变量

#声明一个tf变量
a2=tf.Variable(7)
#声明一个tf变量数组
a3=tf.Variable([1,2,3])
print(a2,a3)
print(a2.numpy(),a3.numpy())


#结果
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=7> <tf.Variable 'Variable:0' shape=(3,) dtype=int32, numpy=array([1, 2, 3])>
7 [1 2 3]

tf形状切换

#tf形状切换
a4=tf.Variable([[1,2,3],[4,5,6]])
print("转换前:")
print(a4.numpy())
a4=tf.reshape(a4,[3,2])
print("转换后:")
print(a4.numpy())


#结果
转换前:
[[1 2 3]
 [4 5 6]]
转换后:
[[1 2]
 [3 4]
 [5 6]]

tf平均值
tf.math.reduce_mean(input_tensor, axis=None, keepdims=False, name=None)

tf.math.reduce_mean(input_tensor, axis=None, keepdims=False, name=None)
参数
axis均值方向默认求所有值的均值,0为所有列求均值,1为所有行求均值
keepdims是否保持数组的状态0为不保持,1为保持
a=tf.constant([1,2.,3,4,5,6,7.])
print(a.dtype)
print(tf.math.reduce_mean(a).numpy())
b=tf.constant([[1,2,1.],[5,2,10]])
print(b.dtype)
print(tf.math.reduce_mean(b).numpy())
print(tf.math.reduce_mean(b,1).numpy())
print(tf.math.reduce_mean(b,0,1).numpy())


#结果
<dtype: 'float32'>
4.0
<dtype: 'float32'>
3.5
[1.3333334 5.6666665]
[[3.  2.  5.5]]

正态分布

tf.random.normal(shape,mean=0.0,stddev=1.0,dtype=tf.float32,seed=None,name=None,)
参数
shape矩阵形状
mean正态的中心值
std正态的标准差
seed随机种子
dtype数据类型
a=tf.random.normal([2,3],2,dtype=float)
a.numpy()


#结果
array([[1.5612446, 1.3915725, 3.9122813],
       [2.382679 , 1.5241811, 2.0791621]], dtype=float32)

均匀分布

tf.random.uniform(shape,minval=0,maxval=None,dtype=tf.float32,seed=None,name=None,)
参数列表
shape矩阵形状
minval最小值
maxval最大值
seed随机种子
dtype数据类型
tf.random.uniform([2,3]).numpy()


#结果
array([[0.07327175, 0.75695205, 0.8055048 ],
       [0.56755877, 0.40262008, 0.98317564]], dtype=float32)

矩阵转置

a=[[1,1],[2,2]]
print("a为:")
print(a)
print("转置后")
tf.transpose(a).numpy()

#结果
a为:
[[1, 1], [2, 2]]
转置后
Out[44]:
array([[1, 2],
       [1, 2]])

求最大数的索引位置

参数
input输入数组
axis计算的维度,默认为0,按列计算,1为按行计算
a=[[2,1],[3,4]]
tf.math.argmax(a,1).numpy()

#结果
array([1, 1], dtype=int64)

维度扩展

a=[1,2]
print(tf.expand_dims(a,0))
print(tf.expand_dims(a,1))

#结果
tf.Tensor([[1 2]], shape=(1, 2), dtype=int32)
tf.Tensor(
[[1]
 [2]], shape=(2, 1), dtype=int32)

矩阵连接

a=[1]
b=[2]
print(tf.concat([a,b],0).numpy())
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
print(tf.concat([t1,t2],axis=0).numpy())

#结果
[1 2]
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]

数据类型转换

a=1
tf.bitcast(a,tf.float32).numpy()

#结果
1e-45
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值