All the solutions I’ve seen so far are unsatisfactory in that they take no advantage of the advances in the hottest field in Computer Science: Machine Learning. But this is your lucky day, and courtesy of Google’s release of the TensorFlow Open Source Library for Machine Intelligence, I am able to remedy this problem, but providing a truly intelligent (artificially!) solution:
#!/usr/bin/env python3
import tensorflow as tf
sess = tf.InteractiveSession()
n = 3
# input will be a matrix containing elements 1 ... n^2
inp = tf.reshape(tf.linspace(1.0, n*n, n*n), [n, n])
# Generate a matrix with rows 1..n
rows = tf.matmul(tf.reshape(tf.range(1, n+1), [n, 1]),
tf.ones([1, n], dtype=tf.int32))
# Generate a flipped triangular matrix
indicator = rows<=tf.reverse(tf.range(1, n+1), dims=[True])
# Desired output is a triangular float matrix with ones in
# upper left corner
desired = tf.to_float(indicator)
# We want to learn the mapping from input to output
tf.set_random_seed(2)
# Output is predicted after multiplying the input by a matrix
# which we learn automatically.
weights = tf.Variable(tf.random_normal([n, n], stddev=1.0/n/n))
predicted = tf.matmul(inp, weights)
# L2 loss
loss = tf.reduce_mean(tf.square(predicted - desired))
optimizer = tf.train.GradientDescentOptimizer(0.005)
train = optimizer.minimize(loss)
# Run machine learning for 1000 steps. You can verify that much
# less than this isn't sufficient.
sess.run(tf.initialize_all_variables())
for step in range(1000):
sess.run(train)
predicted_bool = tf.equal(tf.round(predicted), 1.0)
shape = tf.shape(predicted_bool)
result = tf.select(predicted_bool, tf.fill(shape, 'Smile!'),
tf.fill(shape, ''))
print(result.eval())
# Result:
# [['Smile!' 'Smile!' 'Smile!']
# ['Smile!' 'Smile!' '']
# ['Smile!' '' '']]