<jupyter_start><jupyter_text>Optimization in TensorFlow  Constraints that can't be satisfied: put them into the objective function as a penaltyWhat happens if you want something not yet in TensorFlow?Optimization is a great framework for modeling.Be an **innovator** don't just **follow**.Read papers and implement them.Common objective functions1. MSE2. MAE3. Logistic Error4. Cross EntropyGenerate some synthetic data - understand the algorithm with synthetic data.<jupyter_code>a = np.array([[1, 2, 3, 4]], dtype=np.float32)
XX = np.random.rand(10000, 4)
YY = np.dot(XX, a.transpose())
w = tf.Variable(tf.random_uniform([4,1]))
# objective function is MSE
def f(X):
    return tf.matmul(X, w) # w^2 for non-negative or tf.tanh(w) for -1, +1
def objective(X, Y):
    return tf.reduce_sum(tf.square(tf.sub(Y, f(X)))) # tf.sub is subtract
X = tf.placeholder(tf.float32, [None, 4])
Y = tf.placeholder(tf.float32, [None, 1])
grad = tf.gradients(objective(X, Y), [w])
sess.run(tf.initialize_all_variables())
sess.run(grad, feed_dict={X:np.zeros([10,4]), Y:np.random.rand(10,1)})
step = tf.constant(1e-5)
sess.run(tf.initialize_all_variables())
for i in range(100):
    sess.run(tf.assign_add(w, tf.mul(-step, grad[0])), feed_dict={X:XX, Y:YY})<jupyter_output><empty_output><jupyter_text>Original data was 1, 2, 3, 4<jupyter_code>sess.run(w)
for i in range(1000):
    sess.run(tf.assign_add(w, tf.mul(-step, grad[0])), feed_dict={X:XX, Y:YY})
sess.run(w)<jupyter_output><empty_output><jupyter_text>This is slow, of course - use TensorFlow gradient descent<jupyter_code>optimizer = tf.train.GradientDescentOptimizer(step)
train = optimizer.minimize(objective(X,Y), var_list=[w])
for i in range(100):
    sess.run(train, feed_dict={X:XX, Y:YY})
sess.run(w)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1556179775280899, 'fraction_numerical': 0.028651685393258425, 'mean_word_length': 6.0395256916996045, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, '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': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '135410', 'license': 'MIT', 'n_tokens_mistral': 700, 'n_tokens_neox': 662, 'n_words': 161, 'path': 'Optimization in TensorFlow.ipynb', 'repo_name': 'dtsmith2001/tensorflow-exercises', 'size': '1780'}