使用链接器进行回归
Regression with chainer
如何使用 Chainer 进行回归?
仅仅用像F.mean_squared_error
这样的损失函数替换通常的L.Classifier
是行不通的,例如
from chainer import iterators, optimizers, training
from chainer import Chain
from chainer.datasets import mnist
import chainer.functions as F
import chainer.links as L
from chainer.training import extensions
import numpy as np
# simple addition data
N = 1000
x_ = np.random.choice(10, size=(N, 2)).astype(np.float32)
y_ = x_.sum(axis=1).astype(np.float32)
train = [(x[:,None], np.asarray([y])) for x, y in zip(x_, y_)]
train_iter = iterators.SerialIterator(train, 1000)
# model
class Model(Chain):
def __init__(self):
super(Model, self).__init__()
with self.init_scope():
self.l_out = L.Linear(2, 1)
def forward(self, x):
return self.l_out(x)
model = Model()
model = F.mean_squared_error(model)
# run
optimizer = optimizers.Adam()
optimizer.setup(model)
updater = training.updaters.StandardUpdater(train_iter, optimizer)
trainer = training.Trainer(updater, (1000, 'epoch'), out='mnist_result')
trainer.run()
报错:
TypeError: optimization target must be a link
Counter-intuitively,回归还是要用L.Classifier
,例如对于 MSE:
model = L.Classifier(model, lossfun=F.mean_squared_error, accfun=F.mean_squared_error)
如何使用 Chainer 进行回归?
仅仅用像F.mean_squared_error
这样的损失函数替换通常的L.Classifier
是行不通的,例如
from chainer import iterators, optimizers, training
from chainer import Chain
from chainer.datasets import mnist
import chainer.functions as F
import chainer.links as L
from chainer.training import extensions
import numpy as np
# simple addition data
N = 1000
x_ = np.random.choice(10, size=(N, 2)).astype(np.float32)
y_ = x_.sum(axis=1).astype(np.float32)
train = [(x[:,None], np.asarray([y])) for x, y in zip(x_, y_)]
train_iter = iterators.SerialIterator(train, 1000)
# model
class Model(Chain):
def __init__(self):
super(Model, self).__init__()
with self.init_scope():
self.l_out = L.Linear(2, 1)
def forward(self, x):
return self.l_out(x)
model = Model()
model = F.mean_squared_error(model)
# run
optimizer = optimizers.Adam()
optimizer.setup(model)
updater = training.updaters.StandardUpdater(train_iter, optimizer)
trainer = training.Trainer(updater, (1000, 'epoch'), out='mnist_result')
trainer.run()
报错:
TypeError: optimization target must be a link
Counter-intuitively,回归还是要用L.Classifier
,例如对于 MSE:
model = L.Classifier(model, lossfun=F.mean_squared_error, accfun=F.mean_squared_error)