# tensorflow简介

2017-02-23

tensorflow简介：tensorflow分为构建模型和训练两部分，构建模型通常会用到Tensor，variable,placeholder，而训练阶段会用到Session。

tensorflow简介：tensorflow分为构建模型和训练两部分，构建模型通常会用到Tensor，variable,placeholder，而训练阶段会用到Session。

```import tesorflow as tf
import numpy as np

# create data
x_data = np.random.rand(100).astype(np.float32) # 随机生成100个数据
y_data = x_data*0.1 + 0.3

# create tensorflow struct start
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))  #生成一维向量
biases = tf.Variable(tf.zeros([1]))

y = Weights*x_data + biases

#计算损失函数
loss = tf.reduce_mean(tf.square(y - y_data))
train = optimizer.minimize(loss)

init = tf.initialize_all_variable()
# create tensorflow struct end

with tf.Session() as sess:
sess.run(init)
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(Weights), sess.run(biases))```

```import tensorflow as tf

matrix1 = tf.constant([3, 3])  # 一行两列的矩阵
matrix2 = tf.constant([[2],
[2]])   # 两行一列的矩阵

# method1
sess = tf.Session()
# 两个矩阵相乘
result1 = tf.matmul(matrix1, matrix2)
print(sess.run(result1))
sess.close()

# method2
with tf.Session() as sess:
result2 = tf.matmul(matrix1, matrix2)
print(sess.run(result2))```

session会话，抽象模型的实现者，代码多处会用到它，原因在于，模型是抽象的，只有实现了模型之后，才能够得到具体的值。同样的参数训练、预测，甚至变量的实际查询，都需要用到session。

```import tensorflow as tf

state = tf.Variable(0, name=&#39; counter&#39;)  # 计算器
one = tf.constant(1)   # 常数为1
# 执行new_value = state + one
# 将new_value赋值给state
updata = tf.assign(state, new_value)
# 初始化所有变量
init = tf.initialize_all_variable()
with tf.Session() as sess:
sess.run(init)
# 循环3次
for i in range(3):
sess.run(updata)
# sess指针需要在state上run一下才可以得到结果
print(sess.run(state))```

Variable需要在session之前初始化才可以在session中被使用。

```import tensorflow as tf

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

# 两个数相乘
output = tf.mul(input1, input2)

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

```import tensoflow as tf

Weights = tf.Variable(tf.random_normal([in_size, out_size]))  #矩阵一般习惯首字母大写
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activetion_funtion is None:
outputs = Wx_plus_b
else:
outputs = activetion_funtion(Wx_plus_b)
return outputs```

activation_function=None代表线性函数。