| 66 | return '%d:%g' % (self.index, self.value) |
| 67 | |
| 68 | def gen_feature_nodearray(xi, feature_max=None, issparse=True): |
| 69 | if isinstance(xi, dict): |
| 70 | index_range = xi.keys() |
| 71 | elif isinstance(xi, (list, tuple)): |
| 72 | xi = [0] + xi # idx should start from 1 |
| 73 | index_range = range(1, len(xi)) |
| 74 | else: |
| 75 | raise TypeError('xi should be a dictionary, list or tuple') |
| 76 | |
| 77 | if feature_max: |
| 78 | assert(isinstance(feature_max, int)) |
| 79 | index_range = filter(lambda j: j <= feature_max, index_range) |
| 80 | if issparse: |
| 81 | index_range = filter(lambda j:xi[j] != 0, index_range) |
| 82 | |
| 83 | index_range = sorted(index_range) |
| 84 | ret = (feature_node * (len(index_range)+2))() |
| 85 | ret[-1].index = -1 # for bias term |
| 86 | ret[-2].index = -1 |
| 87 | for idx, j in enumerate(index_range): |
| 88 | ret[idx].index = j |
| 89 | ret[idx].value = xi[j] |
| 90 | max_idx = 0 |
| 91 | if index_range : |
| 92 | max_idx = index_range[-1] |
| 93 | return ret, max_idx |
| 94 | |
| 95 | class problem(Structure): |
| 96 | _names = ["l", "n", "y", "x", "bias"] |