2016-09-20 13 views
1

Новое в tensorflow, питона и NumPy (я предполагаю, что это все, что в данном примере)Как это TensorFlow образец фактически обновить веса, чтобы найти решение

В коде ниже я (почти) понять, что update_weights.run() в цикле вычисляет потерю и развивает новые веса. Я не вижу, как это на самом деле приводит к изменению веса.

Точки я застрял на комментируются # ЭТИМ ЧТО Я НЕ ПОНИМАЮ

Какова взаимосвязь между update_weights.run() и новыми значениями помещаются в массах? Или, может быть; как получится, когда после цикла вызывается weights.eval, что значения изменились?

Спасибо за любую помощь

#@test {"output": "ignore"} 

# Import tf 
import tensorflow as tf 

# Numpy is Num-Pie n dimensional arrays 
# https://en.wikipedia.org/wiki/NumPy 
import numpy as np 

# Plotting library 
# http://matplotlib.org/users/pyplot_tutorial.html 
import matplotlib.pyplot as plt 

# %matplotlib magic 
# http://ipython.readthedocs.io/en/stable/interactive/tutorial.html#magics-explained 
%matplotlib inline 

# Set up the data with a noisy linear relationship between X and Y. 
# Variable? 
num_examples = 5 
noise_factor = 1.5 
line_x_range = (-10,10) 

#Just variables in Python 
# np.linspace - Return evenly spaced numbers over a specified interval. 
X = np.array([ 
     np.linspace(line_x_range[0], line_x_range[1], num_examples), 
     np.linspace(line_x_range[0], line_x_range[1], num_examples) 
    ]) 

# Plot out the starting data 
# plt.figure(figsize=(4,4)) 
# plt.scatter(X[0], X[1]) 
# plt.show() 

# npm.random.randn - Return a sample (or samples) from the “standard normal” distribution. 
# Generate noise for x and y (2) 
noise = np.random.randn(2, num_examples) * noise_factor 

# plt.figure(figsize=(4,4)) 
# plt.scatter(noise[0],noise[1]) 
# plt.show() 

# += on an np.array 
X += noise 

# The 'Answer' polyfit to the noisy data 
answer_m, answer_b = np.polyfit(X[0], X[1], 1) 


# Destructuring Assignment - http://codeschool.org/python-additional-miscellany/ 
x, y = X 

# plt.figure(figsize=(4,4)) 
# plt.scatter(x, y) 
# plt.show() 

# np.array 
# for a in x 
# [(1., a) for a in [1,2,3]] => [(1.0, 1), (1.0, 2), (1.0, 3)] 
# numpy.ndarray.astype - http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html 
# Copy of the array, cast to a specified type. 
x_with_bias = np.array([(1., a) for a in x]).astype(np.float32) 

#Just variables in Python 
# The difference between our current outputs and the training outputs over time 
# Starts high and decreases 
losses = [] 
history = [] 
training_steps = 50 
learning_rate = 0.002 

# Start the session and give it a variable name sess 
with tf.Session() as sess: 
    # Set up all the tensors, variables, and operations. 
    # Creates a constant tensor 
    input = tf.constant(x_with_bias) 
    # Transpose the ndarray y of random float numbers 
    target = tf.constant(np.transpose([y]).astype(np.float32)) 
    # Start with random weights 
    weights = tf.Variable(tf.random_normal([2, 1], 0, 0.1)) 

    # Initialize variables ...?obscure? 
    tf.initialize_all_variables().run() 
    print('Initialization complete') 

    # tf.matmul - Matrix Multiplication 
    # What are yhat? Why this name? 
    yhat = tf.matmul(input, weights) 

    # tf.sub - Matrix Subtraction 
    yerror = tf.sub(yhat, target) 

    # tf.nn.l2_loss - Computes half the L2 norm of a tensor without the sqrt 
    # loss function? 
    loss = tf.nn.l2_loss(yerror) 

    # tf.train.GradientDescentOptimizer - Not sure how this is updating the weights tensor? 
    # What is it operating on? 
    update_weights = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) 

    # _ in Python is conventionally used for a throwaway variable 
    for step in range(training_steps): 
    # Repeatedly run the operations, updating the TensorFlow variable. 
    # THIS IS WHAT I DONT UNDERSTAND 
    update_weights.run() 
    losses.append(loss.eval()) 
    b, m = weights.eval() 
    history.append((b,m,step)) 

    # Training is done, get the final values for the graphs 
    betas = weights.eval() 
    yhat = yhat.eval() 

# Show the fit and the loss over time. 
# destructuring assignment 
fig, (ax1, ax2, ax3) = plt.subplots(1, 3) 

# Adjust whitespace between plots 
plt.subplots_adjust(wspace=.2) 

# Output size of the figure 
fig.set_size_inches(12, 4) 

ax1.set_title("Final Data Fit") 
ax1.axis('equal') 
ax1.axis([-15, 15, -15, 15]) 

# Scatter plot data x and y (pairs?) set with 60% opacity 
ax1.scatter(x, y, alpha=.6) 
# Scatter plot x and np.transpose(yhat)[0] (must be same length), in red, 50% transparency 
# these appear to be the x values mapped onto the 
ax1.scatter(x, np.transpose(yhat)[0], c="r", alpha=.5) 

# Add the line along the slope defined by betas (whatever that is) 
ax1.plot(line_x_range, [betas[0] + a * betas[1] for a in line_x_range], "g", alpha=0.6) 

# This polyfit coefficients are reversed in order vs the betas 
ax1.plot(line_x_range, [answer_m * a + answer_b for a in line_x_range], "r", alpha=0.3) 


ax2.set_title("Loss over Time") 

# Create a range of intefers from 0 to training_steps and plot the losses as a curve 
ax2.plot(range(0, training_steps), losses) 

ax2.set_ylabel("Loss") 
ax2.set_xlabel("Training steps") 

ax3.set_title("Slope over Time") 
ax3.axis('equal') 
ax3.axis([-15, 15, -15, 15]) 

for b, m, step in history: 
    ax3.plot(line_x_range, [b + a * m for a in line_x_range], "g", alpha=0.2) 

# This line seems to be superfluous removing it doesn't change the behaviour 
plt.show() 
+0

Без учета тензорного потока можно только догадываться, что обе они на самом деле являются одной и той же переменной. Вы отлаживали этот раздел? – Bort

+0

Нет, я еще не видел отладчика для тензорного потока, но это отличная идея! Вы бы посоветовали тензор? Как здесь: https://www.tensorflow.org/versions/r0.10/how_tos/summaries_and_tensorboard/index.html – stujo

+1

На мой взгляд, вы должны начать с использования matplotlib, как вы это делали до перехода на Tensorboard, что требует хорошего понимания внутреннего пути Tensorflow делать вещи. – jean

ответ

2

ИТАК update_weights() звонит минимизант на потери, которые вы определили, что ошибка между предсказанием и мишенью.

Что он будет делать, так это добавит небольшое количество к весам (насколько мало контролируется параметром learning_rate), чтобы уменьшить ваши потери и, следовательно, сделать ваши прогнозы «истинными».

Это то, что происходит, когда вы вызываете update_weights(), поэтому после вызова ваши веса изменились с небольшого значения, и если все пойдет по плану, ваше значение потери уменьшится.

Что вы хотите, следуйте эволюции вашей потери, а весы видят, например, если убыток действительно уменьшается (и ваш алгоритм работает), или веса сильно меняются или могут визуализировать их.

Вы можете получить много идей, визуализируя, как изменяется потеря. Вот почему вы должны увидеть полную историю эволюции параметров и потерь; Вот почему вы оцениваете их на каждом шагу.

Eval или запуск операция отличается, когда вы делаете это на минимайзере и параметры, когда вы делаете это на минимайзере будет применять минимизатор к весам, когда вы делаете это на весах это просто Оценивает их. Настоятельно рекомендую вам прочитать this website, где автор объясняет мне гораздо лучше, чем то, что происходит, и более подробно.

+0

Спасибо за отличный ответ Jean, это очень полезно, однако бит, который мне не хватает, - это как update_weights() даже получить ссылку на «вес», чтобы изменить их? Я не вижу, чтобы это передавалось как параметр, так или иначе выработано через функцию потерь, yerror, цепочку вещей (называются тензорами?)? – stujo

+1

Идея Tensorflow заключается в использовании вычислительного графика. Когда вы запустите некоторую строку кода, например W = tf.Variable() или y = tf.matmul (W, x), на этом графике создаются узлы. Затем, когда вы запускаете минимизатор, Tensorflow каким-то образом проходит через весь график, чтобы backpropagate затраты на каждую переменную, которую вы определили и которая связана с ней (стоимость). – jean

+0

Это объясняется в значительной степени в этой статье: [link] (http://download.tensorflow.org/paper/whitepaper2015.pdf). – jean