gpt4 book ai didi

javascript - 在这个简单的神经网络示例中,为什么 Tensorflow 比 convnetjs 慢 100 倍?

转载 作者:行者123 更新时间:2023-12-03 00:24:17 25 4
gpt4 key购买 nike

我已经使用 convnetjs 一年了,现在我想转向更强大、更快速的库。我认为 Tensorflow 会比 JS 库快几个数量级,因此我为这两个库编写了一个简单的神经网络并做了一些测试。它是一种 3-5-5-1 神经网络,使用 SGD 和 RELU 层在一个示例上训练一定数量的 epoch。

tensorflow 代码:

import tensorflow as tf
import numpy
import time

NUM_CORES = 1 # Choose how many cores to use.
sess = tf.Session(config=tf.ConfigProto(inter_op_parallelism_threads=NUM_CORES, intra_op_parallelism_threads=NUM_CORES))

# Parameters
learning_rate = 0.001
training_epochs = 1000
batch_size = 1

# Network Parameters
n_input = 3 # Data input
n_hidden_1 = 5 # 1st layer num features
n_hidden_2 = 5 # 2nd layer num features
n_output = 1 # Data output

# tf Graph input
x = tf.placeholder("float", [None, n_input], "a")
y = tf.placeholder("float", [None, n_output], "b")

# Create model
def multilayer_perceptron(_X, _weights, _biases):
layer_1 = tf.nn.relu(tf.add(tf.matmul(_X, _weights['h1']), _biases['b1'])) #Hidden layer with RELU activation
layer_2 = tf.nn.relu(tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2'])) #Hidden layer with RELU activation
return tf.matmul(layer_2, _weights['out']) + _biases['out']

# Store layers weight & bias
weights = {
'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_hidden_2, n_output]))
}
biases = {
'b1': tf.Variable(tf.random_normal([n_hidden_1])),
'b2': tf.Variable(tf.random_normal([n_hidden_2])),
'out': tf.Variable(tf.random_normal([n_output]))
}

# Construct model
pred = multilayer_perceptron(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_sum(tf.nn.l2_loss(pred-y)) / batch_size # L2 loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost) # Adam Optimizer

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
sess.run(init)

# Training Data
train_X = numpy.asarray([[0.1,0.2,0.3]])
train_Y = numpy.asarray([[0.5]])

# Training cycle
start = time.clock()
for epoch in range(training_epochs):
# Fit training using batch data
sess.run(optimizer, feed_dict={x: train_X, y: train_Y})
end = time.clock()

print end - start #2.5 seconds -> 400 epochs per second
print "Optimization Finished!"

JS代码:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8" />
<title>Regression example convnetjs</title>
<script src="http://cs.stanford.edu/people/karpathy/convnetjs/build/convnet.js"></script>
<script src="http://cs.stanford.edu/people/karpathy/convnetjs/build/util.js"></script>
<script>
var layer_defs, net, trainer;
function start() {
layer_defs = [];
layer_defs.push({ type: 'input', out_sx: 1, out_sy: 1, out_depth: 3 });
layer_defs.push({ type: 'fc', num_neurons: 5, activation: 'relu' });
layer_defs.push({ type: 'fc', num_neurons: 5, activation: 'relu' });
layer_defs.push({ type: 'regression', num_neurons: 1 });
net = new convnetjs.Net();
net.makeLayers(layer_defs);
trainer = new convnetjs.SGDTrainer(net, { learning_rate: 0.001, method: 'sgd', batch_size: 1, l2_decay: 0.001, l1_decay: 0.001 });

var start = performance.now();
for(var i = 0; i < 100000; i++) {
var x = new convnetjs.Vol([0.1, 0.2, 0.3]);
trainer.train(x, [0.5]);
}
var end = performance.now();
console.log(end-start); //3 seconds -> 33333 epochs per second
var predicted_values = net.forward(x);
console.log(predicted_values.w[0]);
}

</script>
</head>
<body>
<button onclick="start()">Start</button>
</body>
</html>

结果是,Convnetjs 在 3 秒内训练了 100,000 个 epoch,而 Tensorflow 在 2.5 秒内训练了 1000 个 epoch。这是预期的吗?

最佳答案

原因可能有很多:

  • 数据输入量很小,大部分时间都花在python和C++核心之间的转换上,而JS只是一种语言。

  • 您在 Tensorflow 中仅使用一个核心,而 JS 可能会利用多个核心

  • JS 库能够创建高度优化的 JIT 版本的程序。

当分布式版本公开时,Tensorflow 的真正好处才会显现。那么在多个节点上运行大型网络的能力将比单个节点的速度更重要。

关于javascript - 在这个简单的神经网络示例中,为什么 Tensorflow 比 convnetjs 慢 100 倍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34479872/

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