gpt4 book ai didi

machine-learning - SVM tensorflow 实现

转载 作者:行者123 更新时间:2023-11-30 08:41:00 25 4
gpt4 key购买 nike

我一直在关注Ng教授的讲座,并尝试使用tensorflow在我的jupyter笔记本上实现SVM。但是,我的模型似乎没有正确收敛。

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

我很确定我错过了一些东西。

最佳答案

请注意,内核矩阵应具有 batch_size^2条目,而你的张量 WF有形状(batch_size, 2) 。这个想法是计算数据集中每对 (x_i, x_j) 的 K(x_i, x_j),然后使用这些内核值作为 SVM 的输入。

我正在使用Andrew Ng's lecture notes以 SVM 为引用;在第 20 页,他推导出了最终的优化问题。您需要替换内积 <x_i, x_j>与你的内核函数。

我建议从线性内核而不是 RBF 开始,并将您的代码与开箱即用的 SVM 实现(如 sklearn's)进行比较。 。这将帮助您确保优化代码正常工作。

最后一点:虽然应该可以使用梯度下降来训练 SVM,但在实践中它们几乎从未以这种方式进行训练。 SVM 优化问题可以通过二次规划来解决,大多数训练 SVM 的方法都利用了这一点。

关于machine-learning - SVM tensorflow 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45317361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com