Skip to content

Instantly share code, notes, and snippets.

View shshemi's full-sized avatar

Shayan Hashemi shshemi

  • Finland
View GitHub Profile
model.compile("adam",
knapsack_loss(input_weights, input_prices, cvc),
metrics=[binary_accuracy, metric_space_violation(input_weights),
metric_overprice(input_prices)])
model.compile("adam",
binary_crossentropy,
metrics=[binary_accuracy, metric_space_violation(input_weights),
metric_overprice(input_prices)])
def get_model(item_count=5):
input_weights = Input((item_count,))
input_prices = Input((item_count,))
inputs_concat = Concatenate()([input_weights, input_prices])
picks = Dense(35, activation="sigmoid")(inputs_concat)
picks = Dense(item_count, activation="sigmoid")(picks)
model = Model(inputs=[input_weights, input_prices], outputs=[picks])
return model
def knapsack_loss(input_weights, input_prices, input_capacity, cvc=1):
def loss(y_true, y_pred):
picks = y_pred
return (-1 * K.batch_dot(picks, input_prices, 1)) + cvc * K.maximum(
K.batch_dot(picks, input_weights, 1) - input_capacity, 0)
return loss
def metric_space_violation(input_weights):
def space_violation(y_true, y_pred):
y_pred = K.round(y_pred)
return K.mean(K.maximum(K.batch_dot(y_pred, input_weights, 1) - 1, 0))
return space_violation
def metric_overprice(input_prices):
def overpricing(y_true, y_pred):
y_pred = K.round(y_pred)
return K.mean(K.batch_dot(y_pred, input_prices, 1) - K.batch_dot(y_true, input_prices, 1))
return overpricing
def brute_force_knapsack(x_weights, x_prices, x_capacity):
item_count = x_weights.shape[0]
picks_space = 2 ** item_count
best_price = -1
best_picks = np.zeros(item_count)
for p in range(picks_space):
picks = [int(c) for c in f"{p:0{item_count}b}"]
price = np.dot(x_prices, picks)
weight = np.dot(x_weights, picks)
if weight <= x_capacity and price > best_price:
def ascii_encode(message, sentence_len):
sen = np.zeros((1, sentence_len))
for i, a in enumerate(message.encode("ascii")):
sen[0, i] = a
return sen
def ascii_decode(message):
return ''.join(chr(int(a)) for a in message[0].argmax(-1))
def get_model(image_shape, sentence_len, dict_len):
# the encoder part
input_img = Input(image_shape)
input_sen = Input((sentence_len,))
embed_sen = Embedding(dict_len, 100)(input_sen)
embed_sen = Flatten()(embed_sen)
embed_sen = Reshape((image_shape[0], image_shape[1], 1))(embed_sen)
convd_img = Conv2D(20, 1, activation="relu")(input_img)
cat_tenrs = Concatenate(axis=-1)([embed_sen, convd_img])
model.load_weights("best_weights.h5")
img = np.expand_dims(img_to_array(load_img("tony_stark.jpg")) / 255.0, axis=0)
sen = ascii_encode('Anthony Edward "Tony" Stark is a character portrayed by Robert Downey Jr. in the MCU film franchise', sentence_len)
y_img = encoder.predict([img, sen])
y_sen = decoder.predict(y_img)
dec_sen = ascii_decode(y_sen)