斯坦福tensorflow教程-实例代码简单代码关于占位符 placeholder与feed_dictvariable 变量

简单代码

# -*- coding: utf-8 -*-
# @Author: yanqiang
# @Date:   2018-05-13 10:37:40
# @Last Modified by:   yanqiang
# @Last Modified time: 2018-05-13 11:41:55

import os


# 在tensorflow的log日志等级如下:
# - 0:显示所有日志(默认等级)
# - 1:显示info、warning和error日志
# - 2:显示warning和error信息
# - 3:显示error日志信息
# 保持默认日志等级时候,tensorflow执行会出现类似以下警告:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import numpy as np
import tensorflow as tf

# 例子1:简单创建 log writer
a = tf.constant(2, name='a')
b = tf.constant(3, name='b')
x = tf.add(a, b, name='add')
writer = tf.summary.FileWriter('./graphs/simple', tf.get_default_graph())
with tf.Session() as sess:
    # writer=tf.summary.FileWriter('./graphs',sess.graph)
    print(sess.run(x))
writer.close()

# 例子2:div的奇思妙用
a = tf.constant([2, 2], name='a')
b = tf.constant([[0, 1], [2, 3]], name='b')
with tf.Session() as sess:
    print(sess.run(tf.div(b, a)))  # 对应元素相除, 取商数
    print(sess.run(tf.divide(b, a)))  # 对应元素相除
    print(sess.run(tf.truediv(b, a)))  # 对应元素 相除
    # print(sess.run(tf.realdiv(b, a)))
    print(sess.run(tf.floordiv(b, a)))  # 结果向下取整, 但结果dtype与输入保持一致
    print(sess.run(tf.truncatediv(b, a)))  # 对应元素 截断除 取余
    print(sess.run(tf.floor_div(b, a)))

# 例子3:乘法
a = tf.constant([10, 20], name='a')
b = tf.constant([2, 3], name='b')
with tf.Session() as sess:
    print(sess.run(tf.multiply(a, b)))
    print(sess.run(tf.tensordot(a, b, 1)))

# 例子4:Python 基础数据类型
t_0 = 19
x = tf.zeros_like(t_0)
y = tf.ones_like(t_0)
print(x)
print(y)

t_1 = ['apple', 'peach', 'banana']
x = tf.zeros_like(t_1)                  # ==> ['' '' '']
# y = tf.ones_like(t_1)                           # ==> TypeError:

t_2 = [[True, False, False],
       [False, False, True],
       [False, True, False]]
x = tf.zeros_like(t_2)                  # ==> 3x3 tensor, all elements are False
y = tf.ones_like(t_2)                   # ==> 3x3 tensor, all elements are True

print(tf.int32.as_numpy_dtype())

# Example 5: printing your graph's definition
my_const = tf.constant([1.0, 2.0], name='my_const')
print(tf.get_default_graph().as_graph_def())

关于占位符 placeholder与feed_dict

# -*- coding: utf-8 -*-
# @Author: yanqiang
# @Date:   2018-05-14 23:01:30
# @Last Modified by:   yanqiang
# @Last Modified time: 2018-05-14 23:12:22

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf

# Example 1: feed_dict with placeholder

# a is a placeholder for a vector of 3 elements,type tf.float32
a = tf.placeholder(tf.float32, shape=[3])
b = tf.constant([5, 5, 5], tf.float32)

# use the placeholder as you would a constant
c = a + b  # short for tf.add(a,b)

writer = tf.summary.FileWriter('graphs/placeholders', tf.get_default_graph())
with tf.Session() as sess:
    # compute the value of c given the value if a is [1,2,3]
    print(sess.run(c, {a: [1, 2, 3]}))
writer.close()

# Example 2:feed_dict with variables
a = tf.add(2, 5)
b = tf.multiply(a, 3)
with tf.Session() as sess:
    print(sess.run(b))  # >> 21
    # compute the value of b given the value of a is 15
    print(sess.run(b, feed_dict={a: 15}))

variable 变量

""" Variable exmaples
Created by Chip Huyen (chiphuyen@cs.stanford.edu)
CS20: "TensorFlow for Deep Learning Research"
cs20.stanford.edu
Lecture 02
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

import numpy as np
import tensorflow as tf

# Example 1: creating variables
s = tf.Variable(2, name='scalar') 
m = tf.Variable([[0, 1], [2, 3]], name='matrix') 
W = tf.Variable(tf.zeros([784,10]), name='big_matrix')
V = tf.Variable(tf.truncated_normal([784, 10]), name='normal_matrix')

s = tf.get_variable('scalar', initializer=tf.constant(2)) 
m = tf.get_variable('matrix', initializer=tf.constant([[0, 1], [2, 3]]))
W = tf.get_variable('big_matrix', shape=(784, 10), initializer=tf.zeros_initializer())
V = tf.get_variable('normal_matrix', shape=(784, 10), initializer=tf.truncated_normal_initializer())

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(V.eval())

# Example 2: assigning values to variables
W = tf.Variable(10)
W.assign(100)
with tf.Session() as sess:
    sess.run(W.initializer)
    print(sess.run(W))                      # >> 10

W = tf.Variable(10)
assign_op = W.assign(100)
with tf.Session() as sess:
    sess.run(assign_op)
    print(W.eval())                         # >> 100

# create a variable whose original value is 2
a = tf.get_variable('scalar', initializer=tf.constant(2)) 
a_times_two = a.assign(a * 2)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer()) 
    sess.run(a_times_two)                   # >> 4
    sess.run(a_times_two)                   # >> 8
    sess.run(a_times_two)                   # >> 16

W = tf.Variable(10)
with tf.Session() as sess:
    sess.run(W.initializer)
    print(sess.run(W.assign_add(10)))       # >> 20
    print(sess.run(W.assign_sub(2)))        # >> 18

# Example 3: Each session has its own copy of variable
W = tf.Variable(10)
sess1 = tf.Session()
sess2 = tf.Session()
sess1.run(W.initializer)
sess2.run(W.initializer)
print(sess1.run(W.assign_add(10)))          # >> 20
print(sess2.run(W.assign_sub(2)))           # >> 8
print(sess1.run(W.assign_add(100)))         # >> 120
print(sess2.run(W.assign_sub(50)))          # >> -42
sess1.close()
sess2.close()

# Example 4: create a variable with the initial value depending on another variable
W = tf.Variable(tf.truncated_normal([700, 10]))
U = tf.Variable(W * 2)

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏C语言及其他语言

【每日一题】问题 1218: 排列

关注我们 题目描述 Ray又对数字的列产生了兴趣: 现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。 输入 ...

29480
来自专栏tkokof 的技术,小趣及杂念

数学小记

结果为 2n + 1, 考虑到任一奇数都可以表示成这种形式,所以使用以下构造方法即可立即得到上述的b和c:

12930
来自专栏数据结构与算法

HDU 3480 Division

Problem Description Little D is really interested in the theorem of sets recen...

27890
来自专栏数据结构与算法

cf1027F. Session in BSU(并查集 匈牙利)

$n$个人,每个人可以在第$a_i$天或第$b_i$,一天最多考一场试,问在最优的情况下,最晚什么时候结束

13410
来自专栏数据处理

proc-tabulate

12220
来自专栏云霄雨霁

字符串查找----查找算法的选择

30400
来自专栏数据结构与算法

agc027D - Modulo Matrix(构造 黑白染色)

构造一个$n * n$的矩阵,要求任意相邻的两个数$a,b$,使得$max(a,b) % min(a,b) \not = 0$

10130
来自专栏乐沙弥的世界

SQL, PL/SQL 之NUMBER数据类型

    NUMBER数据类型在Oracle中使用的较为广泛,可以存储零值,正负数,以及定长数,对于这个数据类型有个几个概念要搞清,否则容易搞混,下面给出具体描述...

10520
来自专栏ACM算法日常

年会Party(树形动态规划)- HDU 1520

There is going to be a party to celebrate the 80-th Anniversary of the Ural Stat...

9220
来自专栏机器学习入门

LWC 53:694. Number of Distinct Islands

LWC 53:694. Number of Distinct Islands 传送门:694. Number of Distinct Islands Probl...

26570

扫码关注云+社区

领取腾讯云代金券