Tensorflow笔记(持续更新)

人工智能:让机器具备人的思维和意识

  • 人工智能三学派
    • 行为注意:基于控制论,构建感知-动作控制系统(控制论,如平衡、行走、避障等自适应控制系统)
    • 符号主义:基于算数逻辑表达式,求解问题时先把问题描述为表达式,再求解表达式。(可用公式描述、实现理性思维,如专家系统)
    • 连接注意:仿生学,模仿神经元连接关系(仿脑神经元连接,实现感性思维,如神经网络)

用计算机仿出神经网络的连接关系,让计算机具备感性思维

  • 准备数据:采集大量“特征/标签”数据
  • 搭建网络:搭建神经网络结构
  • 优化参数:训练网络获取最佳参数(反向传播)
  • 应用网络:将网络保存为模型,输入新数据,输出分类或预测结果(前向传播)

搭建网络时随机初始化了所有参数w和f

  • 损失函数(loss function):预测值(y)和标准答案(y^)的差距。
  • 损失函数可以定量判断w、b的优劣,当损失函数输出最小时,参数w、b会出现最优值。

梯度下降

  • 目的:想找到一组参数w和b,使得损失函数最小
  • 梯度:函数对各参数求偏导后的向量。函数梯度下降方向是函数减小方向。
  • 梯度下降法:沿损失函数梯度下降的方向,寻找损失函数的最小值,得到最优参数的方法。
  • 学习率(learning rate,lr):当学习率设置的过小时,收敛过程将变得十分缓慢。而当学习率设置的过大时,梯度可能会在最小值附近来回震荡,甚至可能无法收敛。
  • 反向传播:从后向前,逐层求损失函数对每层神经元参数的偏导数,迭代更新所有参数。
  • 张量(Tensor):多维数组(列表) 阶:张量的维数
  • 张量可以表示0阶到n阶数组(列表)
维数名字例子
0-D0标量 scalars = 1 2 3
1-D1向量 vectorv=[1,2,3]
2-D2矩阵 matrixm=[ [1,2,3] , [4,5,6] , [7,8,9] ]
n-Dn张量 tensort = [ [ […n个

数据类型

  • tf.init , tf.float
    - tf.int 32 、 tf.float 32 、tf.float 64
  • tf.bool
    - tf.constant([ True,False])
  • tf.string
    - tf.constant(“Hello,world!”)

如何创建一个Tensor

  • 创建一个张量
    tf.constant(张量内容,dtype=数据类型(可选))
import tensorflow as tf
a = tf.constant([1,5],dtype = tf.int64)
print(a)
print(a.dtype)
print(a.shape)

运行结果
tf.Tensor([1 5], shape=(2,), dtype=int64)
<dtype: ‘int64’>
(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)

运行结果
[0 1 2 3 4]
tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)

  • 创建全为0的张量
    tf.zeros(维度)
    创建全为1的张量
    tf.ones(维度)
    创建全为指定值的张量
    tf.fill(维度,指定值)
import tensorflow as tf

a = tf.zeros([2, 3])
b = tf.ones(4)
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)

维度

  • 一维:直接写个数
  • 二维:用 [行,列]
  • 多维:用 [n,m,j,k…]
  • 生成正态分布的随机数,默认均值为0,标准差为1
    tf.random.normal(维度,mean=均值,stddev=标准差)
  • 生成截断式正态分布的随机数
    tf.random.truncated_normal(维度,mean=均值,stddev=标准差)
import tensorflow as tf

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

运行结果
d: tf.Tensor(
[ [-0.71590567 -0.47144413]
[ 0.16898265 2.6714728 ] ], shape=(2, 2), dtype=float32)
e: tf.Tensor(
[ [ 0.46750724 -1.4949024 ]
[ 0.8944788 1.1591487 ] ], shape=(2, 2), dtype=float32)

生成均匀分布随机数
tf.random.uniform(维度, minval=最小值, maxval=最大值)

import tensorflow as tf

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

运行结果
f: tf.Tensor(
[ [0.07836425 0.7483473 ]
[0.2908616 0.69293535] ], shape=(2, 2), dtype=float32)

常用函数

  • 强制tensor转换为该数据类型
    tf.cast(张量名, dtype=数据类型)
  • 计算张量维度上元素的最小值
    tf.reduce_min(张量名)
    计算张量维度上元素的最大值
    tf.reduce_max(张量名)
import tensorflow as tf

x1 = tf.constant([1., 2., 3.], dtype=tf.float64)
print("x1:", x1)
x2 = tf.cast(x1, tf.int32)
print("x2", x2)
print("minimum of x2:", tf.reduce_min(x2))
print("maxmum of x2:", tf.reduce_max(x2))

运行结果
x1: tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
x2 tf.Tensor([1 2 3], shape=(3,), dtype=int32)
minimum of x2: tf.Tensor(1, shape=(), dtype=int32)
maxmum of x2: tf.Tensor(3, shape=(), dtype=int32)

理解axis
在一个二维张量或数组中,可以通过调整axis等于0或1控制执行维度。

  • axis=0代表跨行(经度,down),而axis=1代表跨列(维度,across)
  • 如果不指定axis,则所有元素参与计算。
  • 计算张量沿着指定维度的平均值
    tf.reduce_mean(张量名,axis = 操作轴)
  • 计算张量沿着指定维度的和
    tf.reduce_sum(张量名,axis=操作轴)
import tensorflow as tf

x = tf.constant([[1, 2, 3], [2, 2, 3]])
print("x:", x)
print("mean of x:", tf.reduce_mean(x))  # 求x中所有数的均值
print("sum of x:", tf.reduce_sum(x, axis=1))  # 求每一行的和

运行结果
x: tf.Tensor(
[ [1 2 3 ]
[2 2 3 ] ], shape=(2, 3), dtype=int32)
mean of x: tf.Tensor(2, shape=(), dtype=int32)
sum of x: tf.Tensor([6 7], shape=(2,), dtype=int32)

tf.Variable()将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用该函数标记待训练参数。
tf.Variable(初始值)
w = tf.Variable(tf.random.normal([2,2],mean=0,stddev=1))

数学运算
对应元素的四则运算:tf.add、tf.subtract、tf.multiply、tf.divide
平方、次方与开方: tf.square、tf,pow、tf.sqrt
矩阵乘:tf.matmul

  • 实现两个张量的对应元素相加
    tf.add(张量1,张量2)
  • 实现两个张量的对应元素相减
    tf.subtract(张量1,张量2)
  • 实现两个张量的对应元素相乘
    tf.multiply(张量1,张量2)
  • 实现两个张量的对应元素相除
    tf.divide(张量1,张量2)

只有维度相同的张量才可以做四则运算

import tensorflow as tf

a = tf.ones([1, 3])
b = tf.fill([1, 3], 3.)
print("a:", a)
print("b:", b)
print("a+b:", tf.add(a, b))
print("a-b:", tf.subtract(a, b))
print("a*b:", tf.multiply(a, b))
print("b/a:", tf.divide(b, a))

运行结果
a: tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
b: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
a+b: tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32)
a-b: tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32)
a*b: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
b/a: tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)

  • 计算某个张量的平方
    tf.square(张量名)
  • 计算某个张量的n次方
    tf.pow(张量名,n次方数)
  • 计算某个张良的开方
    tf.sqrt(张量名)
import tensorflow as tf

a = tf.fill([1, 2], 3.)
print("a:", a)
print("a的平方:", tf.pow(a, 3))
print("a的平方:", tf.square(a))
print("a的开方:", tf.sqrt(a))

运行结果
a: tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
a的平方: tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
a的平方: tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
a的开方: tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)

  • 实现两个矩阵的相乘
    tf.matmul(矩阵1,矩阵2)
import tensorflow as tf

a = tf.ones([3, 2])
b = tf.fill([2, 3], 3.)
print("a:", a)
print("b:", b)
print("a*b:", tf.matmul(a, b))

运行结果
a*b: tf.Tensor(
[[6. 6. 6.]
[6. 6. 6.]
[6. 6. 6.]], shape=(3, 3), dtype=float32)

  • 切分传入张量的第一维度,生成输入特征/标签对,构建数据集
  • data = tf.data.Dataset.from_tensor_slices((输入特征,标签))
  • Numpy和Tensor格式都可用该语句读入数据
import tensorflow as tf

features = tf.constant([12, 23, 10, 17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
for element in dataset:
    print(element)

运行结果
(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)

tf.GradientTape实现某个函数对指定参数的求导运算

  • with结构记录计算过程,gradient求出张量的梯度
with tf.GradientTape() as tape:
	....
grad = tape.gradient(函数,对谁求导)
with tf.GradientTape() as tape:
	w = tf.Variable(tf.constant(3,0))
	loss = tf.pow(w,2)
grand = tape.gradient(loss,w)
print(grad)

运行结果
tf.Tensor(6.0,shape=(),dtype = float(32)

enumerate

enumerate是python的内建函数,它可便利每个元素(如列表、元组或字符串),组合为:索引 元素,常在for循环中使用。
enumerate(列表名)

seq = ['one','two','three']
for i,element in enumerate(seq):
	print(i,element)

运行结果
0 one
1 two
2 three

tf.one_hot

独热编码(one-hot encoding):在分类问题中,常用独热编码做标签,标记类别:1表示是,0表示非。

tf.one_hot()函数将待转换数据,转换为one-hot形式的数据输出。
tf.one_hot(待转换数据,depth=几分类)

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值