コード例 #1
0
def forward(net, input_data, deploy=False):
    """Defines and creates the ReInspect network given the net, input data
    and configurations."""

    net.clear_forward()
    if deploy:
        image = np.array(input_data["image"])
    else:
        image = np.array(input_data["image"])
        label = np.array(input_data["label"])
        net.f(NumpyData("label", data=label))

    net.f(NumpyData("image", data=image))
    generate_decapitated_alexnet(net)
    net.f(
        InnerProduct(name="fc8_dish",
                     bottoms=["fc7"],
                     param_lr_mults=[1.0 * 10, 2.0 * 10],
                     param_decay_mults=[1.0, 0.0],
                     weight_filler=Filler("gaussian", 0.01),
                     bias_filler=Filler("constant", 0.0),
                     num_output=128))

    net.f(Softmax("dish_probs", bottoms=["fc8_dish"]))

    if not deploy:
        net.f(SoftmaxWithLoss(name="loss", bottoms=["fc8_dish", "label"]))
        # net.f(Accuracy(name="dish_accuracy",bottoms=["fc8_dish_23", "label"]))

    if deploy:
        probs = np.array(net.blobs["dish_probs"].data)
        return probs
    else:
        return None
コード例 #2
0
def generate_inner_products_using_ip_split(net, step, filler):
    bottom_name = "dropout%d" % step
    generate_ip_split_layers(net, bottom_name, 250, "ip_conf%d" % step, 2)
    generate_ip_split_layers(net, bottom_name, 250,
                             "ip_bbox_unscaled%d" % step, 4)
    net.f(
        Power("ip_bbox%d" % step,
              scale=100,
              bottoms=["ip_bbox_unscaled%d" % step]))
    net.f(Softmax("ip_soft_conf%d" % step, bottoms=["ip_conf%d" % step]))
コード例 #3
0
def generate_inner_products(net, step, filler):
    """Inner products are fully connected layers. They generate
    the final regressions for the confidence (ip_soft_conf),
    and the bounding boxes (ip_bbox)"""

    net.f(InnerProduct("ip_conf%d" % step, 2, bottoms=["dropout%d" % step],
                       output_4d=True,
                       weight_filler=filler))
    net.f(InnerProduct("ip_bbox_unscaled%d" % step, 4,
                       bottoms=["dropout%d" % step], output_4d=True,
                       weight_filler=filler))
    net.f(Power("ip_bbox%d" % step, scale=100,
                bottoms=["ip_bbox_unscaled%d" % step]))
    net.f(Softmax("ip_soft_conf%d" % step, bottoms=["ip_conf%d"%step]))
コード例 #4
0
ファイル: char_model.py プロジェクト: stjordanis/Strada.jl
def eval_forward(net):
    net.clear_forward()
    output_words = []
    net.f(NumpyData('lstm_hidden_prev', np.zeros((1, dimension))))
    net.f(NumpyData('lstm_mem_prev', np.zeros((1, dimension))))
    length = 150
    for step in range(length):
        net.clear_forward()
        net.f(NumpyData('word', [0]))
        prev_hidden = 'lstm_hidden_prev'
        prev_mem = 'lstm_mem_prev'
        if step == 0:
            output = ord('.')
        else:
            output = softmax_choice(net.blobs['softmax'].data)
        output_words.append(output)
        net.blobs['word'].data[0] = output
        net.f(
            Wordvec('wordvec',
                    dimension,
                    vocab_size,
                    bottoms=['word'],
                    param_names=['wordvec_param']))
        net.f(Concat('lstm_concat', bottoms=[prev_hidden, 'wordvec']))
        net.f(
            LstmUnit('lstm',
                     dimension,
                     bottoms=['lstm_concat', prev_mem],
                     param_names=[
                         'lstm_input_value', 'lstm_input_gate',
                         'lstm_forget_gate', 'lstm_output_gate'
                     ],
                     tops=['lstm_hidden_next', 'lstm_mem_next']))
        net.f(Dropout('dropout', 0.16, bottoms=['lstm_hidden_next']))

        net.f(
            InnerProduct('ip',
                         vocab_size,
                         bottoms=['dropout'],
                         param_names=['softmax_ip_weights',
                                      'softmax_ip_bias']))
        net.blobs['ip'].data[:] *= i_temperature
        net.f(Softmax('softmax', bottoms=['ip']))
        net.blobs['lstm_hidden_prev'].data_tensor.copy_from(
            net.blobs['lstm_hidden_next'].data_tensor)
        net.blobs['lstm_mem_prev'].data_tensor.copy_from(
            net.blobs['lstm_mem_next'].data_tensor)
    print ''.join([chr(x) for x in output_words])
コード例 #5
0
def evaluate_forward(net, net_config, feat,scene_feat):
    net.clear_forward()
    feat_dim=feat.shape[1]

    net.f(NumpyData("prev_hidden", np.zeros((1, net_config["mem_cells"]))))
    net.f(NumpyData("prev_mem", np.zeros((1, net_config["mem_cells"]))))
    filler = Filler("uniform", net_config["init_range"])

    length = feat.shape[0]+1
    for step in range(length):
        net.clear_forward()
        if step==0:
            value=scene_feat.reshape(1,feat_dim)
        else:
            value = feat[step-1,:].reshape(1,feat_dim)
        net.f(NumpyData("value", data=value ))
        prev_hidden = "prev_hidden"
        prev_mem = "prev_mem"
        net.f(Concat("lstm_concat", bottoms=[prev_hidden, "value"]))
        net.f(LstmUnit("lstm", net_config["mem_cells"],
            bottoms=["lstm_concat", prev_mem],
            param_names=[
                "input_value", "input_gate", "forget_gate", "output_gate"],
            weight_filler=filler,
            tops=["next_hidden", "next_mem"]))
        net.f(InnerProduct("ip", 1, bottoms=["next_hidden"]))
        net.blobs["prev_hidden"].data_tensor.copy_from(
            net.blobs["next_hidden"].data_tensor)
        net.blobs["prev_mem"].data_tensor.copy_from(
            net.blobs["next_mem"].data_tensor)

    for i in xrange(6):
        net.f(InnerProduct("ip%d"%i, 2, bottoms=["next_hidden"]))
        net.f(Softmax("prob%d"%i, bottoms=["ip%d"%i]))

    predictions=[]
    for i in xrange(6):
        predictions.append(float(net.blobs["prob%d"%i].data.flatten()[1]))

    return predictions
コード例 #6
0
def forward(net, input_data, net_config, deploy=False):
    """Defines and creates the ReInspect network given the net, input data
    and configurations."""

    net.clear_forward()

    net.f(
        NumpyData("wordvec_layer",
                  data=np.array(input_data["wordvec_layer"])))  # 128*38*100*1
    net.f(NumpyData("target_words",
                    data=np.array(input_data["target_words"])))  # 128*100*1*1

    tops = []
    slice_point = []
    for i in range(net_config['max_len']):
        tops.append('label%d' % i)
        if i != 0:
            slice_point.append(i)
    net.f(
        Slice("label_slice_layer",
              slice_dim=1,
              bottoms=["target_words"],
              tops=tops,
              slice_point=slice_point))

    tops = []
    slice_point = []
    for i in range(net_config['max_len']):
        tops.append('target_wordvec%d_4d' % i)
        if i != 0:
            slice_point.append(i)
    net.f(
        Slice("wordvec_slice_layer",
              slice_dim=2,
              bottoms=['wordvec_layer'],
              tops=tops,
              slice_point=slice_point))

    for i in range(net_config["max_len"]):  # 128*38*1*1 -> 128*38
        net.f("""
            name: "target_wordvec%d"
            type: "Reshape"
            bottom: "target_wordvec%d_4d"
            top: "target_wordvec%d"
            reshape_param {
              shape {
                dim: 0  # copy the dimension from below
                dim: -1
              }
            }
            """ % (i, i, i))
        #net.f(Reshape('target_wordvec%d'%i, bottoms = ['target_wordvec%d_4d'%i], shape = [0,-1]))

    filler = Filler("uniform", net_config["init_range"])
    for i in range(net_config['max_len']):
        if i == 0:
            net.f(
                NumpyData(
                    "dummy_layer",
                    np.zeros((net_config["batch_size"],
                              net_config["lstm_num_cells"]))))
            net.f(
                NumpyData(
                    "dummy_mem_cell",
                    np.zeros((net_config["batch_size"],
                              net_config["lstm_num_cells"]))))

        for j in range(net_config['lstm_num_stacks']):
            bottoms = []
            if j == 0:
                bottoms.append('target_wordvec%d' % i)
            if j >= 1:
                bottoms.append('dropout%d_%d' % (j - 1, i))
            if i == 0:
                bottoms.append("dummy_layer")
            else:
                bottoms.append('lstm%d_hidden%d' % (j, i - 1))
            net.f(Concat('concat%d_layer%d' % (j, i), bottoms=bottoms))

            param_names = []
            for k in range(4):
                param_names.append('lstm%d_param_%d' % (j, k))
            bottoms = ['concat%d_layer%d' % (j, i)]
            if i == 0:
                bottoms.append('dummy_mem_cell')
            else:
                bottoms.append('lstm%d_mem_cell%d' % (j, i - 1))
            net.f(
                LstmUnit('lstm%d_layer%d' % (j, i),
                         net_config["lstm_num_cells"],
                         weight_filler=filler,
                         param_names=param_names,
                         bottoms=bottoms,
                         tops=[
                             'lstm%d_hidden%d' % (j, i),
                             'lstm%d_mem_cell%d' % (j, i)
                         ]))

            net.f(
                Dropout('dropout%d_%d' % (j, i),
                        net_config["dropout_ratio"],
                        bottoms=['lstm%d_hidden%d' % (j, i)]))

    bottoms = []
    for i in range(net_config['max_len']):
        bottoms.append('dropout%d_%d' % (net_config['lstm_num_stacks'] - 1, i))
    net.f(Concat('hidden_concat', bottoms=bottoms, concat_dim=0))

    net.f(
        InnerProduct("inner_product",
                     net_config['vocab_size'],
                     bottoms=["hidden_concat"],
                     weight_filler=filler))

    bottoms = []
    for i in range(net_config['max_len']):
        bottoms.append('label%d' % i)
    net.f(Concat('label_concat', bottoms=bottoms, concat_dim=0))

    if deploy:
        net.f(Softmax("word_probs", bottoms=["inner_product"]))
    else:
        net.f(
            SoftmaxWithLoss("word_loss",
                            bottoms=["inner_product", "label_concat"],
                            ignore_label=net_config['zero_symbol']))
コード例 #7
0
def forward(net, input_data, net_config, phase='train', deploy=False):
    """Defines and creates the ReInspect network given the net, input data
    and configurations."""

    net.clear_forward()

    batch_ws_i = input_data["ws_i"]
    batch_stop_i = [net_config['max_len']] * net_config['batch_size']
    wordvec_layer = input_data["wordvec_layer"]  # 128*38*100*1
    net.f(NumpyData("target_words",
                    data=np.array(input_data["target_words"])))  # 128*100*1*1

    tops = []
    slice_point = []
    for i in range(net_config['max_len']):
        tops.append('label%d' % i)
        if i != 0:
            slice_point.append(i)
    net.f(
        Slice("label_slice_layer",
              slice_dim=1,
              bottoms=["target_words"],
              tops=tops,
              slice_point=slice_point))

    net.f(NumpyData("target_wordvec%d" % 0,
                    data=wordvec_layer[:, :, 0, 0]))  # start symbol, 128*38

    filler = Filler("uniform", net_config["init_range"])
    for i in range(net_config['max_len']):
        if i == 0:
            net.f(
                NumpyData(
                    "dummy_layer",
                    np.zeros((net_config["batch_size"],
                              net_config["lstm_num_cells"]))))
            net.f(
                NumpyData(
                    "dummy_mem_cell",
                    np.zeros((net_config["batch_size"],
                              net_config["lstm_num_cells"]))))

        for j in range(net_config['lstm_num_stacks']):
            bottoms = []
            if j == 0:
                bottoms.append('target_wordvec%d' % i)
            if j >= 1:
                bottoms.append('dropout%d_%d' % (j - 1, i))
            if i == 0:
                bottoms.append("dummy_layer")
            else:
                bottoms.append('lstm%d_hidden%d' % (j, i - 1))
            net.f(Concat('concat%d_layer%d' % (j, i), bottoms=bottoms))

            param_names = []
            for k in range(4):
                param_names.append('lstm%d_param_%d' % (j, k))
            bottoms = ['concat%d_layer%d' % (j, i)]
            if i == 0:
                bottoms.append('dummy_mem_cell')
            else:
                bottoms.append('lstm%d_mem_cell%d' % (j, i - 1))
            net.f(
                LstmUnit('lstm%d_layer%d' % (j, i),
                         net_config["lstm_num_cells"],
                         weight_filler=filler,
                         param_names=param_names,
                         bottoms=bottoms,
                         tops=[
                             'lstm%d_hidden%d' % (j, i),
                             'lstm%d_mem_cell%d' % (j, i)
                         ]))

            net.f(
                Dropout('dropout%d_%d' % (j, i),
                        net_config["dropout_ratio"],
                        bottoms=['lstm%d_hidden%d' % (j, i)]))

        net.f(
            InnerProduct("ip%d" % i,
                         net_config['vocab_size'],
                         bottoms=[
                             'dropout%d_%d' %
                             (net_config['lstm_num_stacks'] - 1, i)
                         ],
                         weight_filler=filler))

        if i < net_config['max_len'] - 1:
            tar_wordvec = np.array(wordvec_layer[:, :, i + 1, 0])  # 128*38
            if phase == 'test':
                net.f(Softmax("word_probs%d" % i, bottoms=["ip%d" % i]))
                probs = net.blobs["word_probs%d" % i].data
                for bi in range(net_config['batch_size']):
                    if i >= batch_ws_i[bi] and i < batch_stop_i[bi]:
                        vec = [0] * net_config["vocab_size"]
                        peakIndex = np.argmax(probs[bi, :])
                        if peakIndex == net_config['whitespace_symbol']:
                            batch_stop_i[bi] = i + 1
                        vec[peakIndex] = 1
                        tar_wordvec[bi, :] = vec
            net.f(NumpyData("target_wordvec%d" % (i + 1), data=tar_wordvec))

    bottoms = []
    for i in range(net_config['max_len']):
        bottoms.append("ip%d" % i)
    net.f(Concat('ip_concat', bottoms=bottoms, concat_dim=0))

    bottoms = []
    for i in range(net_config['max_len']):
        bottoms.append('label%d' % i)
    net.f(Concat('label_concat', bottoms=bottoms, concat_dim=0))

    if deploy:
        net.f(Softmax("word_probs", bottoms=["ip_concat"]))

    net.f(
        SoftmaxWithLoss("word_loss",
                        bottoms=["ip_concat", "label_concat"],
                        ignore_label=net_config['zero_symbol']))