首页 > 技术文章 > TensorFlow机器学习&深度学习框架快速入门

yszd 2018-10-09 17:41 原文

 

一.简介

  TensorFlow是Google第二代机器学习和深度学习框架,支持CNN、RNN和LSTM算法,可以跨平台运行。TensorFlow底层部分是C++实现,具有较高的执行效率。支持不同的前端,包含Python和C++。

二.安装

  安装TensorFlow框架需要安装一些依赖工具,这些工具包括:

    1.html5lib-0.9999999

    2.bleach-1.5.0-py2.py3-none-any.whl

    3.Markdown-2.6.11-py2.py3-none-any.whl

    4.protobuf-3.6.1-cp36-cp36m-win_amd64.whl

    5.tensorboard-1.10.0-py3-none-any.whl

    6.tensorflow_tensorboard-1.5.1-py3-none-any.whl

  注意:在安装bleach-1.5.0-py2.py3-none-any.whl时会先下载html5lib-0.9999999.tar.gz包,就算是你已经安装好了html5lib,还是会继续下载,这时要是网络较差,就会一直下载失败,此时,可以这样执行安装,命令如下:pip install bleach-1.5.0-py2.py3-none-any.whl html5lib-0.9999999.tar.gz,记住,是tag.gz包,在windows下,文件扩展名gz不显示。  

  在上面提到的依赖安装完成后,执行安装tensorflow框架,安装成功如下:

  验证:

    

  在程序中引入tensorflow不提示无法识别!

三.代码实现

1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Tue Oct  2 15:49:08 2018
 4 
 5 @author: zhen
 6 """
 7 
 8 import tensorflow as tf
 9 import numpy as np
10 from sklearn.datasets import  fetch_california_housing
11 
12 x = tf.Variable(3, name='x')
13 y = tf.Variable(4, name='y')
14 
15 # 任何创建的节点会自动加入到默认的图中
16 print(x.graph is tf.get_default_graph())
17 
18 # 创建新的图
19 graph = tf.Graph()
20 
21 with graph.as_default():
22     # 只在with范围内有效
23     demo = tf.Variable(3)
24 
25 print(demo.graph is graph)
26     
27 demo2 = tf.Variable(3)
28 print(demo2.graph is graph)
29 
30 # 创建常量
31 constant = tf.constant(3)
32 
33 f = x * x * y + x * y + 1
34 f2 = f * constant
35 
36 # 可以不分别对每个变量去进行初始化,在run运行时初始化
37 init = tf.global_variables_initializer()
38 
39 with tf.Session() as sess:
40     init.run()
41     result = f.eval()
42     result2 = f2.eval()
43     print(result, result2)
44 
45     f_result, f2_result = sess.run([f, f2])
46     print(f_result, f2_result)
47 
48 # 获取数据集
49 housing = fetch_california_housing(data_home="C:/Users/zhen/.spyder-py3/data", download_if_missing=True)
50 # 获取x数据行数和列数
51 m, n = housing.data.shape
52 # 添加额外数据加入特征
53 housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
54 # 创建两个Tensorflow常量节点x和y,去持有数据和标签
55 x = tf.constant(housing_data_plus_bias, dtype=tf.float32, name='x')
56 y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')
57 # 矩阵操作
58 xt = tf.transpose(x)
59 # 计算最优解
60 theta = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(xt, x)), xt), y)
61 with tf.Session() as sess:
62     theta_value = theta.eval()
63     print(theta_value)

四.代码详解

  1.代码在执行时可能会报一下AVX警告【不影响程序正常执行】:

2020-01-13 09:46:26.930863: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2020-01-13 09:46:26.931377: W C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.

  这个警告意思是你安装的TensorFlow支持AVX/AVX2,但是没有编译,不能使用。使用AVX/AVX2可以提升你CPU的执行效率。一般出现这种情况是你安装TensorFlow时使用的是pip install tensorflow而不是源码安装。遇到这种情况可以在你的代码中添加一下程序指定日志级别,屏蔽警告信息:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

  2.fetch_california_housing

    加利福尼亚购房信息数据,这是一个开放的数据源,广泛使用在线性回归&逻辑回归算法的训练上。使用fetch_california_housing(data_home="C:/Users/zhen/.spyder-py3/data", download_if_missing=True)这行程序可以使用这个数据集。download_if_missing=True表示若data_home目录下不存在该数据,就直接下载该数据,若存在则直接加载此数据。

  3.tf.Variable() & tf.constant()

    使用tensorflow创建变量,variable是可变变量,constant是常量。

  4.eval()和run()的区别

    eval():将字符串对象转换为有效的表达式参与求值运算并返回计算结果。eval()也是启动计算的一种方式。基于tensorflow的基本原理,首先需要定义图,然后计算图,其中计算图的函数常见的有run()函数,如sess.run()。要注意的是,eval()只能用于tf.Tensor类对象,也就是有输出的Operation。对于没有输出的Operation,可以用run()或者Session.run(),Session.run()没有这个限制。

  5.np.ones & np.c_ & np.r_

    np.ones:创建一个全是1的n维数组,有三个参数:shape【指定返回数组的大小】、dtype【数组元素的类型,可以不指定,自动推演】、order【是否以内存中的C或Fortran连续顺序存储多维数据,可以不指定】。

    np.c_:按行连接两个矩阵,就是把两个矩阵按行进行拼接,要求行数一致。

    np.r_:按列连接两个矩阵,就是把两个矩阵按列进行拼接,要求列数一致。

  6.tf.transpose & tf.matmul

    tf.transpose:矩阵转置

    tf.matmul:矩阵相乘,与此类似的还有tf.multiply,tf.multiply表示矩阵对应元素相乘!

  7.tf.matrix_diag & tf.matrix_inverse

    tf.matrix_diag:输入一个向量,输出二维的对角矩阵。

    tf.matrix_inverse:输入一个矩阵,得到该矩阵的逆矩阵。需要矩阵中的数据为浮点数!

五.执行结果

  

六.备注

  离线包下载:https://pan.baidu.com/s/1DQdOViNreI9OjiGWLWHZ6g 提取码:ddfp

推荐阅读