代码之家  ›  专栏  ›  技术社区  ›  goofcode

支持向量机张量流实现

  •  2
  • goofcode  · 技术社区  · 7 年前

    我一直在听吴教授的讲座,并试图用tensorflow在我的jupyter笔记本上实现支持向量机。然而,我的模型似乎没有正确收敛。

    Scattered plot after 5000 steps of training

    我想我有错误的损失函数,这可能会不适合我的模型。

    tf.reset_default_graph()
    
    #training hyper parameters
    
    learning_rate = 0.000001
    C = 20
    gamma = 50
    
    X = tf.placeholder(tf.float32, shape=(None,2))
    Y = tf.placeholder(tf.float32, shape=(None,1))
    landmark = tf.placeholder(tf.float32, shape=(None,2))
    
    W = tf.Variable(np.random.random((num_data)),dtype=tf.float32)
    B = tf.Variable(np.random.random((1)),dtype=tf.float32)
    
    batch_size = tf.shape(X)[0]
    
    #RBF Kernel
    tile = tf.tile(X, (1,num_data))
    diff = tf.reshape( tile, (-1, num_data, 2)) - landmark
    tile_shape = tf.shape(diff)
    sq_diff = tf.square(diff)
    sq_dist = tf.reduce_sum(sq_diff, axis=2)
    F = tf.exp(tf.negative(sq_dist * gamma))
    
    WF = tf.reduce_sum(W * F, axis=1) + B
    
    condition = tf.greater_equal(WF, 0)
    H = tf.where(condition,  tf.ones_like(WF),tf.zeros_like(WF))
    
    ERROR_LOSS = C * tf.reduce_sum(Y * tf.maximum(0.,1-WF) + (1-Y) * tf.maximum(0.,1+WF))
    WEIGHT_LOSS = tf.reduce_sum(tf.square(W))/2
    
    TOTAL_LOSS = ERROR_LOSS + WEIGHT_LOSS
    
    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    train = optimizer.minimize(TOTAL_LOSS)
    

    我使用高斯核并将整个训练集作为里程碑。

    Loss function on the lecture

    我很确定我错过了什么。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Tucker Leavitt    7 年前

    batch_size^2 条目,而您的张量 WF (batch_size, 2) 其思想是为数据集中的每对(x\u i,x\u j)计算K(x\u i,x\u j),然后使用这些核值作为支持向量机的输入。

    Andrew Ng's lecture notes 以支持向量机为参考;在第20页,他导出了最终的优化问题。您需要更换内部产品 <x_i, x_j> 使用内核函数。

    我建议从线性核开始,而不是径向基函数,并将代码与开箱即用的支持向量机实现进行比较,如 sklearn's 。这将帮助您确保优化代码正常工作。