机器学习实战(10)——Tensorflow

CSDN话题挑战赛第2期
参赛话题:学习笔记

目录

1 TensorFlow中的线性回归

module 'tensorflow' has no attribute 'xxx'解决方案

2 梯度下降的实现

2.1 手工计算梯度

2.2 使用自动微分

2.3 使用优化器

3 给训练算法提供数据

4 保存和恢复模型

5 用TensorBoard来可视化图和训练曲线


供参考:开始 (juejin.im)

有关 tensorflow 参考文档可以在上述网站下载。

一个Tensorflow程序通常可以分成两个部分:第一部分用来构建一个计算图(称为构建阶段),第二部分来执行这个图(称为执行阶段)。构建阶段通常会构建一个计算图,这个图用来展现ML模型和训练所需的计算。执行阶段则重复地执行每一步训练动作,并逐步提升模型的参数。

在此我们使用jupyter进行演练,如果你还没有下载安装tensorflow,可以使用下面代码实现:

pip install tensorflow -i https://pypi.tuna.tsinghua.edu.cn/simple

常规模块导入及可视化设置:

# Common imports
import numpy as np
import os

# 结果复现,随机数种子
def reset_graph(seed=42):
    tf.compat.v1.reset_default_graph() #tensorflow2.0以上版本需要tf.compat.v1作为接口
    tf.compat.v1.set_random_seed(seed)
    np.random.seed(seed)

# To plot pretty figures
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

1 TensorFlow中的线性回归

输入和输出都是多维数组的话,叫做张量。之前我们演示的代码中,张量都只包含了单个标量值,但可以对任意形状的数组进行计算。

下面的代码展示了如何操作二维的数组来计算加州的住房数据的线性回归。首先,获取数据。然后,对所有训练实例都添加一个额外的偏移。接下来,创建两个TensorFlow的常量节点,x和y以及目标(标签,注意housing.target是一个一维数组,我们需要将它变成一个列向量再来计算)。

module 'tensorflow' has no attribute 'xxx'解决方案

你也可以选择略过该部分,如果你是初次使用tf请留步:

有关module 'tensorflow' has no attribute 'xxx'可以参考:

关于tensorflow 中module ‘tensorflow‘ has no attribute ‘xxx‘问题的根本解决方法。_进击的炼丹师的博客-CSDN博客

tensorflow张量和numpy数组相互转换,参考:

​​​​​​tensorflow张量和numpy数组相互转换_新诺斯给的博客-CSDN博客_tf转numpy

代码展示:

注意:tensorflow2.0以上版本需要tf.compat.v1作为接口

因此,我们可以这样导入:

import tenforflow.compat.v1 as tf

不过,下面为了体现接口,我依然是使用以下导入:

import tenforflow as tf

eager_execution 是tensorflow的立即执行模式,在2.x的tensorflow版本中是默认打开,我们需要调用tf.compat.v1.disable_eager_execution()去关闭。

如果不关闭该模式,则需要.numpy()来转换成数组,继续用eval()则会报错:

用tf.compat.v1.disable_eager_execution()去关闭:

import numpy as np
from sklearn.datasets import fetch_california_housing

reset_graph()
tf.compat.v1.disable_eager_execution()

#加载数据
housing = fetch_california_housing()
m, n = housing.data.shape

#偏移
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]

#创建两个常量节点
X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")

#转置
XT = tf.transpose(X) #transpose()为tf内置矩阵函数(转置),下同

#正规方程
#下面tf.matmul(a,b) #矩阵ab相乘

theta = tf.matmul(tf.matmul(tf.compat.v1.matrix_inverse(tf.matmul(XT, X)), XT), y)

#使用with,也就是python的上下文管理器,执行会会自动关闭会话,释放内存,简单高效!
with tf.compat.v1.Session() as sess:
    theta_value = theta.eval() #与tf.compat.v1.disable_eager_execution()呼应
    
theta_value

用.numpy()来转换成数组:

import numpy as np
from sklearn.datasets import fetch_california_housing

reset_graph()

housing = fetch_california_housing()
m, n = housing.data.shape
housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]

X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name="X")
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y")
XT = tf.transpose(X)
theta = tf.matmul(tf.matmul(tf.compat.v1.matrix_inverse(tf.matmul(XT, X)), XT), y)

with tf.compat.v1.Session() as sess:
    theta_value = theta.numpy()
    
theta_value

运行后你会发现,两个结果是一样的:

array([[-3.68901253e+01],
       [ 4.36643779e-01],
       [ 9.45042260e-03],
       [-1.07117996e-01],
       [ 6.43712580e-01],
       [-3.96291580e-06],
       [-3.78801115e-03],
       [-4.20931637e-01],
       [-4.34006572e-01]], dtype=float32)

我们之前 numpy 是这样计算 theta_value:

X = housing_data_plus_bias
y = housing.target.reshape(-1, 1)
theta_numpy = np.linalg.
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值