文章目录
tensorflow整体理解
tensorflow框架
我们应该了解深度学习的大概框架,forward pass 计算预测值,backward pass计算误差,误差引导参数更新,重复上述操作。
tensorflow它是专门针对深度学习开发的,它是先把网络搭建起来,一层一层把网络搭建起来,前向传播把网络堆砌好之后,这个网络还包含了对反向误差的处理,反向误差在这个网络里面已经内建好了,我们只需要告诉网络采取什么方法和以什么为目标来反向传播,这个就是build graph的过程,我们连如何更新参数都不需要关心,tensorflow全帮你做了。
再次所以一遍你在tensorflow需要做什么:前向传播把网络堆砌好,告诉网络采取什么方法和以什么为目标来反向传播。对,你只需要堆积木。
tensorflow训练
网络搭建好之后,那就是训练了。想象以下已经给你一台机器了,你作为一个工人你所要做的就是放数据和看结果,在tensorflow里不能直接看,需要使用session这个工具去放数据去看结果。
tensorflow基本操作对象
tensorflow操作对象都是tensor,所以我们需要把所有需要用到的变量转为tensorflow识别的tensor
常量:就是已经确定的对象
# define constant for GPU compute as tf.float32
x = tf.constant(1,dtype= tf.float32)
可训练变量:就是需要训练的变量对象
# define a trainable varible
y = tf.Variable(2,dtype=tf.float32)
不可可训练变量:就是不需要训练的变量对象,GAN里有用
# define a untrainable varible
z = tf.Variable(3,dtype=tf.float32,trainable=False)
变化的常量:分批训练,miniBatch是常量,但是它是需要变化的,可以成为块变量,使用“占位符”更能代表他的含义。
# 定义一个数据类型为 tf.float32、“长”未知、“宽”为 2 的矩阵 Placeholder
x = tf.placeholder(tf.float32, [None, 2])
训练操作工具:session()
# 定义一个数据类型为 tf.float32、“长”未知、“宽”为 2 的矩阵 Placeholder
x = tf.placeholder(tf.float32, [None, 2])
# 定义一个 numpy 数组:[ [ 1 2 ], [ 3 4 ], [ 5 6 ] ]
x_data = np.array([[1, 2], [3, 4], [5, 6]])
# 定义 x + 1 对应的 Tensor
z = x + 1
# 利用 Session 及其 feed_dict 参数、将 y 的值赋予给 x、同时输出 z 的值
print(tf.Session().run(z, feed_dict={x: x_data})) # 将会输出 [ [ 2 3 ], [ 4 5 ], [ 6 7 ]
tensorflow实现SVM:
#%%
# =============================================================================
# 1. build graph: variables and operations(forward pass and backword pass)
# 2. train : feed data and train it
# =============================================================================
class TFLinearSVM(ClassifierBase):
def __init__(self):
super(TFLinearSVM, self).__init__()
self._w = None
self._b = None
# 使用 self._sess 属性来存储一个 Session 以方便调用
self._sess = tf.Session()
def fit(self, x, y, sample_weight=None, lr=0.001, epoch=10**4, tol=1e-3):
# 将 sample_weight(样本权重)转换为 constant Tensor
if sample_weight is None:
sample_weight = tf.constant(np.ones(len(y)), dtype=tf.float32, name="sample_weight")
else:
sample_weight = tf.constant(np.array(sample_weight)*len(y), dtype=tf.float32, name="sample_weight")
# 将输入数据转换为 constant Tensor
x, y = tf.constant(x, dtype=tf.float32), tf.constant(y, dtype=tf.float32)
# 将需要训练的 w、b 定义为可训练 Variable
self._w = tf.Variable(np.zeros(x.shape[1]), dtype=tf.float32, name="w")
self._b = tf.Variable(0., dtype=tf.float32, name="b")
# 调用相应方法获得当前模型预测值
y_pred = self.predict(x, True, False)
# 利用相应函数计算出总损失:
# cost = ∑_(i=1)^N max(1-y_i⋅(w⋅x_i+b),0)+ 0.5 * ‖w‖^2
cost = tf.reduce_sum(tf.maximum(1-y*y_pred,0)*sample_weight) + tf.nn.l2_loss(self._w)
# 利用 Tensorflow 封装好的优化器定义“更新参数”步骤
# 该步骤会调用相应算法、以减少上述总损失为目的来进行参数的更新
train_step = tf.train.AdamOptimizer(learning_rate=lr).minimize(cost)
#
self._sess.run(tf.global_variables_initializer())
#
for _ in range(epoch):
if self._sess.run([cost, train_step])[0] <0:
break
def predict(self, x, get_raw_results=False, out_of_sess = True):
# 利用 reduce_sum 方法算出预测向量
rs = tf.reduce_sum(self._w * x, axis=1) + self._b
if not get_raw_results:
rs = tf.sign(rs)
# 如果 out_of_sess 参数为 True、就要利用 Session 把具体数值算出来
if out_of_sess:
rs = self._sess.run(rs)
return rs