Код: Выделить всё
terminate called after throwing an instance of 'std::invalid_argument'
what(): A row can only be accessed on an expression with exact two dimensions
Aborted (core dumped)
Код: Выделить всё
class Softmax {
public:
Softmax(int axis) : m_nAxis(axis) {}
xt::xarray forward(xt::xarray X) {
cached_Y = softmax(X, m_nAxis);
return cached_Y;
}
xt::xarray backward(const xt::xarray& DY) {
xt::xarray DX = xt::zeros(DY.shape());
int nclasses = DY.shape()[0];
for (int i = 0; i < nclasses; i++) {
xt::xarray y = xt::row(cached_Y, i);
xt::xarray dy_i = xt::row(DY, i);
xt::xarray J = xt::diag(y) - xt::linalg::outer(y, y);
xt::view(DX, i) = xt::linalg::dot(J, dy_i);
}
return DX;
}
private:
int m_nAxis;
xt::xarray cached_Y;
int positive_index(int idx, int size) {
if (idx < 0) return idx + size;
return idx;
}
xt::xarray softmax(xt::xarray X, int axis) {
xt::svector shape = X.shape();
axis = positive_index(axis, shape.size());
shape[axis] = 1;
xt::xarray Xmax = xt::amax(X, {axis});
X = xt::exp(X - Xmax.reshape(shape));
xt::xarray SX = xt::sum(X, {axis});
SX = SX.reshape(shape);
X = X / SX;
return X;
}
};
int main(int argc, char* argv[]) {
xt::xarray X = {1, 2, 3};
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79173113/i-got-a-problem-when-implement-the-backward-function-for-softmax-layer-but-i-try[/url]