# Example 2 - Linear Regression Example with Python and theano from MSDN

## code example

``````#!/usr/bin/python
# -*- coding: utf-8 -*-

# https://blogs.msdn.microsoft.com/lukassteindl/2015/12/13/linear-regression-example-with-python-and-theano/
# http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/

"""

The problem is that so far the integration of IPython with matplotlib is entirely static,
while animations are by their nature dynamic.
"""

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import theano
from theano import tensor as T
import numpy as np

style.use('fivethirtyeight')
fig = plt.figure()

trX = np.linspace(-1,1,101)  # (101,)
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33   # (101,)

X = T.scalar()
Y = T.scalar()

def model (X,w):
return X * w

w = theano.shared(np.asarray(0., dtype=theano.config.floatX)) #scalar
y = model(X,w)

cost = T.mean(T.sqr(y-Y))

def run():
for i in range(100):
for x,y in zip (trX,trY):
train(x,y)
print (w.eval())

def animate(i):
# i: iteration of animate
#print i
ax1.clear()
plt.scatter(trX, trY,  label='Gradient Descent on GPU',
alpha=0.3, edgecolors='none')
plt.legend()
plt.grid(True)
for x,y in zip (trX,trY):
train(x,y)
#print (w.eval())

xs = [-1,1]
ys = [-1*w.eval(),w.eval()]
ax1.plot(xs,ys)

def show_animate():
ani = animation.FuncAnimation(fig, animate, interval = 250)
plt.show()

def main():
#run()
show_animate()

main()
``````

## History

• 20180807: created.

Author: kezunlin
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source kezunlin !

TOC