<jupyter_start><jupyter_text>Down the rabbit hole with Tensorflow![img](https://lh3.googleusercontent.com/I1Dpp7I9RZIGl0rVMlPfnhfl-bkl_2uDHZwVC87BWmqtPaAs1irMWOdJxTmTEQJB-VGfLryCyHxqvyNchVIVLL-vqGrF3Q=s688)In this seminar, we're going to play with [Tensorflow](https://www.tensorflow.org/) and see how it helps you build deep learning models.If you're running this notebook outside the course environment, you'll need to install tensorflow:* `pip install tensorflow` should install cpu-only TF on Linux & Mac OS* If you want GPU support from offset, see [TF install page](https://www.tensorflow.org/install/)<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import tensorflow as tf

# session is main tensorflow object. You ask session to compute stuff for you.
sess = tf.InteractiveSession()<jupyter_output><empty_output><jupyter_text>Warming upFor starters, let's implement a python function that computes the sum of squares of numbers from 0 to N-1.* Use numpy or python* An array of numbers 0 to N - numpy.arange(N)<jupyter_code>def sum_squares(N):
    return sum(i*i for i in range(N))
# https://codereview.stackexchange.com/questions/58460/sum-of-squares-square-of-sum-difference
# https://trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm
def sum_squares_O1(n):
    return n*(n+1)*(2*n+1)/6
%%time
sum_squares(10**8)
%%time
sum_squares_O1(10**8)<jupyter_output>CPU times: user 8 µs, sys: 1 µs, total: 9 µs
Wall time: 11.9 µs<jupyter_text>__Same with tensorflow__<jupyter_code># "i will insert N here later"
N = tf.placeholder('int64', name="input_to_your_function")

# a recipe on how to produce {sum of squares of arange of N} given N
result = tf.reduce_sum((tf.range(N)**2))
%%time

# dear session, compute the result please. Here's your N.
print(sess.run(result, {N: 10**8}))

# hint: run it several times to let tensorflow "warm up"<jupyter_output><empty_output><jupyter_text>How it works: computation graphs1. create placeholders for future inputs;2. define symbolic graph: a recipe for mathematical transformation of those placeholders;3. compute outputs of your graph with particular values for each placeholder  * ```sess.run(outputs, {placeholder1:value1, placeholder2:value2})```  * OR output.eval({placeholder:value}) Still confused? We gonna fix that. __Placeholders and constants__<jupyter_code># placeholder that can be arbitrary float32 scalar, vertor, matrix, etc.
arbitrary_input = tf.placeholder('float32')

# input vector of arbitrary length
input_vector = tf.placeholder('float32',shape=(None,))

# input vector that _must_ have 10 elements and integer type
fixed_vector = tf.placeholder('int32',shape=(10,))

# you can generally use None whenever you don't need a specific shape
input1 = tf.placeholder('float64',shape=(None, 100, None))
input2 = tf.placeholder('int32',shape=(None, None, 3, 224, 224))<jupyter_output><empty_output><jupyter_text>You can create new __tensors__ with arbitrary operations on placeholders, constants and other tensors.* tf.reduce_sum(tf.arange(N)\**2) are 3 sequential transformations of placeholder N* there's a tensorflow symbolic version for every numpy function  * `a + b, a / b, a ** b, ...` behave just like in numpy  * np.zeros -> tf.zeros  * np.sin -> tf.sin  * np.mean -> tf.reduce_mean  * np.arange -> tf.range  There are tons of other stuff in tensorflow, see the [docs](https://www.tensorflow.org/api_docs/python) or learn as you go with __shift+tab__.<jupyter_code># elementwise multiplication
double_the_vector = input_vector * 2

# elementwise cosine
elementwise_cosine = tf.cos(input_vector)

# elementwise difference between squared vector and it's means - with some random salt
vector_squares = input_vector ** 2 - tf.reduce_mean(input_vector) + tf.random_normal(tf.shape(input_vector))

! wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
! unzip ngrok-stable-linux-amd64.zip
LOG_DIR = '/tmp/log'
# summary_writer = tf.train.FileWriter(LOG_DIR, sess.graph_def)
get_ipython().system_raw(
    'tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'
    .format(LOG_DIR)
)
get_ipython().system_raw('./ngrok http 6006 &')
! curl -s http://localhost:4040/api/tunnels | python3 -c \
    "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"
!rm /tmp/log/*
!ls /tmp/log/<jupyter_output><empty_output><jupyter_text>Practice 1: polar pretzels_inspired by [this post](https://www.quora.com/What-are-the-most-interesting-equation-plots)_There are some simple mathematical functions with cool plots. For one, consider this:$$ x(t) = t - 1.5 * cos( 15 t) $$$$ y(t) = t - 1.5 * sin( 16 t) $$<jupyter_code>t = tf.placeholder('float32')


# compute x(t) and y(t) as defined above.
x = t - 1.5* tf.cos(15*t)
y = t - 1.5* tf.sin(16*t)


x_points, y_points = sess.run([x, y], {t: np.linspace(-10, 10, num=50000)})
plt.plot(x_points, y_points);

writer = tf.summary.FileWriter(LOG_DIR, graph=sess.graph)
x_points, y_points<jupyter_output><empty_output><jupyter_text>Visualizing graphs with TensorboardIt's often useful to visualize the computation graph when debugging or optimizing. Interactive visualization is where tensorflow really shines as compared to other frameworks. There's a special instrument for that, called Tensorboard. You can launch it from console:__```tensorboard --logdir=/tmp/tboard --port=7007```__If you're pathologically afraid of consoles, try this:__```import os; os.system("tensorboard --logdir=/tmp/tboard --port=7007 &")```___(but don't tell anyone we taught you that)_ One basic functionality of tensorboard is drawing graphs. One you've run the cell above, go to `localhost:7007` in your browser and switch to _graphs_ tab in the topbar. Here's what you should see:Tensorboard also allows you to draw graphs (e.g. learning curves), record images & audio ~~and play flash games~~. This is useful when monitoring learning progress and catching some training issues.One researcher said:```If you spent last four hours of your worktime watching as your algorithm prints numbers and draws figures, you're probably doing deep learning wrong.``` You can read more on tensorboard usage [here](https://www.tensorflow.org/get_started/graph_viz)  Practice 2: mean squared error<jupyter_code># Quest #1 - implement a function that computes a mean squared error of two input vectors
# Your function has to take 2 vectors and return a single number

v1 = tf.placeholder('float32',shape=(None,))
v2 = tf.placeholder('float32',shape=(None,))

# First version
mse = tf.reduce_mean(tf.math.square(v1 - v2))
# Second version
# mse = tf.math.reduce_mean(tf.math.square(v1 - v2))
# Third version
# mse = tf.math.reduce_mean(tf.math.squared_difference(v1, v2) )

compute_mse = lambda vector1, vector2: sess.run(mse, {v1: vector1, v2: vector2})
# Tests
from sklearn.metrics import mean_squared_error

for n in [1, 5, 10, 10 ** 3]:
    
    elems = [np.arange(n),np.arange(n,0,-1), np.zeros(n),
             np.ones(n),np.random.random(n),np.random.randint(100,size=n)]
    
    for el in elems:
        for el_2 in elems:
            true_mse = np.array(mean_squared_error(el,el_2))
            my_mse = compute_mse(el,el_2)
            if not np.allclose(true_mse,my_mse):
                print('Wrong result:')
                print('mse(%s,%s)' % (el,el_2))
                print("should be: %f, but your function returned %f" % (true_mse,my_mse))
                raise ValueError("Что-то не так")

print("All tests passed")<jupyter_output>All tests passed<jupyter_text>Tensorflow variablesThe inputs and transformations have no value outside function call. That's a bit unnatural if you want your model to have parameters (e.g. network weights) that are always present, but can change their value over time.Tensorflow solves this with `tf.Variable` objects.* You can assign variable a value at any time in your graph* Unlike placeholders, there's no need to explicitly pass values to variables when `s.run(...)`-ing* You can use variables the same way you use transformations<jupyter_code># creating shared variable
shared_vector_1 = tf.Variable(initial_value=np.ones(5))

# initialize all variables with initial values
sess.run(tf.global_variables_initializer())
# evaluating shared variable (outside symbolicd graph)
print("initial value", sess.run(shared_vector_1))

# within symbolic graph you use them just as any other inout or transformation, not "get value" needed
# setting new value manually
sess.run(shared_vector_1.assign(np.arange(5)))

#getting that new value
print("new value", sess.run(shared_vector_1))<jupyter_output>new value [0. 1. 2. 3. 4.]<jupyter_text>tf.gradients - why graphs matter* Tensorflow can compute derivatives and gradients automatically using the computation graph* Gradients are computed as a product of elementary derivatives via chain rule:$$ {\partial f(g(x)) \over \partial x} = {\partial f(g(x)) \over \partial g(x)}\cdot {\partial g(x) \over \partial x} $$It can get you the derivative of any graph as long as it knows how to differentiate elementary operations<jupyter_code>my_scalar = tf.placeholder('float32')

scalar_squared = my_scalar ** 2

#a derivative of scalar_squared by my_scalar
derivative = tf.gradients(scalar_squared, [my_scalar])[0]
x = np.linspace(-3,3)
x
x_squared, x_squared_der = sess.run([scalar_squared, derivative], {my_scalar:x})
x_squared, x_squared_der
plt.plot(x, x_squared,label="x^2")
plt.plot(x, x_squared_der, label="derivative")
plt.legend();<jupyter_output><empty_output><jupyter_text>Why autograd is cool<jupyter_code>my_vector = tf.placeholder('float32',[None])

#Compute the gradient of the next weird function over my_scalar and my_vector
#warning! Trying to understand the meaning of that function may result in permanent brain damage

weird_psychotic_function = tf.reduce_mean((my_vector+my_scalar)**(1+tf.nn.moments(my_vector,[0])[1]) + 1./ tf.atan(my_scalar))/(my_scalar**2 + 1) + 0.01*tf.sin(2*my_scalar**1.5)*(tf.reduce_sum(my_vector)* my_scalar**2)*tf.exp((my_scalar-4)**2)/(1+tf.exp((my_scalar-4)**2))*(1.-(tf.exp(-(my_scalar-4)**2))/(1+tf.exp(-(my_scalar-4)**2)))**2
 
der_by_scalar = tf.gradients(weird_psychotic_function, [my_scalar])[0]
der_by_vector = tf.gradients(weird_psychotic_function, [my_vector])[0]
#Plotting your derivative
scalar_space = np.linspace(1, 7, 100)

y = [sess.run(weird_psychotic_function, {my_scalar:x, my_vector:[1, 2, 3]})
     for x in scalar_space]

plt.plot(scalar_space, y, label='function')

y_der_by_scalar = [sess.run(der_by_scalar, {my_scalar:x, my_vector:[1, 2, 3]})
     for x in scalar_space]

plt.plot(scalar_space, y_der_by_scalar, label='derivative')
plt.grid()
plt.legend();<jupyter_output><empty_output><jupyter_text>Almost done - optimizersWhile you can perform gradient descent by hand with automatic grads from above, tensorflow also has some optimization methods implemented for you. Recall momentum & rmsprop?<jupyter_code>y_guess = tf.Variable(np.zeros(2,dtype='float32'))
y_true = tf.range(1,3,dtype='float32')

loss = tf.reduce_mean((y_guess - y_true + tf.random_normal([2]))**2) 

optimizer = tf.train.MomentumOptimizer(0.01,0.9).minimize(loss,var_list=y_guess)

# same, but more detailed:
# updates = [[tf.gradients(loss,y_guess)[0], y_guess]]
# optimizer = tf.train.MomentumOptimizer(0.01,0.9).apply_gradients(updates)
from IPython.display import clear_output

sess.run(tf.global_variables_initializer())

guesses = [sess.run(y_guess)]

for _ in range(100):
    sess.run(optimizer)
    guesses.append(sess.run(y_guess))
    
    clear_output(True)
    plt.plot(*zip(*guesses), marker='.')
    plt.scatter(*sess.run(y_true), c='red')
    plt.show()<jupyter_output><empty_output><jupyter_text>Logistic regression exampleImplement the regular logistic regression training algorithm We shall train on a two-class MNIST dataset. This is a binary classification problem, so we'll train a __Logistic Regression with sigmoid__.$$P(y_i | X_i) = \sigma(W \cdot X_i + b) ={ 1 \over {1+e^{- [W \cdot X_i + b]}} }$$The natural choice of loss function is to use binary crossentropy (aka logloss, negative llh):$$ L = {1 \over N} \underset{X_i,y_i} \sum - [  y_i \cdot log P(y_i | X_i) + (1-y_i) \cdot log (1-P(y_i | X_i)) ]$$Mind the minus :)<jupyter_code>from sklearn.datasets import load_digits
X, y = load_digits(2, return_X_y=True)

# print("y [shape - %s]:" % (str(y.shape)), y)
# print("X [shape - %s]:" % (str(X.shape)), X[:1])
# print('X:\n', X[:1])
print('y:\n', y)
# plt.imshow(X[1].reshape([8,8]))
# inputs and shareds
input_X = tf.placeholder(dtype='float32', shape=[None, 64], name="input_X")
input_y = tf.placeholder(dtype='float32', shape=[None, 1],  name="input_y")

W = tf.Variable(tf.zeros([64, 1]), name="weights")
b = tf.Variable(tf.zeros([1, 1]),   name="bias")

predicted_y_proba = tf.matmul(input_X, W) + b
# predicted_y_proba = input_X @ W + b 

prediction = tf.round(tf.sigmoid(predicted_y_proba))
entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=predicted_y_proba, labels=input_y)
loss = tf.reduce_mean(entropy)
train_step = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
# X_train.shape,  X_train[0].shape, np.matrix(y_train[0]).T.shape, np.matrix(y_train).T.shape
from sklearn.metrics import roc_auc_score

init = tf.global_variables_initializer()
sess.run(init)

for i in range(5):   

    loss_i, _ = sess.run([loss, train_step], feed_dict={input_X: X_train, input_y: np.matrix(y_train).T})
    
    print("loss at iter %i: %.4f" % (i, loss_i))

    print("train auc:", roc_auc_score(y_train, sess.run(predicted_y_proba, {input_X: X_train})))
    print("test auc:", roc_auc_score(y_test, sess.run(predicted_y_proba, {input_X: X_test})))

    
print ("resulting weights:")
# plt.imshow(sess.run(W).reshape(8, -1))
# plt.colorbar();
for i in range(10):
  el = X[i]

#   plt.imshow(el.reshape([8,8]))
  prob = sess.run(prediction, {input_X: np.array([el])})
  print(prob, y[i])<jupyter_output><empty_output><jupyter_text>Practice 3: my first tensorflow networkYour ultimate task for this week is to build your first neural network [almost] from scratch and pure tensorflow.This time you will same digit recognition problem, but at a larger scale* images are now 28x28* 10 different digits* 50k samplesNote that you are not required to build 152-layer monsters here. A 2-layer (one hidden, one output) NN should already have ive you an edge over logistic regression.__[bonus score]__If you've already beaten logistic regression with a two-layer net, but enthusiasm still ain't gone, you can try improving the test accuracy even further! The milestones would be 95%/97.5%/98.5% accuraсy on test set.__SPOILER!__At the end of the notebook you will find a few tips and frequently made mistakes. If you feel enough might to shoot yourself in the foot without external assistance, we encourage you to do so, but if you encounter any unsurpassable issues, please do look there before mailing us.<jupyter_code>!pip install python-mnist
from keras.datasets import mnist

# [down]loading the original MNIST dataset.
# Please note that you should only train your NN on _train sample,
#  _val can be used to evaluate out-of-sample error, compare models or perform early-stopping
#  _test should be hidden under a rock untill final evaluation... But we both know it is near impossible to catch you evaluating on it.
(X_train, y_train), (X_test, y_test) = mnist.load_data()

print (X_train.shape, y_train.shape)
plt.imshow(X_train[0])
img_size = 28*28
classes = 10
n_hidden = 256
# <this cell looks as if it wants you to create variables here>

X = tf.placeholder(dtype='float32', shape=[None, img_size], name="X")
y = tf.placeholder(dtype='float32', shape=[None, classes], name="y")

W_hidden = tf.Variable(tf.random_normal([classes, n_hidden]), name="weights_hidden")
W_out = tf.Variable(tf.random_normal([n_hidden, classes]), name="weights_out")

b_hidden = tf.Variable(tf.random_normal([n_hidden]), name="bias_hidden")
b_out = tf.Variable(tf.random_normal([classes]), name="bias_out")
X.shape, W_hidden.shape, b_hidden.shape
# <you could just as well create a computation graph here - loss, optimizers, all that stuff>

hidden_layer = tf.matmul(X, W_hidden) + b_hidden
logits = tf.add(tf.matmul(hidden_layer, W_out), b_out)

<this may or may not be a good place to run optimizer in a loop>
<this may be a perfect cell to write a training & evaluation loop in>
<predict & evaluate on test here, right? No cheating pls.><jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12365429722740122, 'fraction_numerical': 0.020448667829434053, 'mean_word_length': 5.327245053272451, 'pattern_counts': {'":': 0, '<': 55, '<?xml version=': 0, '>': 59, 'https://': 9, 'lorem ipsum': 0, 'www.': 5, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '89381', 'license': 'MIT', 'n_tokens_mistral': 5899, 'n_tokens_neox': 5555, 'n_words': 1653, 'path': 'week02_autodiff/seminar_tensorflow.ipynb', 'repo_name': 'legchikov/Practical_DL', 'size': '16627'}