|
| 1 | +from __future__ import print_function |
| 2 | + |
| 3 | +import keras.backend as K |
| 4 | +import keras.losses as losses |
| 5 | +import keras.optimizers as optimizers |
| 6 | +import numpy as np |
| 7 | + |
| 8 | +from keras.callbacks import ModelCheckpoint |
| 9 | +from keras.layers.advanced_activations import LeakyReLU |
| 10 | +from keras.layers import Input, RepeatVector, Reshape |
| 11 | +from keras.layers.embeddings import Embedding |
| 12 | +from keras.layers.merge import Concatenate, Multiply |
| 13 | +from keras.losses import binary_crossentropy |
| 14 | +from keras.models import Model, Sequential |
| 15 | +from keras.optimizers import Adam |
| 16 | +from matplotlib import pyplot as plt |
| 17 | + |
| 18 | +from .robot_multi_models import * |
| 19 | +from .mhp_loss import * |
| 20 | +from .loss import * |
| 21 | +from .sampler2 import * |
| 22 | + |
| 23 | +from .conditional_image import ConditionalImage |
| 24 | +from .costar import * |
| 25 | + |
| 26 | +class ConditionalImageCostar(ConditionalImage): |
| 27 | + |
| 28 | + def __init__(self, *args, **kwargs): |
| 29 | + super(ConditionalImageCostar, self).__init__(*args, **kwargs) |
| 30 | + self.PredictorCb = ImageWithFirstCb |
| 31 | + |
| 32 | + def _makeModel(self, image, *args, **kwargs): |
| 33 | + |
| 34 | + img_shape = image.shape[1:] |
| 35 | + img_size = 1. |
| 36 | + for dim in img_shape: |
| 37 | + img_size *= dim |
| 38 | + gripper_size = 1 |
| 39 | + arm_size = 6 |
| 40 | + |
| 41 | + # ===================================================================== |
| 42 | + # Load the image decoders |
| 43 | + img_in = Input(img_shape,name="predictor_img_in") |
| 44 | + img0_in = Input(img_shape,name="predictor_img0_in") |
| 45 | + #arm_in = Input((arm_size,)) |
| 46 | + #gripper_in = Input((gripper_size,)) |
| 47 | + #arm_gripper = Concatenate()([arm_in, gripper_in]) |
| 48 | + label_in = Input((1,)) |
| 49 | + ins = [img0_in, img_in] |
| 50 | + |
| 51 | + encoder = MakeImageEncoder(self, img_shape) |
| 52 | + decoder = MakeImageDecoder(self, self.hidden_shape) |
| 53 | + |
| 54 | + LoadEncoderWeights(self, encoder, decoder) |
| 55 | + |
| 56 | + # ===================================================================== |
| 57 | + # Load the arm and gripper representation |
| 58 | + h = encoder([img0_in, img_in]) |
| 59 | + |
| 60 | + if self.validate: |
| 61 | + self.loadValidationModels(arm_size, gripper_size, h0, h) |
| 62 | + |
| 63 | + next_option_in = Input((1,), name="next_option_in") |
| 64 | + next_option_in2 = Input((1,), name="next_option_in2") |
| 65 | + ins += [next_option_in, next_option_in2] |
| 66 | + |
| 67 | + # ===================================================================== |
| 68 | + # Apply transforms |
| 69 | + y = Flatten()(OneHot(self.num_options)(next_option_in)) |
| 70 | + y2 = Flatten()(OneHot(self.num_options)(next_option_in2)) |
| 71 | + |
| 72 | + tform = self._makeTransform() if not self.dense_transform else self._makeDenseTransform() |
| 73 | + tform.summary() |
| 74 | + x = tform([h,y]) |
| 75 | + x2 = tform([x,y2]) |
| 76 | + |
| 77 | + image_out, image_out2 = decoder([x]), decoder([x2]) |
| 78 | + |
| 79 | + # Compute classifier on the last transform |
| 80 | + if not self.no_disc: |
| 81 | + image_discriminator = LoadGoalClassifierWeights(self, |
| 82 | + make_classifier_fn=MakeCostarImageClassifier, |
| 83 | + img_shape=img_shape) |
| 84 | + #disc_out1 = image_discriminator([img0_in, image_out]) |
| 85 | + disc_out2 = image_discriminator([img0_in, image_out2]) |
| 86 | + |
| 87 | + # Create custom encoder loss |
| 88 | + if self.enc_loss: |
| 89 | + loss = EncoderLoss(self.image_encoder, self.loss) |
| 90 | + enc_losses = [loss, loss] |
| 91 | + enc_outs = [x, x2] |
| 92 | + enc_wts = [1e-2, 1e-2] |
| 93 | + img_loss_wt = 1. |
| 94 | + else: |
| 95 | + enc_losses = [] |
| 96 | + enc_outs = [] |
| 97 | + enc_wts = [] |
| 98 | + img_loss_wt = 1. |
| 99 | + |
| 100 | + # Create models to train |
| 101 | + if self.no_disc: |
| 102 | + disc_wt = 0. |
| 103 | + else: |
| 104 | + disc_wt = 1e-3 |
| 105 | + if self.no_disc: |
| 106 | + train_predictor = Model(ins + [label_in], |
| 107 | + [image_out, image_out2] + enc_outs) |
| 108 | + train_predictor.compile( |
| 109 | + loss=[self.loss, self.loss,] + enc_losses, |
| 110 | + loss_weights=[img_loss_wt, img_loss_wt] + enc_wts, |
| 111 | + optimizer=self.getOptimizer()) |
| 112 | + else: |
| 113 | + train_predictor = Model(ins + [label_in], |
| 114 | + #[image_out, image_out2, disc_out1, disc_out2] + enc_outs) |
| 115 | + [image_out, image_out2, disc_out2] + enc_outs) |
| 116 | + train_predictor.compile( |
| 117 | + loss=[self.loss, self.loss, "categorical_crossentropy"] + enc_losses, |
| 118 | + #loss_weights=[img_loss_wt, img_loss_wt, 0.9*disc_wt, disc_wt] + enc_wts, |
| 119 | + loss_weights=[img_loss_wt, img_loss_wt, disc_wt] + enc_wts, |
| 120 | + optimizer=self.getOptimizer()) |
| 121 | + train_predictor.summary() |
| 122 | + |
| 123 | + # Set variables |
| 124 | + self.predictor = None |
| 125 | + self.model = train_predictor |
| 126 | + |
| 127 | + |
| 128 | + def _getData(self, image, label, goal_idx, q, gripper, labels_to_name, *args, **kwargs): |
| 129 | + ''' |
| 130 | + Parameters: |
| 131 | + ----------- |
| 132 | + image: jpeg encoding of image |
| 133 | + label: integer code for which action is being performed |
| 134 | + goal_idx: index of the start of the next action |
| 135 | + q: joint states |
| 136 | + gripper: floating point gripper openness |
| 137 | + labels_to_name: list of high level actions (AKA options) |
| 138 | + ''' |
| 139 | + |
| 140 | + # Null option to be set as the first option |
| 141 | + # Verify this to make sure we aren't loading things with different |
| 142 | + # numbers of available options/high-level actions |
| 143 | + assert(len(labels_to_name) == self.null_option) |
| 144 | + self.null_option = len(labels_to_name) |
| 145 | + # Total number of options incl. null |
| 146 | + self.num_options = len(labels_to_name) + 1 |
| 147 | + |
| 148 | + length = label.shape[0] |
| 149 | + prev_label = np.zeros_like(label) |
| 150 | + prev_label[1:] = label[:(length-1)] |
| 151 | + prev_label[0] = self.null_option |
| 152 | + |
| 153 | + goal_idx = np.min((goal_idx, np.ones_like(goal_idx)*(length-1)),axis=0) |
| 154 | + |
| 155 | + if not (image.shape[0] == goal_idx.shape[0]): |
| 156 | + print("Image shape:", image.shape) |
| 157 | + print("Goal idxs:", goal_idx.shape) |
| 158 | + print(label) |
| 159 | + print(goal_idx) |
| 160 | + raise RuntimeError('data type shapes did not match') |
| 161 | + goal_label = label[goal_idx] |
| 162 | + goal_image = image[goal_idx] |
| 163 | + goal_image2, goal_label2 = GetNextGoal(goal_image, label) |
| 164 | + |
| 165 | + # Extend image_0 to full length of sequence |
| 166 | + image0 = image[0] |
| 167 | + image0 = np.tile(np.expand_dims(image0,axis=0),[length,1,1,1]) |
| 168 | + |
| 169 | + lbls_1h = np.squeeze(ToOneHot2D(label, self.num_options)) |
| 170 | + lbls2_1h = np.squeeze(ToOneHot2D(goal_label2, self.num_options)) |
| 171 | + if self.no_disc: |
| 172 | + return ([image0, image, label, goal_label, prev_label], |
| 173 | + [goal_image, |
| 174 | + goal_image2,]) |
| 175 | + else: |
| 176 | + return ([image0, image, label, goal_label, prev_label], |
| 177 | + [goal_image, |
| 178 | + goal_image2, |
| 179 | + lbls2_1h,]) |
| 180 | + |
0 commit comments