In [2]:
from __future__ import print_function
import tensorflow as tf
with tf.Session():
input1 = tf.constant([1.0,1.0,1.0,1.0])
input2 = tf.constant([2.0,2.0,2.0,2.0])
output = tf.add(input1, input2)
result = output.eval()
print("result: ", result)
In [3]:
# 基于numpy的写法
print([x + y for x,y in zip([1.0]*4, [2.0]*4)])
In [4]:
import numpy as np
x, y = np.full(4, 1.0), np.full(4, 2.0)
print("{} + {} = {}".format(x, y ,x+y))
In [5]:
import tensorflow as tf
with tf.Session():
input1 = tf.constant(1.0, shape=[4])
input2 = tf.constant(2.0, shape=[4])
input3 = tf.constant(3.0, shape=[4])
output = tf.add(tf.add(input1,input2),input3)
result = output.eval()
print(result)
In [6]:
# 操作符重载
with tf.Session():
input1 = tf.constant(1.0, shape=[4])
input2 = tf.constant(2.0, shape=[4])
output = input1 + input2
print(output.eval())
In [7]:
# 矩阵操作(2阶张量)
import tensorflow as tf
import numpy as np
with tf.Session():
input1 = tf.constant(1.0,shape=[2,3])
input2 = tf.constant(np.reshape(np.arange(1.0,7.0, dtype=np.float32), (2,3)))
output = tf.add(input1,input2)
print(output.eval())
In [8]:
# 矩阵相乘
#@test {"output": "ignore"}
import tensorflow as tf
import numpy as np
with tf.Session():
input_features = tf.constant(np.reshape([1,0,0,1],(1,4)).astype(np.float32))
weights = tf.constant(np.random.randn(4,2).astype(np.float32))
output = tf.matmul(input_features, weights)
print("Input:")
print(input_features.eval())
print("Weights:")
print(weights.eval())
print("Output:")
print(output.eval())
In [9]:
# 用变量迭代
#@test {"output": "ignore"}
import tensorflow as tf
import numpy as np
with tf.Session() as sess:
total = tf.Variable(tf.zeros([1,2]))
weights = tf.Variable(tf.random_uniform([1,2]))
tf.global_variables_initializer().run()
update_weights = tf.assign(weights, tf.random_uniform([1,2], -1.0, 1.0))
update_total = tf.assign(total, tf.add(total, weights))
for _ in range(5):
sess.run(update_weights)
sess.run(update_total)
print(weights.eval(),total.eval())
In [ ]: