# 简单代码

```# -*- coding: utf-8 -*-
# @Author: yanqiang
# @Date:   2018-05-13 10:37:40

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

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
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_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(sess2.run(W.assign_sub(2)))           # >> 8
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 条评论

## 相关文章

29480

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

12220

30400

10130

### SQL, PL/SQL 之NUMBER数据类型

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

10520

### 年会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