使用张量流的线性回归非常缓慢



我正在尝试在tensorflow中实现一个简单的线性回归(目标是最终将其扩展到更高级的模型)。我当前的代码如下:

def linear_regression(data, labels):
    # Setup placeholders and variables
    num_datapoints = data.shape[0]
    num_features = data.shape[1]
    x = tf.placeholder(tf.float32, [None, num_features])
    y_ = tf.placeholder(tf.float32, [None])
    coeffs = tf.Variable(tf.random_normal(shape=[num_features, 1]))
    bias = tf.Variable(tf.random_normal(shape=[1]))
    # Prediction
    y = tf.matmul(x, coeffs) + bias
    # Cost function
    cost = tf.reduce_sum(tf.pow(y-y_, 2))/(2.*num_datapoints)

    # Optimizer
    NUM_STEPS = 500
    optimizer = tf.train.AdamOptimizer()
    train_step = optimizer.minimize(lasso_cost)
    # Fit the model
    init = tf.initialize_all_variables()
    cost_history = np.zeros(NUM_STEPS)
    sess = tf.Session()
    sess.run(init)
    for i in range(NUM_STEPS):
        if i % 100 == 0:
            print 'Step:', i
        for xi, yi in zip(data, labels):
            sess.run(train_step, feed_dict={x: np.expand_dims(xi, axis=0), 
                y_: np.expand_dims(yi, axis=0)})
            cost_history[i] = sess.run(lasso_cost, feed_dict={x: data,
                y_:labels})
    return sess.run(coeffs), cost_history

该代码起作用,并找到正确的系数。然而,它非常缓慢。在我的MacBook Pro上,对于一个具有1000个数据点和10个功能的数据集,仅运行几个训练时期就需要几分钟。由于我运行的是OSX,所以我没有GPU加速,这可能解释了速度慢的原因,但我认为它可能比这更快。我尝试过不同的优化器,但性能非常相似。

有什么明显的方法可以加快代码的速度吗?否则,感觉tensorflow对这些类型的问题几乎毫无用处。

它非常慢,因为您逐点训练网络,这需要NUM_STEPS * num_datapoints迭代(这会导致50万次循环)。

所有你真正需要训练你的网络是

for i in range(NUM_STEPS):
    sess.run(train_step, feed_dict={x: data, y_:labels})

这只需要几秒钟。

最新更新