import tensorflow as tf
# https://www.lfd.uci.edu/~gohlke/pythonlibs/#xgboost
tf.__version__
'1.10.0'
创建变量
a = 3
# 创建一个变量
w = tf.Variable([[0.5,1.0]])
x = tf.Variable([[2.0],[1.0]])
y = tf.matmul(w, x)
#全局变量初始化,创建变量时一定要初始化全局变量,创建常量时可以不进行初始化
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)#除了赋值操作,其他的操作都需要run才能生效。
print (y.eval())#等价于print (sess.run(y))
[[2.]]
tensorflow很多操作跟numpy有些类似的
tf.zeros([3, 4], int32) ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
tf.zeros_like(tensor) ==> [[0, 0, 0], [0, 0, 0]]
tf.ones([2, 3], int32) ==> [[1, 1, 1], [1, 1, 1]]
tf.ones_like(tensor) ==> [[1, 1, 1], [1, 1, 1]]
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.] [-1. -1. -1.]]
tf.linspace(10.0, 12.0, 3, name=“linspace”) => [ 10.0 11.0 12.0]
tf.range(start, limit, delta) ==> [3, 6, 9, 12, 15]
创建常量
#生成的值服从具有指定平均值和标准偏差的正态分布
norm = tf.random_normal([2, 3], mean=-1, stddev=4)
# 洗牌
c = tf.constant([[1, 2], [3, 4], [5, 6]])#常量可以直接进行定义
shuff = tf.random_shuffle(c)
# 每一次执行结果都会不同
sess = tf.Session()
print (sess.run(norm))
print (sess.run(shuff))
[[-5.58110332 0.84881377 7.51961231]
[ 3.27404118 -7.22483826 7.70631599]]
[[5 6]
[1 2]
[3 4]]
加减及赋值操作
state = tf.Variable(0)
new_value = tf.add(state, tf.constant(1))
update = tf.assign(state, new_value)#将new_value赋给state
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(state))
for _ in range(3):
sess.run(update)
print(sess.run(state))
0
1
2
3
np转化为tensor
import numpy as np
a = np.zeros((3,3))
ta = tf.convert_to_tensor(a)
with tf.Session() as sess:
print(sess.run(ta))
[[ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0.]]
其他运算
a = tf.constant(5.0)
b = tf.constant(10.0)
x = tf.add(a, b, name="add")
y = tf.div(a, b, name="divide")
with tf.Session() as sess:
print("a =", sess.run(a))
print("b =", sess.run(b))
print("a + b =", sess.run(x))
print("a/b =", sess.run(y))
a = 5.0
b = 10.0
a + b = 15.0
a/b = 0.5
设置容器
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:[7.], input2:[2.]}))
[array([ 14.], dtype=float32)]