# Tensorflow 基础构架

```# coding:utf-8
import tensorflow as tf
import numpy as np

x_data = np.random.rand(100).astype(np.float32) # 生成100个随机数，类型是float32
y_data = x_data*0.1+0.3
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0)) # tf.Variable是用来生成tf变量,这里就是生成一个[-1,1]数
biases = tf.Variable(tf.zeros([1])) # zeros可以生成一个0

y = Weights*x_data+biases # 针对每个x算出y值

loss = tf.reduce_mean(tf.square(y-y_data)) # 计算loss 平方求平均

train = optimizer.minimize(loss) #　训练，让loss最小
init = tf.initialize_all_variables() # 初始化所有的变量
sess = tf.Session() # 会话，贼重要
sess.run(init) # 啥也得run才可以

print sess.run(Weights)

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

## 会话Session

session是个执行命令的东西，用来执行tf图上的某个小的功能。就是啥也要用sess.run一下啦。这里演示一个简单的矩阵乘法：

```# coding:utf-8
import tensorflow as tf

matrix1 = tf.constant([[3,3]])
matrix2 = tf.constant([[2],
[2]])
product = tf.matmul(matrix1,matrix2)  # matrix multiply np.dot(m1,m2)```

```sess = tf.Session()
result = sess.run(product)
print result
sess.close()```

```with tf.Session() as sess: # 自动关
result2 = sess.run(product)
print result2```

## 变量Variable

```state = tf.Variable(0,name='counter')
one = tf.constant(1)
update = tf.assign(state,new_value) # 更新state的值

init = tf.initialize_all_variables() # 必须初始化

with tf.Session() as sess:
sess.run(init)
for _ in range(3): # 更新３次
sess.run(update)
print sess.run(state)```

这个方法输出１，２，３三个数。这可以看出，sess.run就是运行了一下update获得这个值。

## placeholder

placeholder的作用就是先给数据占个位置，在需要的时候再传入。

```# coding:utf8
import tensorflow as tf
import numpy as np

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.]})) # placeholder和feed_dict是绑定的```

# 建造神经网络

```# coding:utf8
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

layer_name = 'layer%s'% n_layer
with tf.name_scope(layer_name): # 意思是这个with里的元素被包括在scope里
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size,out_size]),name='W') # 就是建造一个数组，[行,列]
tf.histogram_summary(layer_name+'/weights',Weights) # 让weights
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1,out_size]) + 0.1,name='b')
tf.histogram_summary(layer_name+'/biases',biases)
with tf.name_scope('Wx'):
Wx_plus_b=tf.matmul(inputs,Weights) + biases # 计算一波
if activation_function is None: # 如果不指定激励函数
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b) # 如果指定了激励函数
tf.histogram_summary(layer_name+'/outputs',outputs)
return outputs

x_data = np.linspace(-1,1,300)[:,np.newaxis] # 这个能生成300个数，后面中括号可以让它变成竖着的
noise = np.random.normal(0,0.05,x_data.shape) # 生成噪声点，这里是个正太分布，均值是0方差是0.05，和x_data一样的格式
y_data = np.square(x_data)-0.5+noise # 计算y

with tf.name_scope('inputs'):
xs = tf.placeholder(tf.float32,[None,1],name='x_input')
ys = tf.placeholder(tf.float32,[None,1],name='y_input')

with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-predition),reduction_indices=[1]))
tf.scalar_summary('loss',loss)
with tf.name_scope('train'):

init = tf.initialize_all_variables()
sess = tf.Session()
merged = tf.merge_all_summaries()
writer = tf.train.SummaryWriter("logs/",sess.graph) # 将所有的图画到log里
sess.run(init)

fig = plt.figure() # 用这个画图
ax.scatter(x_data,y_data) # 点的编号
plt.ion() # 不用停顿
plt.show() #　输出图片

for i in range(1000):
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i%50 == 0:
result = sess.run(merged,feed_dict={xs:x_data,ys:y_data})
try:
ax.lines.remove(lines[0]) # 去除上次的线
except Exception:
pass
#print sess.run(loss,feed_dict={xs:x_data,ys:y_data})
predition_value = sess.run(predition,feed_dict={xs:x_data}) # 预测值
lines = ax.plot(x_data,predition_value,'r-',lw=5) # 用红色，宽度为５的曲线的形式画出来预测曲线
plt.pause(0.1)```

67 篇文章35 人订阅

0 条评论

## 相关文章

3425

### Metal入门教程（六）边界检测

Metal入门教程（一）图片绘制 Metal入门教程（二）三维变换 Metal入门教程（三）摄像头采集渲染 Metal入门教程（四）灰度计算 Metal入门教程...

2999

4725

1630

### 【Scikit-Learn 中文文档】双聚类 - 无监督学习 - 用户指南 | ApacheCN

2.4. 双聚类 Biclustering 可以使用 sklearn.cluster.bicluster 模块。 Biclustering 算法对数据矩阵的...

3609

2869

2137

27110

4275

642