Skip to content

Instantly share code, notes, and snippets.

@kripken
Last active February 16, 2026 21:04
Show Gist options
  • Select an option

  • Save kripken/9582513853a6b6be3a777331d52b5ce9 to your computer and use it in GitHub Desktop.

Select an option

Save kripken/9582513853a6b6be3a777331d52b5ce9 to your computer and use it in GitHub Desktop.
Greeting Neural Network
def matrix_math(matrix, offset, vector):
'''
Computes
matrix*vector + offset
Matrix is mxn, vector ix 1xn, offset is 1xn
'''
m = len(matrix)
n = len(vector)
ret = [0] * len(offset)
for i in range(m):
for j in range(n):
ret[i] += matrix[i][j] * vector[j]
ret[i] += offset[i]
return ret
class NeuralNetwork:
'''
Given a name in the input layer, emit "Hello, {NAME}" in the output.
'''
max_name_len = 8
def linear_layer(self, input):
'''
Copy the input into the right place, with the rest of the string in
the offset.
'''
weights = [
# First 7 spots are will be filled in by 'Hello, '
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
# Next, we copy in the input.
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
]
# 'Hello, ' + zeroes
offset = [72, 101, 108, 108, 111, 44, 32, 0, 0, 0, 0, 0, 0, 0, 0]
return matrix_math(weights, offset, input)
# Run the network on some tests
nn = NeuralNetwork()
for name in ['Anna', 'Joe', 'Crevyzik']:
# Convert name to numbers.
input = [ord(c) for c in name.ljust(nn.max_name_len, ' ')]
# Run the network.
output = nn.linear_layer(input)
# Convert back to letters , and print.
output = ''.join([chr(i) for i in output])
print(f'input: {name.ljust(nn.max_name_len)} ==> ', end='')
print(f'neural network output: {output}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment