TensorFlow 基础(一)

1 . 两种使用 Session 的方法:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf


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

# method1 需要 close
sess = tf.Session()
result = sess.run(product)
print(result)
sess.close() 

# method2  不需要 close
with tf.Session() as sess:
    result2 = sess.run(product)
    print(result2)

2 . 使用 placeholder 传入值

import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)


output = tf.multiply(input1, input2)


with tf.Session() as sess:
    print(sess.run(output, feed_dict = {input1:[[2,3]], input2:[[3], [4]]}))

3 . 变量的使用 Variable

import os
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


state = tf.Variable(3, name='counter')
print(state.name)
one = tf.constant(1)


new_value = tf.add(state, one)
update = tf.assign(state, new_value)


init = tf.global_variables_initializer()


with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容