基于TensorFlow的机器学习(1) -- 基础介绍

关于tensorflow的相关基础概念,可以参考之前写过的介绍文章。后期由于需要进行大量的代码实践,因此将会基于源代码对Tensorflow进行系统性的学习。

首先是使用tensorflow输出Hello World:

import tensorflow as tf
# simple hello world using Tensorflow

# Create a Constant op
# The op is added as a node to the default graph

# The value returned by the constructor represents the output
# of the Constant op.
hello = tf.constant("Hello, Tensorflow!")

# Start tf session
sess = tf.Session()

# Run graph
print sess.run(hello) # => Hello, Tensorflow!

相对而言较为简单,不进行详述。

接下来看tensorflow如何采用常量的方式进行算数运算:

import tensorflow as tf

a = tf.constant(2)
b = tf.constant(3)

# Launch the default graph.
with tf.Session() as sess:
    print "a: %i" % sess.run(a), "b: %i" % sess.run(b)
    #print "Add: %i" % (sess.run(a) + sess.run(b))
    print "Add: %i" % sess.run(a+b)
    print "Mul: %i" % sess.run(a*b)
    # a:2 b:3, Add: 5, Mul: 6

我们知道,tensorflow是基于图的张量流运算,而上述是直接进行的常量声明,与实际并不是很相符合,因此我们接下来进行张量流图的使用:

import tensorflow as tf

a = tf.placeholder(tf.int32)
b = tf.placeholder(tf.int32)

# Define some operations
add = tf.add(a, b)
mul = tf.multiply(a, b)

# Launch the default graph
with tf.Session() as sess:
    print "Add: %i" % sess.run(add, feed_dict={a:2, b:3})
    print "Mul: %i" % sess.run(mul, feed_dict={a:2, b:3})
# Add: 5 Mul: 6

上述所有都是张量,还可以使用矩阵来进行操作(机器学习中几乎所有的运算归根结底都是h矩阵运算):

import tensorflow as tf

matrix1 = tf.constant([[3.,3.]])
# print matrix1
matrix2 = tf.constant([[2.], [2.]])
# print matrix2

product = tf.matmul(matrix1, matrix2)
# print product

with tf.Session() as sess:
    result = sess.run(product)
    print result  # => [[ 12. ]]

以上即是tensorflow基础运算的所有内容,内容编写主要的参考资料为https://github.com/aymericdamien/TensorFlow-Examples

上述所有代码亲测可在Ubuntu 16.04, python 2.7 相关环境下运行通过。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值