深度学习的始祖框架,grandfather级别的框架 —— Theano —— 示例代码学习(5)

Angry Panda / 2024-02-13 / 原文

代码1:(求雅可比矩阵, jacobian矩阵求解)

import theano
from theano import tensor

# Creating a vector
x = tensor.dvector('x')

# Creating 'y' expression
y = (2 * x ** 3)

# Computing derivative
Output, updates = theano.scan(lambda i, y, x : tensor.grad(y[i], x),\
                               sequences=tensor.arange(y.shape[0]),\
                                  non_sequences=[y, x])

# Creating function
# fun = theano.function([x], Output, updates=updates)
fun = theano.function([x], Output)

# Calling function
print( fun([3,3]) )

运行结果:

image



代码2:(求黑森矩阵, Hession矩阵求解)

import theano
from theano import tensor

# Creating a vector
x = tensor.dvector('x')

# Creating 'y' expression
y = (2 * x ** 3)

# Calculating cost
cost = y.sum()

# Computing derivative
derivative = tensor.grad(cost, x)
output, updates = theano.scan(lambda i, derivative,x : \
                              tensor.grad(derivative[i], x),\
                               sequences=tensor.arange(derivative.shape[0]),\
                                 non_sequences=[derivative, x])

# Creating function
# fun = theano.function([x], output, updates=updates)
fun = theano.function([x], output)

# Calling function
print( fun([3,3]) )

运行结果:

image



代码3:(theano自定义列表List类型)

import theano.typed_list

# Creating typedlist
f1 = theano.typed_list.TypedListType(theano.tensor.fvector)()

# Creating a vector
f2 = theano.tensor.fvector()

# Appending 'f1' and 'f2'
f3 = theano.typed_list.append(f1, f2)

# Creating function which takes two vectors 'f1' and 'f2' as input and gives 'f3' as output
fun = theano.function([f1, f2], f3)

# Calling function
print( fun([[1,2]], [2]) )
print( type(fun([[1,2]], [2])) )

运行结果:

image



代码4:(theano的switch选择函数)

import theano
from theano import tensor

# Creating two scalars
x, y = tensor.scalars('x', 'y')
xx, yy = tensor.vectors('xx', 'yy')

# switch expression
switch_expression = tensor.switch(tensor.gt(x, y), x, y)
switch_expression2 = tensor.switch(tensor.gt(xx, yy), xx, yy)

# Creating function
fun = theano.function([x, y], switch_expression, mode=theano.compile.mode.Mode(linker='vm'))
fun2 = theano.function([xx, yy], switch_expression2, mode=theano.compile.mode.Mode(linker='vm'))

# Calling function fun(12,11)
print( fun(12,11) )

print( fun2([2, 2, 2], [1, 1, 1]) )

print( fun2([2, 0, 2], [1, 3, 1]) )

运行结果:

image



代码5:

import theano

# Creating a theano variable 'x' with value 10
x = theano.shared(10, 'xxx')

#This will just print the variable x
print(x)

# Eval function
print(x.eval()) #This will print its actual value

运行结果:

image