theano教程:http://deeplearning.net/software/theano/tutorial/adding.html
兩個標量相加
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from theano import function
import theano.tensor as T
# 第1步:定義兩個變量及其類型
x = T.dscalar('x') # 雙精度浮點型的0-維數組(也就是標量)
y = T.dscalar('y')
# 第2步:構建表達式
z = x + y
# 構造函數f,輸入[x, y],輸出是一個0維的numpy.ndarray
f = function([x, y], z)
print f(2, 3) # 使用函數
兩個矩陣相加
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
from theano import function
import theano.tensor as T
x = T.dmatrix('x')
y = T.dmatrix('y')
z = x + y
f = function([x, y], z)
print f([[1, 2], [3, 4]], [[10, 20], [30, 40]])
print f(numpy.array([[1, 2], [3, 4]]), numpy.array([[10, 20], [30, 40]]))
練習
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from theano import function
import theano.tensor as T
a = T.vector() # 向量
b = T.vector()
out = a ** 2 + b ** 2 + 2 * a * b
f = function([a, b], out)
print f([0, 1], [1, 2])
>>>[ 1. 9.]