読者です 読者をやめる 読者になる 読者になる

TensorFLowの基本演算

定数

import tensorflow as tf

# 定数
a = tf.constant(2)
b = tf.constant(3)

with tf.Session() as sess:
    print("a: %i" % sess.run(a), "b: %i" % sess.run(b))
    print("Addition with constants: %i" % sess.run(a+b))
    print("Multiplication with constants: %i" % sess.run(a*b))

# a: 2 b: 3
# Addition with constants: 5
# Multiplication with constants: 6

変数

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

# 演算を定義
add = tf.add(a, b)
mul = tf.multiply(a, b)

with tf.Session() as sess:
    # Run every operation with variable input
    print("Addition with variables: %i" % sess.run(add, feed_dict={a: 2, b: 3}))
    print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))

# Addition with variables: 5
# Multiplication with variables: 6

行列演算

# 1x2 行列
matrix1 = tf.constant([[3., 3.]])

# 2x1行列
matrix2 = tf.constant([[2.],[2.]])

# 行列積
product = tf.matmul(matrix1, matrix2)

with tf.Session() as sess:
    result = sess.run(product)
    print(result)

# [[ 12.]]