use*_*216 1 python performance regression 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
Run Code Online (Sandbox Code Playgroud)
该代码起作用,并找到正确的系数。但是,它非常慢。在我的MacBook Pro上,仅花几分钟时间即可为包含1000个数据点和10个功能的数据集运行几个训练时期。由于我正在运行OSX,因此我没有GPU加速功能,这可以解释某些缓慢现象,但是我认为它可能比这更快。我尝试了不同的优化程序,但是性能非常相似。
有什么明显的方法可以加快此代码的速度吗?否则,感觉tensorflow对于这些类型的问题几乎没有用。
这太慢了,因为您逐点训练网络,这需要NUM_STEPS * num_datapoints迭代(这导致了五十万个循环)。
您训练网络所需的全部是
for i in range(NUM_STEPS):
sess.run(train_step, feed_dict={x: data, y_:labels})
Run Code Online (Sandbox Code Playgroud)
这只需要几秒钟。