001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.reef.examples.group.bgd.data; 020 021import org.apache.reef.examples.group.utils.math.Vector; 022 023/** 024 * Example implementation on a index and value array. 025 */ 026public final class SparseExample implements Example { 027 028 private static final long serialVersionUID = -2127500625316875426L; 029 030 private final float[] values; 031 private final int[] indices; 032 private final double label; 033 034 public SparseExample(final double label, final float[] values, final int[] indices) { 035 this.label = label; 036 this.values = values; 037 this.indices = indices; 038 } 039 040 public int getFeatureLength() { 041 return this.values.length; 042 } 043 044 @Override 045 public double getLabel() { 046 return this.label; 047 } 048 049 @Override 050 public double predict(final Vector w) { 051 double result = 0.0; 052 for (int i = 0; i < this.indices.length; ++i) { 053 result += w.get(this.indices[i]) * this.values[i]; 054 } 055 return result; 056 } 057 058 @Override 059 public void addGradient(final Vector gradientVector, final double gradient) { 060 for (int i = 0; i < this.indices.length; ++i) { 061 final int index = this.indices[i]; 062 final double contribution = gradient * this.values[i]; 063 final double oldValue = gradientVector.get(index); 064 final double newValue = oldValue + contribution; 065 gradientVector.set(index, newValue); 066 } 067 } 068}