pycnn add实例

来源:互联网 发布:linux 得到当前时间 编辑:程序博客网 时间:2024/06/05 09:23

初步接触神经网络,还不会设计使用复杂的网络结构,还是借鉴xor的流程,做一个学习三个输入值做加法的训练模型。

from pycnn import *import randomhidden_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) + aloss = 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_examplesx_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]))

参考资料

  1. pycnn-api
  2. pycnn-examples-xor
0 0
原创粉丝点击