pycnn add 실례

3853 단어 신경 망pycnn
초보 적 으로 신경 망 을 접 하고 복잡 한 네트워크 구 조 를 사용 하 는 지,아니면 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]))

참고 자료
  • pycnn-api
  • pycnn-examples-xor
  • 좋은 웹페이지 즐겨찾기