tensorflow 入门

      TensorFlow是由Google创建的一个开源软件库,用于实现机器学习和深度学习系统。这两个名称包含一系列共享挑战的强大算法 - 允许计算机学习如何自动发现复杂模式和/或做出最佳决策。

TensorFlow的核心是数据流编程库。它利用各种优化技术使数学表达式的计算更容易,更高效。

TensorFlow的一些主要功能包括:

  • 有效地处理涉及多维数组的数学表达式
  • 深度神经网络和机器学习概念的良好支持
  • GPU / CPU计算,可以在两种体系结构上执行相同的代码
  • 跨机器和大型数据集的高可扩展性计算

这些特性使TensorFlow成为生产规模的机器智能的完美框架。

在这个TensorFlow教程中,您将学习如何在TensorFlow中使用简单但功能强大的机器学习方法,以及如何使用它的一些辅助库来调试,可视化和调整用它创建的模型。

1.使用anconda安装tensorflow

参见博客,有详细的安装教程

本文主要讲如何使用tensorflow

2.数据流图(将运算可视化,这一部分稍作了解)

在TensorFlow中,使用数据流图描述计算。图的每个节点表示数学运算的实例(如加法,除法或乘法),并且每个边是在其上执行运算的多维数据集(张量)。

3.常量

在TensorFlow中,使用函数常量创建常量,该函数常量具有签名constant(value, dtype=None, shape=None, name='Const', verify_shape=False),其中value是将在进一步计算中使用的实际常量值,dtype是数据类型参数(例如,float32 / 64,int8 / 16等),shape是可选维度,name是张量的可选名称,最后一个参数是布尔值,表示验证值的形状。

如果您需要在训练模型中具有特定值的常量,则constant可以使用该对象,如下例所示:

z = tf.constant(5.2, name="x", dtype=tf.float32)

4.变量

 

TensorFlow中的变量是包含张量的内存缓冲区,必须显式初始化并在图中使用以维持会话中的状态。通过简单地调用构造函数,可以在计算图中添加变量。

一旦开始使用训练模型,变量就特别有用,它们用于保存和更新参数。作为构造函数的参数传递的初始值表示可以作为张量转换或返回的张量或对象。这意味着如果我们想要在训练过程中使用一些预定义或随机值填充变量,然后在迭代中更新,我们可以通过以下方式定义它:

k = tf.Variable(tf.zeros([1]), name="k")

在TensorFlow中使用变量的另一种方法是在计算中,该变量不可训练,并且可以通过以下方式定义:

k = tf.Variable(tf.add(a, b), trainable=False)

5.session

为了实际评估节点,我们必须在会话中运行计算图。

会话封装TensorFlow运行时的控件和状态。没有参数的会话将使用在当前会话中创建的默认图,否则会话类接受图形参数,该参数在该会话中用于执行。

下面是一个简短的代码片段,显示了如何在TensorFlow中使用上面定义的术语来计算简单的线性函数。

import tensorflow as tf

x = tf.constant(-2.0, name="x", dtype=tf.float32)
a = tf.constant(5.0, name="a", dtype=tf.float32)
b = tf.constant(13.0, name="b", dtype=tf.float32)

y = tf.Variable(tf.add(tf.multiply(a, x), b))

init = tf.global_variables_initializer()

with tf.Session() as session:
    session.run(init)
    print session.run(y)

使用TensorFlow:定义计算图

使用数据流图表的好处是执行模型与其执行(在CPU,GPU或某种组合上)分开,一旦实现,TensorFlow中的软件可以在CPU或GPU上使用,其中所有复杂性都与代码相关执行是隐藏的。

计算图可以在使用TensorFlow库的过程中构建,而无需显式实例化Graph对象。

TensorFlow中的Graph对象可以作为简单代码行的结果创建c = tf.add(a, b)。这将创建一个操作节点,该节点采用两个张量a并将b其总和c作为输出。

计算图是一个内置的过程,它使用库而无需直接调用对象。TensorFlow中的图形对象(包含一组操作和张量作为数据单元)用于允许相同过程并包含多个图形的操作之间,其中每个图形将分配给不同的会话。例如,简单的代码c = tf.add(a, b)行将创建一个操作节点,该节点采用两个张量ab作为输入,并将它们的和c作为输出。

TensorFlow还提供了一种馈送机制,用于将张量修补到图中的任何操作,其中馈送用张量值替换操作的输出。Feed run()函数作为函数调用中的参数传递。

占位符是TensorFlow允许开发人员通过占位符将数据注入到计算图中的方式,这些占位符绑定在某些表达式中。占位符的签名是:

placeholder(dtype, shape=None, name=None)

其中dtype是张量中元素的类型,可以提供要进给的张量的形状和操作的名称。

如果形状未通过,则可以以任何形状进给该张量。一个重要的注意事项是占位符张量必须提供数据,否则,在执行会话时,如果缺少该部分,占位符将生成具有以下结构的错误:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'y' with dtype float

占位符的优点在于它们允许开发人员创建操作和一般的计算图,而无需事先提供数据,并且可以在运行时从外部源添加数据。

让我们来看一个简单的问题,即乘以两个整数xyTensorFlow方式,其中占位符将通过会话run方法与提要机制一起使用。

import tensorflow as tf

x = tf.placeholder(tf.float32, name="x")
y = tf.placeholder(tf.float32, name="y")

z = tf.multiply(x, y, name="z")

with tf.Session() as session:
    print session.run(z, feed_dict={x: 2.1, y: 3.0})

使用TensorBoard可视化计算图

TensorBoard是一种用于分析数据流图的可视化工具。这对于更好地理解机器学习模型非常有用。

使用TensorBoard,您可以深入了解有关参数的不同类型的统计信息以及有关计算图形部分的详细信息。深度神经网络具有大量节点并不罕见。TensorBoard允许开发人员深入了解每个节点以及如何在TensorFlow运行时上执行计算。

TensorBoard图表视图

现在让我们回到我们的示例,从TensorFlow教程开始,我们用格式定义了一个线性函数y = a*x + b

为了记录以后可以在TensorBoard中使用的会话中的事件,TensorFlow提供了FileWriter该类。它可用于创建事件文件,用于存储构造函数接受六个参数的摘要事件,如下所示:

__init__(logdir, graph=None, max_queue=10, flush_secs=120, graph_def=None, filename_suffix=None)

其中需要logdir参数,其他参数具有默认值。graph参数将从训练程序中创建的会话对象传递。完整的示例代码如下所示:

import tensorflow as tf


x = tf.constant(-2.0, name="x", dtype=tf.float32)
a = tf.constant(5.0, name="a", dtype=tf.float32)
b = tf.constant(13.0, name="b", dtype=tf.float32)


y = tf.Variable(tf.add(tf.multiply(a, x), b))


init = tf.global_variables_initializer()


with tf.Session() as session:
    merged = tf.summary.merge_all() // new
    writer = tf.summary.FileWriter("logs", session.graph) // new


    session.run(init)
    print session.run(y)

我们只添加了两个新行。我们合并了默认图表中收集的所有摘要,并分别FileWriter用于将事件转储到文件中。

运行程序后,我们将文件放在目录日志中,最后一步是运行tensorboard

tensorboard --logdir logs/

现在TensorBoard在默认端口6006上启动并运行。打开http://localhost:6006并单击Graphs菜单项(位于页面顶部)后,您将能够看到图形,如下图所示:

TensorBoard数据流图

TensorBoard标记常量和摘要节点特定符号,如下所述。

图图标

数学与TensorFlow

张量是TensorFlow中的基本数据结构,它们代表数据流图中的连接边。

张量只是标识多维数组或列表。张量结构可以用三个参数来识别:等级,形状和类型。

  • 等级:标识张量的维数。等级被称为张量的阶数或n维,其中例如等级1张量是矢量或等级2张量是矩阵。
  • 形状:张量的形状是它具有的行数和列数。
  • 类型:分配给张量元素的数据类型。

要在TensorFlow中构建张量,我们可以构建一个n维数组。这可以通过使用NumPy库或通过将Python n维数组转换为TensorFlow张量来轻松完成。

具有不同尺寸的张量

要构建一维张量,我们将使用一个NumPy数组,我们将通过传递一个内置的Python列表来构造它。

import numpy as np
tensor_1d = np.array([1.45, -1, 0.2, 102.1])

使用这种数组类似于使用内置的Python列表。主要区别在于NumPy数组还包含一些其他属性,如尺寸,形状和类型。

>> print tensor_1d
[   1.45   -1.      0.2   102.1 ]

>> print tensor_1d[0]
1.45

>> print tensor_1d[2]
0.2

>> print tensor_1d.ndim
1

>> print tensor_1d.shape
(4,)

>> print tensor_1d.dtype
float64

NumPy数组可以使用辅助函数convert_to_tensor轻松转换为TensorFlow张量,这有助于开发人员将Python对象转换为张量对象。此函数接受张量对象,NumPy数组,Python列表和Python标量。

tensor = tf.convert_to_tensor(tensor_1d, dtype=tf.float64)

现在,如果我们将张量绑定到TensorFlow会话,我们将能够看到转换的结果。

tensor = tf.convert_to_tensor(tensor_1d, dtype=tf.float64)

with tf.Session() as session:
    print session.run(tensor)
    print session.run(tensor[0])
    print session.run(tensor[1])

输出:

[   1.45   -1.      0.2   102.1 ]
1.45
-1.0

我们可以用类似的方式创建一个二维张量或矩阵:

tensor_2d = np.array(np.random.rand(4, 4), dtype='float32')
tensor_2d_1 = np.array(np.random.rand(4, 4), dtype='float32')
tensor_2d_2 = np.array(np.random.rand(4, 4), dtype='float32')

m1 = tf.convert_to_tensor(tensor_2d)
m2 = tf.convert_to_tensor(tensor_2d_1)
m3 = tf.convert_to_tensor(tensor_2d_2)
mat_product = tf.matmul(m1, m2)
mat_sum = tf.add(m2, m3)
mat_det = tf.matrix_determinant(m3)

with tf.Session() as session:
    print session.run(mat_product)
    print session.run(mat_sum)
    print session.run(mat_det)

张量操作

在上面的例子中,我们在向量和矩阵上引入了一些TensorFlow操作。操作在张量上执行某些计算。这些计算如下表所示。

TensorFlow运算符描述
tf.addX + Y
tf.subtractXY
tf.multiplyX * Y
tf.divx / y的
tf.modx%y
tf.abs| X |
tf.negative-X
tf.sign签(x)的
tf.squareX * X
tf.round轮(x)的
tf.sqrtSQRT(x)的
tf.powX ^ÿ
tf.expE 1 X
tf.log日志(X)
tf.maximummax(x,y)
tf.minimummin(x,y)
tf.cosCOS(x)的
tf.sin的sin(x)

上表中列出的TensorFlow操作使用张量对象,并按元素执行。因此,如果要计算向量x的余弦值,TensorFlow操作将对传递的张量中的每个元素进行计算。

tensor_1d = np.array([0, 0, 0])
tensor = tf.convert_to_tensor(tensor_1d, dtype=tf.float64)
with tf.Session() as session:
    print session.run(tf.cos(tensor))

输出:

[ 1.  1.  1.]

矩阵运算

矩阵运算对于机器学习模型非常重要,例如线性回归,因为它们经常被用在它们中。TensorFlow支持所有最常见的矩阵运算,像乘法移调反转,计算行列式,求解线性方程组,并有更多的

接下来,我们将解释一些矩阵运算。它们在机器学习模型中往往很重要,比如线性回归。让我们编写一些代码,这些代码将执行基本的矩阵运算,如乘法,获得转置,获得行列式,乘法,sol等等。

以下是调用这些操作的基本示例。

import tensorflow as tf
import numpy as np

def convert(v, t=tf.float32):
    return tf.convert_to_tensor(v, dtype=t)

m1 = convert(np.array(np.random.rand(4, 4), dtype='float32'))
m2 = convert(np.array(np.random.rand(4, 4), dtype='float32'))
m3 = convert(np.array(np.random.rand(4, 4), dtype='float32'))
m4 = convert(np.array(np.random.rand(4, 4), dtype='float32'))
m5 = convert(np.array(np.random.rand(4, 4), dtype='float32'))

m_tranpose = tf.transpose(m1)
m_mul = tf.matmul(m1, m2)
m_det = tf.matrix_determinant(m3)
m_inv = tf.matrix_inverse(m4)
m_solve = tf.matrix_solve(m5, [[1], [1], [1], [1]])

with tf.Session() as session:
    print session.run(m_tranpose)
    print session.run(m_mul)
    print session.run(m_inv)
    print session.run(m_det)
    print session.run(m_solve)

 

降维

TensorFlow支持不同类型的缩减。缩减是一种通过在这些维度上执行某些操作来从张量中移除一个或多个维度的操作。可以在此处找到当前版本的TensorFlow支持的减少列表。我们将在下面的示例中介绍其中的一些。

import tensorflow as tf
import numpy as np

def convert(v, t=tf.float32):
    return tf.convert_to_tensor(v, dtype=t)

x = convert(
    np.array(
        [
            (1, 2, 3),
            (4, 5, 6),
            (7, 8, 9)
        ]), tf.int32)

bool_tensor = convert([(True, False, True), (False, False, True), (True, False, False)], tf.bool)

red_sum_0 = tf.reduce_sum(x)
red_sum = tf.reduce_sum(x, axis=1)

red_prod_0 = tf.reduce_prod(x)
red_prod = tf.reduce_prod(x, axis=1)

red_min_0 = tf.reduce_min(x)
red_min = tf.reduce_min(x, axis=1)

red_max_0 = tf.reduce_max(x)
red_max = tf.reduce_max(x, axis=1)

red_mean_0 = tf.reduce_mean(x)
red_mean = tf.reduce_mean(x, axis=1)

red_bool_all_0 = tf.reduce_all(bool_tensor)
red_bool_all = tf.reduce_all(bool_tensor, axis=1)

red_bool_any_0 = tf.reduce_any(bool_tensor)
red_bool_any = tf.reduce_any(bool_tensor, axis=1)


with tf.Session() as session:
    print "Reduce sum without passed axis parameter: ", session.run(red_sum_0)
    print "Reduce sum with passed axis=1: ", session.run(red_sum)

    print "Reduce product without passed axis parameter: ", session.run(red_prod_0)
    print "Reduce product with passed axis=1: ", session.run(red_prod)

    print "Reduce min without passed axis parameter: ", session.run(red_min_0)
    print "Reduce min with passed axis=1: ", session.run(red_min)

    print "Reduce max without passed axis parameter: ", session.run(red_max_0)
    print "Reduce max with passed axis=1: ", session.run(red_max)

    print "Reduce mean without passed axis parameter: ", session.run(red_mean_0)
    print "Reduce mean with passed axis=1: ", session.run(red_mean)

    print "Reduce bool all without passed axis parameter: ", session.run(red_bool_all_0)
    print "Reduce bool all with passed axis=1: ", session.run(red_bool_all)

    print "Reduce bool any without passed axis parameter: ", session.run(red_bool_any_0)
    print "Reduce bool any with passed axis=1: ", session.run(red_bool_any)

输出:

Reduce sum without passed axis parameter:  45
Reduce sum with passed axis=1:  [ 6 15 24]
Reduce product without passed axis parameter:  362880
Reduce product with passed axis=1:  [  6 120 504]
Reduce min without passed axis parameter:  1
Reduce min with passed axis=1:  [1 4 7]
Reduce max without passed axis parameter:  9
Reduce max with passed axis=1:  [3 6 9]
Reduce mean without passed axis parameter:  5
Reduce mean with passed axis=1:  [2 5 8]
Reduce bool all without passed axis parameter:  False
Reduce bool all with passed axis=1:  [False False False]
Reduce bool any without passed axis parameter:  True
Reduce bool any with passed axis=1:  [ True  True  True]

减少运算符的第一个参数是我们想要减少的张量。第二个参数是我们想要执行缩减的维度索引。该参数是可选的,如果未通过,则将沿所有维度执行缩减。

我们可以看一下reduce_sum操作。我们传递一个二维张量,并希望沿着维度1减少它。

在我们的例子中,结果总和将是:

[1 + 2 + 3 = 6, 4 + 5 + 6 = 15, 7 + 8 + 9 = 24]

如果我们传递维度0,结果将是:

[1 + 4 + 7 = 12, 2 + 5 + 8 = 15, 3 + 6 + 9 = 18]

如果我们不传递任何轴,结果只是总和:

1 + 4 + 7 = 12, 2 + 5 + 8 = 15, 3 + 6 + 9 = 45

所有减少功能都具有类似的界面,并在TensorFlow 减少文档中列出。

分割

分段是一个过程,其中一个维度是将维度映射到提供的段索引的过程,并且结果元素由索引行确定。

分段实际上是在重复索引下对元素进行分组,因此,例如,在我们的例子中,我们[0, 0, 1, 2, 2]在张量上应用了分段id tens1,这意味着第一个和第二个数组将在分段操作之后进行转换(在我们的例子中求和)并且将得到一个新的数组,看起来像(2, 8, 1, 0) = (2+0, 5+3, 3-2, -5+5)。张量中的第三个元素tens1是未触及的,因为它没有被分组在任何重复的索引中,并且最后两个数组的求和方式与第一个组的情况相同。除了求和之外,TensorFlow还支持乘积平均值最大值最小值

分段总和

import tensorflow as tf
import numpy as np




def convert(v, t=tf.float32):
    return tf.convert_to_tensor(v, dtype=t)


seg_ids = tf.constant([0, 0, 1, 2, 2])
tens1 = convert(np.array([(2, 5, 3, -5), (0, 3, -2, 5), (4, 3, 5, 3), (6, 1, 4, 0), (6, 1, 4, 0)]), tf.int32)
tens2 = convert(np.array([1, 2, 3, 4, 5]), tf.int32)


seg_sum = tf.segment_sum(tens1, seg_ids)
seg_sum_1 = tf.segment_sum(tens2, seg_ids)


with tf.Session() as session:
    print "Segmentation sum tens1: ", session.run(seg_sum)
    print "Segmentation sum tens2: ", session.run(seg_sum_1)
Segmentation sum tens1:  
[[ 2  8  1  0]
 [ 4  3  5  3]
 [12  2  8  0]]
 
Segmentation sum tens2: [3 3 9]

序列实用程序

序列实用程序包括以下方法:

  • argmin函数,它返回输入张量轴上具有最小值的索引,
  • argmax函数,它返回输入张量轴上具有最大值的索引,
  • setdiff,它计算两个数字或字符串列表之间的差异,
  • where函数,它将从两个传递的元素x或y返回元素,这取决于传递的条件,或
  • unique 功能,它将返回1-D张量中的独特元素。

我们在下面演示一些执行示例:

import numpy as np
import tensorflow as tf

def convert(v, t=tf.float32):
    return tf.convert_to_tensor(v, dtype=t)

x = convert(np.array([
    [2, 2, 1, 3],
    [4, 5, 6, -1],
    [0, 1, 1, -2],
    [6, 2, 3, 0]
]))

y = convert(np.array([1, 2, 5, 3, 7]))
z = convert(np.array([1, 0, 4, 6, 2]))

arg_min = tf.argmin(x, 1)
arg_max = tf.argmax(x, 1)
unique = tf.unique(y)
diff = tf.setdiff1d(y, z)

with tf.Session() as session:
    print "Argmin = ", session.run(arg_min)
    print "Argmax = ", session.run(arg_max)

    print "Unique_values = ", session.run(unique)[0]
    print "Unique_idx = ", session.run(unique)[1]

    print "Setdiff_values = ", session.run(diff)[0]
    print "Setdiff_idx = ", session.run(diff)[1]

    print session.run(diff)[1]

输出:

Argmin = [2 3 3 3]
Argmax =  [3 2 1 0]
Unique_values =  [ 1.  2.  5.  3.  7.]
Unique_idx =  [0 1 2 3 4]
Setdiff_values =  [ 5.  3.  7.]
Setdiff_idx =  [2 3 4]

使用TensorFlow进行机器学习

在本节中,我们将展示TensorFlow的机器学习用例。第一个例子是用kNN方法对数据进行分类的算法,第二个例子是使用线性回归算法

k近邻

第一种算法是k-最近邻(kNN)。它是一种监督学习算法,它使用距离度量,例如欧几里德距离,来根据训练对数据进行分类。它是最简单的算法之一,但仍然非常强大,可用于分类数据。这个算法的优点:

  • 当训练模型足够大时,给出高精度
  • 通常对异常值不敏感,我们不需要对数据做任何假设。

这个算法的缺点:

  • 计算上昂贵的,和
  • 需要大量内存,需要将新的分类数据添加到所有初始培训实例中。

kNN概述

我们将在此代码示例中使用的距离是Euclidean,它定义了两点之间的距离,如下所示:

数学方程

在这个公式中,n是空间的维数,x是训练数据的向量,y是我们想要分类的新数据点。

import os
import numpy as np
import tensorflow as tf

ccf_train_data = "train_dataset.csv"
ccf_test_data = "test_dataset.csv"

dataset_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../datasets'))

ccf_train_filepath = os.path.join(dataset_dir, ccf_train_data)
ccf_test_filepath = os.path.join(dataset_dir, ccf_test_data)

def load_data(filepath):
    from numpy import genfromtxt

    csv_data = genfromtxt(filepath, delimiter=",", skip_header=1)
    data = []
    labels = []

    for d in csv_data:
        data.append(d[:-1])
        labels.append(d[-1])

    return np.array(data), np.array(labels)

train_dataset, train_labels = load_data(ccf_train_filepath)
test_dataset, test_labels = load_data(ccf_test_filepath)

train_pl = tf.placeholder("float", [None, 28])
test_pl = tf.placeholder("float", [28])

knn_prediction = tf.reduce_sum(tf.abs(tf.add(train_pl, tf.negative(test_pl))), axis=1)

pred = tf.argmin(knn_prediction, 0)

with tf.Session() as tf_session:
    missed = 0

    for i in xrange(len(test_dataset)):
        knn_index = tf_session.run(pred, feed_dict={train_pl: train_dataset, test_pl: test_dataset[i]})

        print "Predicted class {} -- True class {}".format(train_labels[knn_index], test_labels[i])

        if train_labels[knn_index] != test_labels[i]:
            missed += 1

    tf.summary.FileWriter("../samples/article/logs", tf_session.graph)

print "Missed: {} -- Total: {}".format(missed, len(test_dataset))

我们在上面的例子中使用的数据集是可以在Kaggle数据集部分找到的数据集。我们使用的包含欧洲持卡人信用卡交易的那个。我们使用的数据没有任何清理或过滤,并且根据Kaggle中对此数据集的描述,它是高度不平衡的。数据集包含31个变量:Time,V1,...,V28,Amount和Class。在此代码示例中,我们仅使用V1,...,V28和Class。类别标签为1的欺诈交易和不为0的交易。

代码示例主要包含我们在前面部分中描述的内容,但我们引入了加载数据集的函数。该函数load_data(filepath)将CSV文件作为参数,并返回一个元组,其中包含以CSV格式定义的数据和标签。

在该功能的下方,我们为测试和训练数据定义了占位符。训练数据用于预测模型中以解析需要分类的输入数据的标签。在我们的例子中,kNN使用欧几里德距离来获得最近的标签。

错误率可以通过简单除法计算,当分类器错过了在我们的情况下对于该数据集的示例总数为0.2时(即,分类器为20%的测试数据提供了错误的数据标签)。

线性回归

线性回归算法寻找两个变量之间的线性关系。如果我们将因变量标记为y,将自变量标记为x,那么我们将尝试估计函数的参数y = Wx + b

线性回归是应用科学领域中广泛使用的算法。该算法允许在实现中添加机器学习的两个重要概念:成本函数和用于找到函数最小值的梯度下降方法

使用该方法实现的机器学习算法必须预测y作为x线性回归算法将确定值的位置的函数的值,W并且b这些值实际上是未知的并且在整个训练过程中确定。选择成本函数,并且通常使用均方误差,其中梯度下降是用于找到成本函数的局部最小值的优化算法。

梯度下降方法只是局部函数最小值,但它可以用于搜索全局最小值,方法是在找到局部最小值并多次重复此过程后随机选择一个新起点。如果函数的最小值数量有限并且尝试次数非常多,则很有可能在某个时刻发现全局最小值。关于这种技术的更多细节我们将留给我们在介绍部分中提到的文章

import tensorflow as tf
import numpy as np

test_data_size = 2000
iterations = 10000
learn_rate = 0.005

def generate_test_values():
    train_x = []
    train_y = []

    for _ in xrange(test_data_size):
        x1 = np.random.rand()
        x2 = np.random.rand()
        x3 = np.random.rand()
        y_f = 2 * x1 + 3 * x2 + 7 * x3 + 4
        train_x.append([x1, x2, x3])
        train_y.append(y_f)

    return np.array(train_x), np.transpose([train_y])

x = tf.placeholder(tf.float32, [None, 3], name="x")
W = tf.Variable(tf.zeros([3, 1]), name="W")
b = tf.Variable(tf.zeros([1]), name="b")
y = tf.placeholder(tf.float32, [None, 1])

model = tf.add(tf.matmul(x, W), b)

cost = tf.reduce_mean(tf.square(y - model))
train = tf.train.GradientDescentOptimizer(learn_rate).minimize(cost)

train_dataset, train_values = generate_test_values()

init = tf.global_variables_initializer()

with tf.Session() as session:
    session.run(init)

    for _ in xrange(iterations):

        session.run(train, feed_dict={
            x: train_dataset,
            y: train_values
        })

    print "cost = {}".format(session.run(cost, feed_dict={
        x: train_dataset,
        y: train_values
    }))

    print "W = {}".format(session.run(W))
    print "b = {}".format(session.run(b))

输出:

cost = 3.1083032809e-05
W = [[ 1.99049103]
 [ 2.9887135 ]
 [ 6.98754263]]
b = [ 4.01742554]

在上面的例子中,我们有两个新的变量,我们叫costtrain。通过这两个变量,我们定义了一个我们想要在训练模型中使用的优化器和我们想要最小化的函数。

最后,输出参数Wb应该与generate_test_values函数中定义的参数相同。在第17行,我们实际上定义了我们用来产生线性数据点来训练,其中的函数w1=2w2=3w3=7b=4。上述示例的线性回归是多变量,其中使用了多个自变量。

结论

正如您在TensorFlow教程中所看到的,TensorFlow是一个功能强大的框架,可以轻松地处理数学表达式和多维数组,这在机器学习中是必不可少的。它还抽象出执行数据图和缩放的复杂性。

随着时间的推移,TensorFlow越来越受欢迎,现在正被开发人员用于解决问题,使用深度学习方法进行图像识别,视频检测,文本处理,如情绪分析等。与任何其他库一样,您可能需要一些时间来使用关于TensorFlow构建的概念。而且,一旦您这样做,在文档和社区支持的帮助下,将问题表示为数据图并使用TensorFlow解决它们可以使机器学习成为一个不那么繁琐的过程。

 

参考https://www.toptal.com/machine-learning/tensorflow-machine-learning-tutorial

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值