|
1 | | -import cv2 |
2 | | -import os |
3 | | -import matplotlib.pyplot as plt |
4 | | -import numpy as np |
5 | | -import tensorflow as tf |
6 | | -import time |
7 | | -import h5py |
8 | | -import sys |
9 | | -import glob |
10 | | - |
11 | | -IM_SHAPE = (64, 64, 3) |
12 | | - |
13 | | - |
14 | | -def plot_image_prediction(i, predictions_array, true_label, img): |
15 | | - predictions_array, true_label, img = predictions_array[i], true_label[i], img[i] |
16 | | - plt.grid(False) |
17 | | - plt.xticks([]) |
18 | | - plt.yticks([]) |
19 | | - |
20 | | - plt.imshow(np.squeeze(img), cmap=plt.cm.binary) |
21 | | - |
22 | | - predicted_label = np.argmax(predictions_array) |
23 | | - if predicted_label == true_label: |
24 | | - color = "blue" |
25 | | - else: |
26 | | - color = "red" |
27 | | - |
28 | | - plt.xlabel( |
29 | | - "{} {:2.0f}% ({})".format( |
30 | | - predicted_label, 100 * np.max(predictions_array), true_label |
31 | | - ), |
32 | | - color=color, |
33 | | - ) |
34 | | - |
35 | | - |
36 | | -def plot_value_prediction(i, predictions_array, true_label): |
37 | | - predictions_array, true_label = predictions_array[i], true_label[i] |
38 | | - plt.grid(False) |
39 | | - plt.xticks([]) |
40 | | - plt.yticks([]) |
41 | | - thisplot = plt.bar(range(10), predictions_array, color="#777777") |
42 | | - plt.ylim([0, 1]) |
43 | | - predicted_label = np.argmax(predictions_array) |
44 | | - |
45 | | - thisplot[predicted_label].set_color("red") |
46 | | - thisplot[true_label].set_color("blue") |
47 | | - |
48 | | - |
49 | | -class DatasetLoader(tf.keras.utils.Sequence): |
50 | | - def __init__(self, data_path, batch_size, training=True): |
51 | | - print("Opening {}".format(data_path)) |
52 | | - sys.stdout.flush() |
53 | | - |
54 | | - self.cache = h5py.File(data_path, "r") |
55 | | - |
56 | | - print("Loading data into memory...") |
57 | | - sys.stdout.flush() |
58 | | - self.images = self.cache["images"][:] |
59 | | - self.labels = self.cache["labels"][:].astype(np.float32) |
60 | | - self.image_dims = self.images.shape |
61 | | - |
62 | | - train_inds = np.arange(len(self.images)) |
63 | | - pos_train_inds = train_inds[self.labels[train_inds, 0] == 1.0] |
64 | | - neg_train_inds = train_inds[self.labels[train_inds, 0] != 1.0] |
65 | | - if training: |
66 | | - self.pos_train_inds = pos_train_inds[: int(0.8 * len(pos_train_inds))] |
67 | | - self.neg_train_inds = neg_train_inds[: int(0.8 * len(neg_train_inds))] |
68 | | - else: |
69 | | - self.pos_train_inds = pos_train_inds[-1 * int(0.2 * len(pos_train_inds)) :] |
70 | | - self.neg_train_inds = neg_train_inds[-1 * int(0.2 * len(neg_train_inds)) :] |
71 | | - |
72 | | - np.random.shuffle(self.pos_train_inds) |
73 | | - np.random.shuffle(self.neg_train_inds) |
74 | | - |
75 | | - self.train_inds = np.concatenate((self.pos_train_inds, self.neg_train_inds)) |
76 | | - self.batch_size = batch_size |
77 | | - self.p_pos = np.ones(self.pos_train_inds.shape) / len(self.pos_train_inds) |
78 | | - |
79 | | - def get_train_size(self): |
80 | | - return self.pos_train_inds.shape[0] + self.neg_train_inds.shape[0] |
81 | | - |
82 | | - def __len__(self): |
83 | | - return int(np.floor(self.get_train_size() / self.batch_size)) |
84 | | - |
85 | | - def __getitem__(self, index): |
86 | | - selected_pos_inds = np.random.choice( |
87 | | - self.pos_train_inds, size=self.batch_size // 2, replace=False, p=self.p_pos |
88 | | - ) |
89 | | - selected_neg_inds = np.random.choice( |
90 | | - self.neg_train_inds, size=self.batch_size // 2, replace=False |
| 1 | +from openai import OpenAI |
| 2 | + |
| 3 | +class LLMClient: |
| 4 | + def __init__(self, model: str, api_key: str, api_base: str = "https://openrouter.ai/api/v1"): |
| 5 | + self.llm_client = OpenAI(api_key=api_key, base_url=api_base) |
| 6 | + self.model = model |
| 7 | + |
| 8 | + def ask(self, user: str, system: str = None, **kwargs): |
| 9 | + messages = [{"role": "user", "content": user}] |
| 10 | + if system: |
| 11 | + messages.insert(0, {"role": "system", "content": system}) |
| 12 | + res = self.llm_client.chat.completions.create( |
| 13 | + model=self.model, |
| 14 | + messages=messages, |
| 15 | + **kwargs |
91 | 16 | ) |
92 | | - selected_inds = np.concatenate((selected_pos_inds, selected_neg_inds)) |
| 17 | + return res |
93 | 18 |
|
94 | | - sorted_inds = np.sort(selected_inds) |
95 | | - train_img = (self.images[sorted_inds] / 255.0).astype(np.float32) |
96 | | - train_label = self.labels[sorted_inds, ...] |
97 | | - return np.array(train_img), np.array(train_label) |
98 | 19 |
|
99 | | - def get_n_most_prob_faces(self, prob, n): |
100 | | - idx = np.argsort(prob)[::-1] |
101 | | - most_prob_inds = self.pos_train_inds[idx[: 10 * n : 10]] |
102 | | - return (self.images[most_prob_inds, ...] / 255.0).astype(np.float32) |
| 20 | +yoda_test_text = ( |
| 21 | + "Wisdom, sought by many, found by few, it is. Haste not, patience have. " |
| 22 | + "For in stillness, answers come. Much to learn, still you have. " |
| 23 | + "Fear leads to anger; anger, to hate. Down the dark path, guide you it will. " |
| 24 | + "Trust the Force, you must. Powerful ally it is. Life it creates, surrounds, binds. " |
| 25 | + "Adventure, excitement, a Jedi craves not these things. Discipline, balance, seek you should. " |
| 26 | + "Hmm, clearer now is the path, yes? Help you more, I can, if needed it is. " |
| 27 | + "Endless, the journey of learning is. Stay true to your path, and clarity you will find. " |
| 28 | + "Remember, the Force flows through all, but your heart determines how it shapes your destiny. " |
| 29 | + "Much more to teach, I have. Ready, are you? Mmm." |
| 30 | +) |
103 | 31 |
|
104 | | - def get_all_faces(self): |
105 | | - return (self.images[self.pos_train_inds] / 255.0).astype(np.float32) |
106 | 32 |
|
107 | | - def return_sample_batch(self): |
108 | | - return self.__getitem__(0) |
109 | 33 |
|
| 34 | +# class Llama(LLMClient): |
| 35 | +# def __init__(self, api_key: str): |
| 36 | +# """ |
| 37 | +# Initialize the LlamaFree model client. |
110 | 38 |
|
111 | | -def get_test_faces(): |
112 | | - cwd = os.path.dirname(__file__) |
113 | | - images = {"LF": [], "LM": [], "DF": [], "DM": []} |
114 | | - for key in images.keys(): |
115 | | - files = glob.glob(os.path.join(cwd, "data", "faces", key, "*.png")) |
116 | | - for file in sorted(files): |
117 | | - image = cv2.resize(cv2.imread(file), (64, 64))[:, :, ::-1] / 255.0 |
118 | | - images[key].append(image) |
| 39 | +# LlamaFree is available from LlamaFree. |
| 40 | +# Provide your LlamaFree API key (`api_key`) to access. |
| 41 | +# """ |
| 42 | +# # super().__init__(model="meta-llama/llama-3.2-3b-instruct", api_key=api_key) |
| 43 | +# super().__init__(model="meta-llama/llama-3.1-8b-instruct", api_key=api_key) |
119 | 44 |
|
120 | | - return images["LF"], images["LM"], images["DF"], images["DM"] |
121 | 45 |
|
| 46 | +# class LFM40B(LLMClient): |
| 47 | +# def __init__(self, api_key: str): |
| 48 | +# """ |
| 49 | +# Initialize the LFM-40B model client. |
122 | 50 |
|
123 | | -def plot_k(imgs, fname=None): |
124 | | - fig = plt.figure() |
125 | | - fig.subplots_adjust(hspace=0.6) |
126 | | - num_images = len(imgs) |
127 | | - for img in range(num_images): |
128 | | - ax = fig.add_subplot(int(num_images / 5), 5, img + 1) |
129 | | - ax.xaxis.set_visible(False) |
130 | | - ax.yaxis.set_visible(False) |
131 | | - img_to_show = imgs[img] |
132 | | - ax.imshow(img_to_show, interpolation="nearest") |
133 | | - plt.subplots_adjust(wspace=0.20, hspace=0.20) |
134 | | - plt.show() |
135 | | - if fname: |
136 | | - plt.savefig(fname) |
137 | | - plt.clf() |
138 | | - |
139 | | - |
140 | | -def plot_percentile(imgs, fname=None): |
141 | | - fig = plt.figure() |
142 | | - fig, axs = plt.subplots(1, len(imgs), figsize=(11, 8)) |
143 | | - for img in range(len(imgs)): |
144 | | - ax = axs[img] |
145 | | - ax.xaxis.set_visible(False) |
146 | | - ax.yaxis.set_visible(False) |
147 | | - img_to_show = imgs[img] |
148 | | - ax.imshow(img_to_show, interpolation="nearest") |
149 | | - if fname: |
150 | | - plt.savefig(fname) |
151 | | - |
152 | | - |
153 | | -def plot_accuracy_vs_risk(sorted_images, sorted_uncertainty, sorted_preds, plot_title): |
154 | | - num_percentile_intervals = 10 |
155 | | - num_samples = len(sorted_images) // num_percentile_intervals |
156 | | - all_imgs = [] |
157 | | - all_unc = [] |
158 | | - all_acc = [] |
159 | | - for percentile in range(num_percentile_intervals): |
160 | | - cur_imgs = sorted_images[ |
161 | | - percentile * num_samples : (percentile + 1) * num_samples |
162 | | - ] |
163 | | - cur_unc = sorted_uncertainty[ |
164 | | - percentile * num_samples : (percentile + 1) * num_samples |
165 | | - ] |
166 | | - cur_predictions = tf.nn.sigmoid( |
167 | | - sorted_preds[percentile * num_samples : (percentile + 1) * num_samples] |
168 | | - ) |
169 | | - avged_imgs = tf.reduce_mean(cur_imgs, axis=0) |
170 | | - all_imgs.append(avged_imgs) |
171 | | - all_unc.append(tf.reduce_mean(cur_unc)) |
172 | | - all_acc.append((np.ones((num_samples)) == np.rint(cur_predictions)).mean()) |
173 | | - |
174 | | - plt.plot(np.arange(num_percentile_intervals) * 10, all_acc) |
175 | | - plt.title(plot_title) |
176 | | - plt.show() |
177 | | - plt.clf() |
178 | | - return all_imgs |
| 51 | +# LFM-40B is available from Lambda Labs. |
| 52 | +# Provide your Lambda Labs API key (`api_key`) to access. |
| 53 | +# """ |
| 54 | +# api_base = "https://api.lambdalabs.com/v1" |
| 55 | +# super().__init__(model="lfm-40b", api_base=api_base, api_key=api_key) |
0 commit comments