Tensorflow中的执行时间比Numpy中的执行时间长

时间:2019-06-10 00:46:49

标签: python numpy tensorflow gradient-descent

我正在从Geron的动手机器学习中使用Tensorflow和Numpy复制一个梯度下降示例。这很奇怪,但是即使启用了GPU,Numpy似乎也比Tensorflow快5至6倍。

我想知道设置Tensorflow时我做错了什么。这两个代码如下:

第一个张量流。投放时间:aprox。 8秒

from sklearn.datasets import fetch_california_housing
dados = fetch_california_housing()
nlins, ncols = dados['data'].shape

minimos = np.min(dados['data'],axis=0)
maximos = np.max(dados['data'],axis=0)
intervalo = maximos - minimos
dados_n = (dados['data'] - minimos) / intervalo

import numpy as np
uns = np.ones(nlins).reshape(-1,1)
x = np.concatenate([uns, dados_n], axis=1)
y = dados['target'].reshape(-1,1)

eta = 0.1 
epocas = 10000 

import tensorflow as tf
X = tf.constant(x, dtype=tf.float32, name='X')
Y = tf.constant(y, dtype=tf.float32, name='Y')
beta = tf.Variable(tf.random_uniform([ncols + 1, 1],
                                     -1.0, 1.0,seed=42), name='beta')
Yhat = tf.matmul(X, beta, name='Yhat')
erro = Yhat - Y
mse = tf.reduce_mean(tf.square(erro), name='mse')
gradiente = 2/nlins * tf.matmul(tf.transpose(X), erro)
novo_beta = tf.assign(beta, beta - eta * gradiente)

init = tf.global_variables_initializer()

from time import time

sess = tf.InteractiveSession()
sess.run(init)
inicio = time()
for i in range(epocas):
    sess.run(novo_beta)
fim = time()
result = mse.eval()
sess.close()

tempo = fim - inicio
print("Tempo = %.2f" % tempo)
print("MSE = %.2f" % result) # 0.57

现在numpy。播放时间:1.50秒

epocas = 10000
eta = 0.1

import numpy as np
np.set_printoptions(precision=3)

from sklearn.datasets import fetch_california_housing
dados = fetch_california_housing()
nlins, ncols = dados['data'].shape
uns = np.ones(nlins).reshape(-1,1)

minimos = np.min(dados['data'],axis=0)
maximos = np.max(dados['data'],axis=0)
intervalo = maximos - minimos
dados_n = (dados['data'] - minimos)/intervalo

x = np.concatenate([uns,dados_n], axis=1)
y = dados['target'].reshape(-1,1)

np.random.seed(42)
beta = np.random.uniform(low=-1, high=1, size=9).reshape(-1,1)

from time import time
inicio = time()
for i in range(epocas):
    mse = np.mean(np.square(x.dot(beta)-y))
    gradiente = 2/nlins * x.T.dot(x.dot(beta)-y)
    beta = beta - eta * gradiente
fim = time()
tempo = fim - inicio
print("tempo = %.2f" % tempo) 
print("mse = %.2f" % mse) 

我在Tensorflow实施中做错了什么

0 个答案:

没有答案