Skip to content

Instantly share code, notes, and snippets.

@bayerj
Created August 4, 2011 17:46
Show Gist options
  • Select an option

  • Save bayerj/1125740 to your computer and use it in GitHub Desktop.

Select an option

Save bayerj/1125740 to your computer and use it in GitHub Desktop.
Linear regression in python.
import scipy
import theano
import theano.tensor as T
# Define variables.
W = T.matrix('weights')
x = T.matrix('features')
z = T.matrix('targets')
# Define model. (Yes, no bias, I am lazy)
y = T.dot(x, W)
# Define loss function.
error = ((z - y)**2).sum()
# Build gradient expression.
d_error_wrt_W = T.grad(error, [W])
# Compile error function and its gradient.
f = theano.function([W, x, z], error)
f_prime = theano.function([W, x, z], d_error_wrt_W)
# Some constants.
steprate = 0.001
iterations = 1000
# Define data. This is is just a one dimensional problem.
features = scipy.array([[1], [2], [1.5]])
targets = scipy.array([[2], [4], [3]])
parameters = scipy.random.standard_normal((1,1))
# Run stupid gradient descent.
for i in range(iterations):
error = f(parameters, features, targets)
errorgrad = f_prime(parameters, features, targets)
parameters -= errorgrad * steprate
print error
# This should print out 2.
print parameters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment