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)


result:  [ 3.  3.  3.  3.]

In [3]:
# 基于numpy的写法
print([x + y for x,y in zip([1.0]*4, [2.0]*4)])


[3.0, 3.0, 3.0, 3.0]

In [4]:
import numpy as np
x, y = np.full(4, 1.0), np.full(4, 2.0)
print("{} + {} = {}".format(x, y ,x+y))


[ 1.  1.  1.  1.] + [ 2.  2.  2.  2.] = [ 3.  3.  3.  3.]

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)


[ 6.  6.  6.  6.]

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())


[ 3.  3.  3.  3.]

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())


[[ 2.  3.  4.]
 [ 5.  6.  7.]]

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())


Input:
[[ 1.  0.  0.  1.]]
Weights:
[[-0.79031324  0.64767152]
 [-0.78116518  0.61767405]
 [ 0.70150155  0.3006005 ]
 [-1.50426447 -0.61652637]]
Output:
[[-2.2945776   0.03114516]]

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())


[[-0.92653728 -0.69333982]] [[-0.92653728 -0.69333982]]
[[ 0.94992948 -0.49395561]] [[ 0.0233922  -1.18729544]]
[[-0.74896598  0.81623888]] [[-0.72557378 -0.37105656]]
[[ 0.94949746 -0.61281729]] [[ 0.22392368 -0.98387384]]
[[-0.88515854  0.49709058]] [[-0.66123486 -0.48678327]]

In [ ]: