Tensorflow (3)

擷取自網路

設定好環境後,開始學習一些基本語法。寫程式的人應該對 Hello World 很熟悉吧。

After setting up configuration, we start to learn some basic syntax. Every programmer should be familiar with ‘Hello world’, right?

Print

import tensorflow as tf

# set up the constant
hello = tf.constant('hello world')

# start session
sess = tf.Session()

# run the operation
print(sess.run(hello))
擷取自網路

Basic operation

There are two ways to do basic operations.

  1. Using constant
import tensorflow as tf

# Basic operations
# set up constant

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

# print the output 
with tf.Session() as sess:
    print("a=2, b=3")
    print("Addition with constants: %i" % sess.run(a+b))
    print("Multiplication with constants: %i" % sess.run(a*b))
    print("Subtraction with constants: %i" % sess.run(a-b))
    print("Division with constants: %i" % sess.run(a/b))

2. Using variables

import tensorflow as tf

#Define a and b
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

# Define operations
add = tf.add(a,b)
mul = tf.multiply(a,b)
sub = tf.subtract(a,b)
div = tf.divide(a,b)


#Print the output
with tf.Session() as sess:
    # Run every operation with variable input
    print("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 5}))
    print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 5}))
    print("Subtraction with variables: %i" % sess.run(sub, feed_dict={a: 2, b: 5}))
    print("Division with variables: %i" % sess.run(div, feed_dict={a: 2, b: 5}))

這篇文章,我們介紹了基本的操作。

In this article, we introduce some basic operations.

-MsHe

發表留言