Tensorflow学习之基础

tensorflow漫漫学习之路自此开始。

学习tensorflow之前,需要了解tensorflow内部数据的表现形式,tensorflow采用张量(Tensor)作为数据的基本单位,tensorflow中的张量可以表示为标量、一维数组、二维矩阵等。如下所示:                    

import tensorflow as tf

#定义一个标量
random_float=tf.random.uniform(shape=())
print('标量',random_float)
#定义一个有两个元素的零向量
zero_vec=tf.zeros(shape=(2))
print('向量',zero_vec)
#定义两个2*2的常量矩阵
A=tf.constant([[2.,4.],[1.,3.]])
B=tf.constant([[2.3,4.1],[1.3,3.5]])

print('矩阵',A)

输出如下所示: 

标量 tf.Tensor(0.031272292, shape=(), dtype=float32)
向量 tf.Tensor([0. 0.], shape=(2,), dtype=float32)
矩阵 tf.Tensor([[2. 4.],[1. 3.]], shape=(2, 2), dtype=float32)

 其中,tf.random.uniform(shape,minval=0,maxval=None,dtype=float32,seed=None,name=None)从均匀分布中输出值,该值在[minval,maxval)区间内遵循均匀分布。

shape:张量的形状即维度

minval:生成的随机值范围的下限,默认为0.

maxval:要生成的随机值范围的上限,如果 dtype 是浮点,则默认为1.

dtype:输出的类型有float16、float32、float64、int32、int64

seed:一个 Python 整数,用于为分布创建一个随机种子,查看 tf.set_random_seed 行为

name:操作的名称(可选)

 tf.zeros(shape,dtype,name)输出全零值的张量。

shape:张量的形状

dtype:输出的类型,如上

name:操作的名称

tf.constant(value,shape,dtype,name) 输出指定维度(shape)与值(value)的张量。

在tensorflow中可以通过shape、dtype、numpy获得张量的形状、类型以及值,若是没有指定值的类型,系统一般默认为floa32,也可以自己通过dtype指定类型。

tensorflow中对已有张量有大量的操作得到新的张量,如下所示:

add_c=tf.add(A,B)
matmul_c=tf.matmul(A,B)
print('和',add_c)
print('积',matmul_c)

和 tf.Tensor(
[[4.3 8.1]
 [2.3 6.5]], shape=(2, 2), dtype=float32)
积 tf.Tensor(
[[ 9.799999 22.2     ]
 [ 6.2      14.6     ]], shape=(2, 2), dtype=float32) 

从上可以看出,tf.add()只能对两个形状一样的张量进行操作,如\begin{bmatrix} 2 &3 \\ 4&5 \end{bmatrix}+\begin{bmatrix} 1 &3 \\ 3&2 \end{bmatrix}=\begin{bmatrix} 3& 6\\ 7&7 \end{bmatrix} 。tf.matmul()可以对两个形状不一致的张量进行操作,但必须符合A.shape为n*m,B.shape为m*k这样得出的张量形状为n*k,如\begin{bmatrix} 1 &1 &1 \\ 1& 1 &1 \end{bmatrix}\times \begin{bmatrix} 1 & 1 &1 \\ 1& 1 &1 \\ 1& 1 &1 \end{bmatrix}=\begin{bmatrix} 3 &3 &3 \\ 3&3 &3 \end{bmatrix}

 

在机器学习中,我们通常需要求导,tensorFlow中提供了强大的求导机制。

import tensorflow as tf
x = tf.Variable(initial_value=3.)
with tf.GradientTape() as tape:
# 在 tf.GradientTape() 的上下文内,所有计算步骤 都会被记录以用于求导 
    y = tf.square(x)
y_grad = tape.gradient(y, x)
# 计算y关于x的导数
print([y, y_grad])

参考文献 

https://blog.csdn.net/qq_36512295/article/details/100600001

https://blog.csdn.net/weixin_36670529/article/details/93470877

简单粗暴的tensorflow2.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值