学习《简单粗暴TensorFlow2》

学习《简单粗暴TensorFlow2》

官方文档:https://tf.wiki/zh_hans/basic/basic.html

第一个tensorflow程序

#导入tensorflow模块并为模块起一个别名
import tensorflow as tf
#在此我们就现为它起别名为tf,即TensorFlow的缩写
A = tf.constant([[1,2],[3,4]])
B = tf.constant([[5,6],[7,8]])
C = tf.matmul(A,B)
print(C)

输出

tf.Tensor(
[[19 22]
 [43 50]], shape=(2, 2), dtype=int32)
  • 英文翻译
    constants:常数,常量
    matrix:矩阵
    multiplication:乘法
    可知matmul()函数功能为矩阵相乘
  • 回顾矩阵乘法计算
    定义矩阵 计算矩阵乘积

代码中的矩阵乘法

关于TensorFlow使用张量

TensorFlow使用张量(Tensor)作为数据基本单位
0维数组:标量
1维数组:向量
2维数组:矩阵
多维数组:张量
import tensorflow as tf
#定义一个随机数(标量)
random_float = tf.random.uniform(shape=())
#定义一个有2个元素的零向量
zeros_vector = tf.zeros(shape=(2))
#定义两个2*2的常量矩阵
A = tf.constant([[1.0,2.0],[3.0,4.0]])
B = tf.constant([[5.0,6.0],[7.0,8.0]])
#张量最重要的属性是形状、类型、值。可以通过shape、dtype 属性、与numpy()方法获取
print(A.shape)
print(A.dtype)
print(A.numpy())

输出

(2, 2)
<dtype: 'float32'>
[[1. 2.]
 [3. 4.]]

指定张量内容数据类型

import tensorflow as tf
#在TensorFlow中大多数API都会默认张量的元素类型为tf.float32
#也可以加入dtype参数指定
zero_vector = tf.zeros(shape=(2),dtype=tf.int32)
#tensorflow中的张量的numpy方法是将张量值转为一个NumPy数组返回
print(type(zero_vector.numpy()))

输出

<class 'numpy.ndarray'>
  • TensorFlow中里面有大量的操作,使得我们对张量进行相关计算
import tensorflow as tf
A = tf.constant([[1,2],[3,4]])
B = tf.constant([[1,2],[3,4]])
#计算矩阵 A + B
C = tf.add(A,B)
D = tf.matmul(A,B)
print(C)
print(D)

输出

tf.Tensor(
[[2 4]
 [6 8]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[ 7 10]
 [15 22]], shape=(2, 2), dtype=int32)

TensorFlow2自动求导机制

import tensorflow as tf
#TensorFlow引入了GradientTape() “求导记录器”来实现自动求导
#以 y(x)=x^2 计算在x=3时的导数

#定义tensorflow变量
x = tf.Variable(initial_value=3.)#变量x初始值为3
with tf.GradientTape() as tape:#与python3文件对象类似
    y = tf.square(x)
y_grad = tape.gradient(y,x) #计算y关于x的导数
print(y)
print(y_grad)
#可见在x=3时 关于函数y=x^2  y=9  y关于x的导数 2*x 为6

输出

tf.Tensor(9.0, shape=(), dtype=float32)
tf.Tensor(6.0, shape=(), dtype=float32)

TensorFlow多元函数求偏导数

在这里插入图片描述

import tensorflow as tf
#对于多元函数求偏导数,以及对向量或矩阵的求导
x = tf.constant([[1.,2.],[3.,4.]])
y = tf.constant([[1.],[2.]])
w = tf.Variable(initial_value=[[1.],[2.]])
b = tf.Variable(initial_value=1.)
with tf.GradientTape() as tape:
    L = tf.reduce_sum(tf.square(tf.matmul(x,w) + b -y))
w_grad,b_grad = tape.gradient(L,[w,b])
print(L)
print(w_grad)
print(b_grad)

输出

tf.Tensor(125.0, shape=(), dtype=float32)
tf.Tensor(
[[ 70.]
 [100.]], shape=(2, 1), dtype=float32)
tf.Tensor(30.0, shape=(), dtype=float32)
  • 表达式推导

在这里插入图片描述

  • 注意:关于+b的疑问?在numpy中有如下情况

在这里插入图片描述

体验线性模型

理论知识回顾

在这里插入图片描述在这里插入图片描述

  • 从房价价格回归问题入手线性模型

在这里插入图片描述

数据归一化

在这里插入图片描述

# 数据归一化
import numpy as np
x_data=[2013,2014,2015,2016,2017]
y_data=[12000,14000,15000,16500,17500]
X_array = np.array(x_data,dtype=np.float32)
Y_array = np.array(y_data,dtype=np.float32)

X = (X_array - X_array.min()) / (X_array.max() - X_array.min())
Y = (Y_array - Y_array.min()) / (Y_array.max() - X_array.min())

print(X)
print(Y)

输出

[0.   0.25 0.5  0.75 1.  ]
[0.         0.12914057 0.19371085 0.2905663  0.35513657]

在这里插入图片描述

numpy中的线性回归

梯度下降不做过多阐述、对此陌生的学习者可以在网络上寻找课程资源进行学习

#numpy中的线性回归
import numpy as np
#数据归一化
x_data=[2013,2014,2015,2016,2017]
y_data=[12000,14000,15000,16500,17500]
X_array = np.array(x_data,dtype=np.float32)
Y_array = np.array(y_data,dtype=np.float32)
X = (X_array - X_array.min()) / (X_array.max() - X_array.min())
Y = (Y_array - Y_array.min()) / (Y_array.max() - X_array.min())
print(X)
print(Y)
#np.dot()求内积 np.sum()求和
a,b = 0,0
num_epoch = 10000#梯度下降迭代次数
learning_rate = 5e-4#学习率
for i in range(num_epoch):
    y_pred = a * X + b
    grad_a,grad_b = 2*(y_pred - Y).dot(X),2 * (y_pred - Y).sum()
    #更新 a b
    a,b = a - learning_rate * grad_a,b - learning_rate * grad_b
print(a,b)
#我们可以得到当 a=0.34674477390013597 b=0.020443427665159785
#时损失最小
  • 公式推导

在这里插入图片描述
在这里插入图片描述

TensorFlow下的线性回归

# 数据归一化
import numpy as np
import tensorflow as tf
x_data=[2013,2014,2015,2016,2017]
y_data=[12000,14000,15000,16500,17500]
X_array = np.array(x_data,dtype=np.float32)
Y_array = np.array(y_data,dtype=np.float32)
X = (X_array - X_array.min()) / (X_array.max() - X_array.min())
Y = (Y_array - Y_array.min()) / (Y_array.max() - X_array.min())
print(X)
print(Y)
"""
在tensorflow中最好的优点就是自动求导机制
使用tape.gradient(y,x)自动计算梯度
使用optimizer.apply_gradients(grads_and_vars)自动更新模型参数
"""
#首先我们像数据集定义为张量进行表达
#将numpy数组转为tensorflow张量
X = tf.constant(X)
Y = tf.constant(Y)
#定义a、b变量
a = tf.Variable(initial_value=0.)
b = tf.Variable(initial_value=0.)
variables = [a,b]
num_epoch = 10000#梯度下降迭代次数
optimizer = tf.keras.optimizers.SGD(learning_rate=5e-4)
for i in range(num_epoch):
    with tf.GradientTape() as tape:
        y_pred=a * X + b
        loss = tf.reduce_sum(tf.square(y_pred - Y))
    # TensorFlow自动计算损失函数关于自变量地梯度
    grads = tape.gradient(loss,variables)
    # TensorFlow自动根据梯度更新参数
    optimizer.apply_gradients(grads_and_vars=zip(grads,variables))
print(a)
print(b)
#可以直到当a=0.34674457 b=0.020443512是loss最小化

  • 翻译
    optimizer(优化器) SGD(stochastic gradient sescent 随机梯度下降)
    learning_rate(学习率)
    Epoch 在深度学习中常定义为:
    使用训练集的全部数据对模型进行一次完整训练,被称之为"一代训练"

输出

[0.   0.25 0.5  0.75 1.  ]
[0.         0.12914057 0.19371085 0.2905663  0.35513657]
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=0.34674457>
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=0.020443512>
  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高万禄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值