Tensorflow学习:Session会话控制

本文内容:

  1. 体会tensorflow.matmul(x,y)与numpy.dot(x,y)的内容
  2. with tf.Session()的自动关闭功能(即with语句功能)
# -*- coding: utf-8 -*-
"""
Created on Wed May  3 09:18:43 2017
E-mail: [email protected]
@author: DidiLv
"""

import tensorflow as tf
import numpy as np
#### creat the matrix
# matrix1 = [3,3]; matix2 = [2,2]'

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

product1_tf = tf.matmul(matrix1, matrix2) # matrix multiply: np.dot(m1,m2)
product2_tf = tf.matmul(matrix2, matrix1)

product1_np = np.dot(matrix1, matrix2)
product2_np = np.dot(matrix2, matrix1)

## method1
sess = tf.Session()

result1_tf = sess.run(product1_tf)
result2_tf = sess.run(product2_tf)

result1_np = sess.run(product1_np)
result2_np = sess.run(product2_np)

sess.close()
print("The tensorflow product m1xm2 is:",result1_tf)
print("The tensorflow product m2xm1 is:",result2_tf)
print("The tensorflow product m1xm2 is:",result1_np)
print("The tensorflow product m2xm1 is:",result2_np)

## method2 
with tf.Session() as sess:
    result1_tf = sess.run(product1_tf)
    result2_tf = sess.run(product2_tf)

    result1_np = sess.run(product1_np)
    result2_np = sess.run(product2_np)

print("The tensorflow product m1xm2 is:",result1_tf)
print("The tensorflow product m2xm1 is:",result2_tf)
print("The tensorflow product m1xm2 is:",result1_np)
print("The tensorflow product m2xm1 is:",result2_np)

你可能感兴趣的:(机器学习,Tensorflow)