初步接触神经网络,还不会设计使用复杂的网络结构,还是借鉴xor的流程,做一个学习三个输入值做加法的训练模型。
from pycnn import *
import random
hidden_size = 8 # 隐层大小
iterations = 5000 # 迭代次数
m = Model() # 创建一个模型
sgd = SimpleSGDTrainer(m) # 用简单的随机梯度下降法训练模型
m.add_parameters('W', (hidden_size, 3)) # 8*3,3个输入值,8个隐藏层节点
m.add_parameters('b', hidden_size) # 8*1,即列向量
m.add_parameters('V', (1, hidden_size)) # 1*8,即行向量
m.add_parameters('a', 1)
renew_cg() # new computation graph. not strictly needed here, but good practice.
W = parameter(m['W'])
b = parameter(m['b'])
V = parameter(m['V'])
a = parameter(m['a'])
x = vecInput(3)
y = scalarInput(0)
h = tanh((W*x)+b)
y_pred = (V*h) + a
loss = squared_distance(y_pred, y)
# 定义一个获取训练数据及测试数据的方法
def get_examples(num):
extent = 1
x_examples = []
y_examples = []
for i in xrange(num):
a = random.random()*extent
b = random.random()*extent
c = random.random()*extent
x_examples.append([a, b, c])
y_examples.append((a+b+c))
return x_examples, y_examples
x_examples, y_examples = get_examples(100)
for i in xrange(iterations):
mloss = 0.0
for j in xrange(len(x_examples)):
x.set(x_examples[j])
y.set(y_examples[j])
mloss += loss.scalar_value()
loss.backward()
sgd.update()
# sgd.update(1.0)
# sgd.update_epoch()
mloss /= len(x_examples)
if i % (iterations/10) == 0 or i == (iterations-1):
print 'iter %d, loss: %f' % (i, mloss)
x_test, y_test = get_examples(10)
for i in xrange(len(x_test)):
x.set(x_test[i])
print '[%f, %f, %f]: %f, %f' % (x_test[i][0], x_test[i][1], x_test[i][2], y_pred.scalar_value(), sum(x_test[i]))