@webwriter/deep-learning-model 0.0.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/.github/workflows/main.yml +8 -0
  2. package/LICENSE +7 -0
  3. package/README.md +290 -0
  4. package/components/dataset-input/dataset-input.styles.ts +20 -0
  5. package/components/dataset-input/dataset-input.ts +196 -0
  6. package/components/inference-fields/class-input.ts +83 -0
  7. package/components/inference-fields/class-output.ts +62 -0
  8. package/components/inference-fields/image-input.ts +182 -0
  9. package/components/inference-fields/image.ts +82 -0
  10. package/components/inference-fields/inference-interfaces.ts +15 -0
  11. package/components/inference-fields/number-input.ts +62 -0
  12. package/components/inference-fields/number-output.ts +56 -0
  13. package/components/model-editor.ts +273 -0
  14. package/components/model-tests/bad-samples.ts +152 -0
  15. package/components/model-tests/loss-distribution.ts +174 -0
  16. package/components/reference-element-select.ts +105 -0
  17. package/custom-elements.json +1446 -0
  18. package/custom.d.ts +180 -0
  19. package/dist/widgets/webwriter-feature-engineering.css +444 -0
  20. package/dist/widgets/webwriter-feature-engineering.js +112241 -0
  21. package/dist/widgets/webwriter-model-designing.css +444 -0
  22. package/dist/widgets/webwriter-model-designing.js +113967 -0
  23. package/dist/widgets/webwriter-model-evaluation.css +444 -0
  24. package/dist/widgets/webwriter-model-evaluation.js +119019 -0
  25. package/dist/widgets/webwriter-model-prediction.css +444 -0
  26. package/dist/widgets/webwriter-model-prediction.js +109260 -0
  27. package/dist/widgets/webwriter-model-training.css +444 -0
  28. package/dist/widgets/webwriter-model-training.js +121391 -0
  29. package/editing-config.json +73 -0
  30. package/icon.svg +1 -0
  31. package/lib/dataset/class.ts +155 -0
  32. package/lib/dataset/dataset.ts +293 -0
  33. package/lib/dataset/feature.ts +110 -0
  34. package/lib/dataset/image.ts +312 -0
  35. package/lib/dataset/linear.ts +120 -0
  36. package/lib/layers/activation.ts +48 -0
  37. package/lib/layers/add.ts +50 -0
  38. package/lib/layers/attention.ts +74 -0
  39. package/lib/layers/concat.ts +50 -0
  40. package/lib/layers/conv.ts +83 -0
  41. package/lib/layers/dropout.ts +44 -0
  42. package/lib/layers/fcl.ts +66 -0
  43. package/lib/layers/flatten.ts +48 -0
  44. package/lib/layers/index.ts +708 -0
  45. package/lib/layers/input.ts +55 -0
  46. package/lib/layers/noise.ts +43 -0
  47. package/lib/layers/output.ts +64 -0
  48. package/lib/layers/reshape.ts +76 -0
  49. package/lib/layers/transposeconv.ts +90 -0
  50. package/lib/tflib.ts +6 -0
  51. package/lit-localize.json +47 -0
  52. package/localization/ar.xlf +532 -0
  53. package/localization/bg.xlf +531 -0
  54. package/localization/cs.xlf +532 -0
  55. package/localization/da.xlf +531 -0
  56. package/localization/de.xlf +531 -0
  57. package/localization/el.xlf +533 -0
  58. package/localization/es.xlf +532 -0
  59. package/localization/et.xlf +532 -0
  60. package/localization/fi.xlf +531 -0
  61. package/localization/fr.xlf +532 -0
  62. package/localization/generated/ar.ts +158 -0
  63. package/localization/generated/bg.ts +157 -0
  64. package/localization/generated/cs.ts +158 -0
  65. package/localization/generated/da.ts +157 -0
  66. package/localization/generated/de.ts +157 -0
  67. package/localization/generated/el.ts +159 -0
  68. package/localization/generated/es.ts +158 -0
  69. package/localization/generated/et.ts +158 -0
  70. package/localization/generated/fi.ts +157 -0
  71. package/localization/generated/fr.ts +158 -0
  72. package/localization/generated/hu.ts +157 -0
  73. package/localization/generated/id.ts +158 -0
  74. package/localization/generated/index.js +3 -0
  75. package/localization/generated/it.ts +158 -0
  76. package/localization/generated/ja.ts +157 -0
  77. package/localization/generated/ko.ts +157 -0
  78. package/localization/generated/locale-codes.js +83 -0
  79. package/localization/generated/lt.ts +157 -0
  80. package/localization/generated/lv.ts +157 -0
  81. package/localization/generated/nb.ts +157 -0
  82. package/localization/generated/nl.ts +157 -0
  83. package/localization/generated/pl.ts +158 -0
  84. package/localization/generated/pt-BR.ts +158 -0
  85. package/localization/generated/pt-PT.ts +158 -0
  86. package/localization/generated/ro.ts +158 -0
  87. package/localization/generated/ru.ts +158 -0
  88. package/localization/generated/sk.ts +158 -0
  89. package/localization/generated/sl.ts +158 -0
  90. package/localization/generated/sv.ts +157 -0
  91. package/localization/generated/tr.ts +157 -0
  92. package/localization/generated/uk.ts +157 -0
  93. package/localization/generated/zh-hans.ts +140 -0
  94. package/localization/generated/zh-hant.ts +140 -0
  95. package/localization/hu.xlf +531 -0
  96. package/localization/id.xlf +532 -0
  97. package/localization/it.xlf +532 -0
  98. package/localization/ja.xlf +531 -0
  99. package/localization/ko.xlf +531 -0
  100. package/localization/lt.xlf +531 -0
  101. package/localization/lv.xlf +531 -0
  102. package/localization/nb.xlf +531 -0
  103. package/localization/nl.xlf +531 -0
  104. package/localization/pkg/ar.xliff +7 -0
  105. package/localization/pkg/bg.xliff +7 -0
  106. package/localization/pkg/cs.xliff +7 -0
  107. package/localization/pkg/da.xliff +7 -0
  108. package/localization/pkg/de.xliff +7 -0
  109. package/localization/pkg/el.xliff +7 -0
  110. package/localization/pkg/es.xliff +7 -0
  111. package/localization/pkg/et.xliff +7 -0
  112. package/localization/pkg/fi.xliff +7 -0
  113. package/localization/pkg/fr.xliff +7 -0
  114. package/localization/pkg/hu.xliff +7 -0
  115. package/localization/pkg/id.xliff +7 -0
  116. package/localization/pkg/it.xliff +7 -0
  117. package/localization/pkg/ja.xliff +7 -0
  118. package/localization/pkg/ko.xliff +7 -0
  119. package/localization/pkg/lt.xliff +7 -0
  120. package/localization/pkg/lv.xliff +7 -0
  121. package/localization/pkg/nb.xliff +7 -0
  122. package/localization/pkg/nl.xliff +7 -0
  123. package/localization/pkg/pl.xliff +7 -0
  124. package/localization/pkg/pt-BR.xliff +7 -0
  125. package/localization/pkg/pt-PT.xliff +7 -0
  126. package/localization/pkg/ro.xliff +7 -0
  127. package/localization/pkg/ru.xliff +7 -0
  128. package/localization/pkg/sk.xliff +7 -0
  129. package/localization/pkg/sl.xliff +7 -0
  130. package/localization/pkg/sv.xliff +7 -0
  131. package/localization/pkg/tr.xliff +7 -0
  132. package/localization/pkg/uk.xliff +7 -0
  133. package/localization/pkg/zh-hans.xliff +7 -0
  134. package/localization/pkg/zh-hant.xliff +7 -0
  135. package/localization/pl.xlf +532 -0
  136. package/localization/pt-BR.xlf +532 -0
  137. package/localization/pt-PT.xlf +532 -0
  138. package/localization/ro.xlf +532 -0
  139. package/localization/ru.xlf +532 -0
  140. package/localization/sk.xlf +532 -0
  141. package/localization/sl.xlf +532 -0
  142. package/localization/snippets/ar.xliff +16 -0
  143. package/localization/snippets/bg.xliff +16 -0
  144. package/localization/snippets/cs.xliff +16 -0
  145. package/localization/snippets/da.xliff +16 -0
  146. package/localization/snippets/de.xliff +16 -0
  147. package/localization/snippets/el.xliff +16 -0
  148. package/localization/snippets/es.xliff +16 -0
  149. package/localization/snippets/et.xliff +16 -0
  150. package/localization/snippets/fi.xliff +16 -0
  151. package/localization/snippets/fr.xliff +16 -0
  152. package/localization/snippets/hu.xliff +16 -0
  153. package/localization/snippets/id.xliff +16 -0
  154. package/localization/snippets/it.xliff +16 -0
  155. package/localization/snippets/ja.xliff +16 -0
  156. package/localization/snippets/ko.xliff +16 -0
  157. package/localization/snippets/lt.xliff +16 -0
  158. package/localization/snippets/lv.xliff +16 -0
  159. package/localization/snippets/nb.xliff +16 -0
  160. package/localization/snippets/nl.xliff +16 -0
  161. package/localization/snippets/pl.xliff +16 -0
  162. package/localization/snippets/pt-BR.xliff +16 -0
  163. package/localization/snippets/pt-PT.xliff +16 -0
  164. package/localization/snippets/ro.xliff +16 -0
  165. package/localization/snippets/ru.xliff +16 -0
  166. package/localization/snippets/sk.xliff +16 -0
  167. package/localization/snippets/sl.xliff +16 -0
  168. package/localization/snippets/sv.xliff +16 -0
  169. package/localization/snippets/tr.xliff +16 -0
  170. package/localization/snippets/uk.xliff +16 -0
  171. package/localization/snippets/zh-hans.xliff +16 -0
  172. package/localization/snippets/zh-hant.xliff +16 -0
  173. package/localization/sv.xlf +531 -0
  174. package/localization/tr.xlf +531 -0
  175. package/localization/uk.xlf +531 -0
  176. package/localization/zh-hans.xlf +531 -0
  177. package/localization/zh-hant.xlf +531 -0
  178. package/package.json +104 -3
  179. package/snippets/MNIST.html +21 -0
  180. package/test.json +63 -0
  181. package/tsconfig.json +8 -0
  182. package/widgets/webwriter-feature-engineering.ts +421 -0
  183. package/widgets/webwriter-model-designing.ts +300 -0
  184. package/widgets/webwriter-model-evaluation.ts +215 -0
  185. package/widgets/webwriter-model-prediction.ts +307 -0
  186. package/widgets/webwriter-model-training.ts +684 -0
@@ -0,0 +1,312 @@
1
+ import { SlInput } from '@shoelace-style/shoelace';
2
+ import { html, TemplateResult } from "lit";
3
+ import { until } from 'lit/directives/until.js';
4
+ import { FeatureSettings, FeatureTransformation, NonEmptyArray } from './feature';
5
+ import { msg, str } from '@lit/localize';
6
+
7
+ import type * as TF from "@tensorflow/tfjs";
8
+ import getTF from "../../lib/tflib";
9
+ let tf: typeof TF;
10
+ (async () => {tf = await getTF()})()
11
+
12
+ /**
13
+ * This is the transformation from string values to an image
14
+ */
15
+ export default class ImageTransformation extends FeatureTransformation {
16
+ static {
17
+ this.registry.push({name: "Image Encoding", constructor:this});
18
+ }
19
+
20
+ private widthElement: SlInput;
21
+ private heightElement: SlInput;
22
+
23
+ /**
24
+ * The constructor runs through the samples and registers the unique classes.
25
+ */
26
+ public constructor(samples: Array<any>, settings: FeatureSettings) {
27
+ super("Image Encoding", samples, settings);
28
+
29
+ if (!this.settings.shema)
30
+ this.settings.shema = "binary";
31
+ if (!this.settings.width)
32
+ this.settings.width = 0;
33
+ if (!this.settings.height)
34
+ this.settings.height = 0;
35
+ if (!this.settings.transform)
36
+ this.settings.transform = "identity";
37
+
38
+ let that = this;
39
+ this.getRawImage(samples[0]).onload = function (e: Event) {
40
+ let img = e.target as HTMLImageElement;
41
+ if (that.settings.width == 0) {
42
+ that.settings.width = img.width;
43
+ if (that.widthElement) {
44
+ that.widthElement.value = String(img.width);
45
+ }
46
+ }
47
+
48
+ if (that.settings.height == 0) {
49
+ that.settings.height = img.height;
50
+ if (that.heightElement) {
51
+ that.heightElement.value = String(img.height);
52
+ that.heightElement.max = img.height;
53
+ }
54
+ }
55
+ if (that.widthElement && that.heightElement) {
56
+ that.widthElement.max = img.width;
57
+ that.heightElement.max = img.height;
58
+ }
59
+ }
60
+ }
61
+
62
+ public size() {
63
+ let channels = 3;
64
+ if (this.settings.transform == "grayscale")
65
+ channels = 1;
66
+ return [this.settings.width, this.settings.height, channels] as NonEmptyArray<number>;
67
+ }
68
+
69
+ public async transform(value: string | number[]): Promise<TF.Tensor3D> {
70
+ let bytes: Uint8Array;
71
+
72
+ if (typeof value == "string") {
73
+ if (value.trim().startsWith("[")) {
74
+ value = JSON.parse(value) as number[];
75
+ bytes = new Uint8Array(value);
76
+ } else {
77
+ const binaryString = atob(value);
78
+ bytes = new Uint8Array(binaryString.length);
79
+ for (let i = 0; i < binaryString.length; i++) {
80
+ bytes[i] = binaryString.charCodeAt(i);
81
+ }
82
+ }
83
+ } else {
84
+ bytes = new Uint8Array(value);
85
+ }
86
+
87
+ return await this.pngBinaryToTensor(bytes, this.settings.width, this.settings.height);
88
+ }
89
+
90
+ public getInputElement(id:string): TemplateResult {
91
+ return html`<drawing-canvas id=${id} width=${this.settings.width} height=${this.settings.height}></drawing-canvas>`
92
+ }
93
+
94
+ public getOutputElement(id:string): TemplateResult {
95
+ return html`<tensor-image id=${id}></tensor-image>`
96
+ }
97
+
98
+ public async inverse(tensor: TF.Tensor3D): Promise<string> {
99
+ const [height, width, channels] = tensor.shape;
100
+ if (channels !== 3 && channels !== 4) {
101
+ throw new Error('Tensor must have 3 (RGB) or 4 (RGBA) channels');
102
+ }
103
+
104
+ const data = await tensor.data();
105
+ const imageDataArray = new Uint8ClampedArray(width * height * 4);
106
+ for (let i = 0; i < width * height; i++) {
107
+ imageDataArray[i * 4 + 0] = (data[i * channels + 0] || 0) * 255; // R
108
+ imageDataArray[i * 4 + 1] = (data[i * channels + 1] || 0) * 255; // G
109
+ imageDataArray[i * 4 + 2] = (data[i * channels + 2] || 0) * 255 // B
110
+ imageDataArray[i * 4 + 3] = (channels === 4 ? data[i * channels + 3] : 1) * 255 // A
111
+ }
112
+
113
+ const canvas = document.createElement('canvas');
114
+ canvas.width = width;
115
+ canvas.height = height;
116
+ const ctx = canvas.getContext('2d');
117
+ const imageData = new ImageData(imageDataArray, width, height);
118
+ ctx.putImageData(imageData, 0, 0);
119
+
120
+ return new Promise((resolve) => {
121
+ canvas.toBlob((blob) => {
122
+ const reader = new FileReader();
123
+ reader.onloadend = () => {
124
+ const base64 = reader.result.toString().split(',')[1];
125
+ const binary = atob(base64);
126
+ resolve(binary);
127
+ };
128
+ reader.readAsDataURL(blob);
129
+ }, 'image/png');
130
+ });
131
+ }
132
+
133
+ async pngBinaryToTensor(pngBinary, targetWidth, targetHeight) {
134
+ let blob = new Blob([pngBinary], { type: 'image/png' });
135
+ let bitmap = await createImageBitmap(blob);
136
+
137
+ let tensor = tf.tidy(() => {
138
+ let img = tf.browser.fromPixels(bitmap)
139
+ .resizeBilinear([targetWidth, targetHeight])
140
+ .toFloat()
141
+ .div<TF.Tensor3D>(tf.scalar(255));
142
+ if (this.settings.transform == "grayscale")
143
+ img = tf.image.rgbToGrayscale(img);
144
+ return img;
145
+ });
146
+
147
+ return tensor as TF.Tensor3D;
148
+ }
149
+
150
+ private transformImage(img: HTMLImageElement, width: number, height: number) {
151
+ let canvas = document.createElement('canvas');
152
+ canvas.width = width;
153
+ canvas.height = height;
154
+
155
+ let ctx = canvas.getContext('2d');
156
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
157
+
158
+ if (this.settings.transform == "grayscale") {
159
+ let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
160
+ let data = imageData.data;
161
+ for (let i = 0; i < data.length; i += 4) {
162
+ let r = data[i];
163
+ let g = data[i + 1];
164
+ let b = data[i + 2];
165
+ let gray = 0.3 * r + 0.59 * g + 0.11 * b;
166
+
167
+ data[i] = data[i + 1] = data[i + 2] = gray;
168
+ }
169
+
170
+ ctx.putImageData(imageData, 0, 0);
171
+ }
172
+
173
+ let outImg = document.createElement("img");
174
+ outImg.src = canvas.toDataURL();
175
+ return outImg;
176
+ }
177
+
178
+ public getSettingElement(changeCallback, editMode:string): TemplateResult {
179
+ let that = this;
180
+ function typechange(e: Event) {
181
+ let element = e.target as HTMLInputElement;
182
+ let value: string | number = element.value;
183
+ if (element.type == "number")
184
+ value = parseFloat(value);
185
+ that.settings[element.name] = value;
186
+ changeCallback(that.settings);
187
+ }
188
+
189
+ //This is needed because the global sl-input class is broken...
190
+ this.widthElement = document.createElement("sl-input");
191
+ this.widthElement.type = "number"
192
+ this.widthElement.label = msg("Width");
193
+ this.widthElement.value = this.settings.width;
194
+ this.widthElement.addEventListener("sl-change", typechange);
195
+ this.widthElement.max = this.settings.width;
196
+ this.widthElement.min = 1;
197
+ this.widthElement.name = "width";
198
+ this.widthElement.disabled = editMode == "read"
199
+
200
+ this.heightElement = document.createElement("sl-input");
201
+ this.heightElement.type = "number"
202
+ this.heightElement.label = msg("Height");
203
+ this.heightElement.value = this.settings.height;
204
+ this.heightElement.addEventListener("sl-change", typechange);
205
+ this.heightElement.max = this.settings.height;
206
+ this.heightElement.min = 1;
207
+ this.heightElement.name = "height";
208
+ this.heightElement.disabled = editMode == "read"
209
+
210
+ return html`
211
+ <sl-select name="shema" value=${this.settings.shema} @sl-change=${typechange} label=${msg("Import Format")} ?disabled=${editMode == "read"}>
212
+ <sl-option value="binary">${msg("Binary String")}</sl-option>
213
+ <sl-option value="base64">${msg("Base64 String")}</sl-option>
214
+ </sl-select>
215
+ ${this.widthElement}${this.heightElement}
216
+ <sl-select name="transform" value=${this.settings.transform} @sl-change=${typechange} label=${msg("Image Pre-Processing")} ?disabled=${editMode == "read"}>
217
+ <sl-option value="identity">${msg("Identity")}</sl-option>
218
+ <sl-option value="grayscale">${msg("Grayscale")}</sl-option>
219
+ </sl-select>`;
220
+ }
221
+
222
+ public async getImage(value: string | number[]): Promise<HTMLImageElement> {
223
+ let img = this.getRawImage(value);
224
+ await (new Promise(function (res, rej) {
225
+ img.onload = res;
226
+ }))
227
+ let scaled = this.transformImage(img, this.settings.width, this.settings.height);
228
+ return scaled;
229
+ }
230
+
231
+ public getRawImage(value: string | number[]): HTMLImageElement {
232
+ let bytes: Uint8Array;
233
+
234
+ if (typeof value == "string") {
235
+ if (value.trim().startsWith("[")) {
236
+ const parsedValue = JSON.parse(value) as number[];
237
+ bytes = new Uint8Array(parsedValue);
238
+ } else {
239
+ const binaryString = atob(value);
240
+ bytes = new Uint8Array(binaryString.length);
241
+ for (let i = 0; i < binaryString.length; i++) {
242
+ bytes[i] = binaryString.charCodeAt(i);
243
+ }
244
+ }
245
+ } else {
246
+ bytes = new Uint8Array(value);
247
+ }
248
+
249
+ let blob = new Blob([bytes as any], { type: 'image/png' });
250
+ let imageUrl = URL.createObjectURL(blob);
251
+ let img = new Image();
252
+ img.src = imageUrl;
253
+ return img;
254
+ }
255
+
256
+ private async waitUntilImageDimensionsAvailable() {
257
+ let that = this;
258
+ return new Promise(function (res, rej) {
259
+ let inter = setInterval(function () {
260
+ if (that.settings.width != 0 && that.settings.height != 0) {
261
+ clearInterval(inter);
262
+ res(null);
263
+ }
264
+ }, 10);
265
+ })
266
+ }
267
+
268
+ public renderPredictionDifference(pred:TF.Tensor3D, label:TF.Tensor3D) {
269
+ return html`${until((async () => {
270
+ let predValue = this.renderTransformedValue(await this.inverse(pred));
271
+ let labelValue = this.renderTransformedValue(await this.inverse(label));
272
+ return html`${msg(str`Prediction: ${predValue}, Label: ${labelValue}`)}`;
273
+ })(), html`${msg("Visualizing Difference...")}`)}`;
274
+ }
275
+
276
+ public renderTransformedValue(value: string | number[]): TemplateResult {
277
+ return html`${until(
278
+ (async () => {
279
+ await this.waitUntilImageDimensionsAvailable();
280
+ let img = await this.getImage(value);
281
+ return img;
282
+ })(),
283
+ html`${msg("Loading image")}`)
284
+ }`;
285
+ }
286
+
287
+ public renderOriginalValue(value: string | number[]): string {
288
+ if (typeof value == "string") {
289
+ if (value.trim().startsWith("[")) {
290
+ // Old format: already in array string format
291
+ return value;
292
+ } else {
293
+ // New format: base64 string
294
+ const binaryString = atob(value);
295
+ const bytes = new Uint8Array(binaryString.length);
296
+ for (let i = 0; i < binaryString.length; i++) {
297
+ bytes[i] = binaryString.charCodeAt(i);
298
+ }
299
+ // Show only first 9 and last 3 bytes for readability
300
+ const byteArray = Array.from(bytes);
301
+ if (byteArray.length > 20) {
302
+ const first = byteArray.slice(0, 9);
303
+ const last = byteArray.slice(-3);
304
+ return `[${first.join(', ')}, ..., ${last.join(', ')}]`;
305
+ }
306
+ return JSON.stringify(byteArray);
307
+ }
308
+ } else {
309
+ return JSON.stringify(value);
310
+ }
311
+ }
312
+ }
@@ -0,0 +1,120 @@
1
+ import { SlSelect } from '@shoelace-style/shoelace';
2
+ import { html, TemplateResult } from "lit";
3
+ import { msg, str } from "@lit/localize";
4
+ import { until } from 'lit/directives/until.js';
5
+ import { FeatureSettings, FeatureTransformation, NonEmptyArray } from './feature';
6
+
7
+ import type * as TF from "@tensorflow/tfjs";
8
+ import getTF from "../../lib/tflib";
9
+ let tf: typeof TF;
10
+ (async () => {tf = await getTF()})()
11
+
12
+ /**
13
+ * This is the transformation from string values to a class encoding
14
+ */
15
+ export default class LinearTransformation extends FeatureTransformation {
16
+ static {
17
+ this.registry.push({name: "Number Encoding", constructor:this});
18
+ }
19
+
20
+ /**
21
+ * The constructor runs through the samples and registers the unique classes.
22
+ */
23
+ public constructor(samples: Array<string>, settings: FeatureSettings) {
24
+ super("Number Encoding", samples, settings);
25
+ if (isNaN(parseFloat(samples[0])))
26
+ throw new Error("number transformation contained invalid numbers")
27
+
28
+ if (!this.settings.type)
29
+ this.settings.type = "linear";
30
+
31
+ this.aggrigatedInformation.max = parseFloat(samples[0]);
32
+ this.aggrigatedInformation.min = parseFloat(samples[0]);
33
+ for (let sample of samples) {
34
+ let number = parseFloat(sample);
35
+ if (isNaN(number))
36
+ throw new Error("number transformation contained invalid numbers")
37
+
38
+ let min = this.aggrigatedInformation.min;
39
+ let max = this.aggrigatedInformation.max;
40
+ if (number > max)
41
+ this.aggrigatedInformation.max = number;
42
+ if (number < min)
43
+ this.aggrigatedInformation.min = number;
44
+ }
45
+ if (this.aggrigatedInformation.min - this.aggrigatedInformation.max == 0)
46
+ throw new Error("the provided values are all the same and thus do not offer any information")
47
+ }
48
+
49
+ public size() {
50
+ return [1] as NonEmptyArray<number>;
51
+ }
52
+
53
+ public async transform(value: string): Promise<TF.Tensor1D> {
54
+ if (typeof value == "string")
55
+ value = JSON.parse(value);
56
+ let min = this.aggrigatedInformation.min;
57
+ let max = this.aggrigatedInformation.max;
58
+ let tensor = new Array<number>(1)
59
+ let number = parseFloat(value);
60
+ if (isNaN(number))
61
+ throw new Error("number transformation contained invalid numbers")
62
+
63
+ if (this.settings.type == "linear")
64
+ tensor[0] = (number - min) / (max - min)
65
+ if (this.settings.type == "exp")
66
+ tensor[0] = Math.log(((number - min) / (max - min)) * (Math.E - 1) + 1)
67
+ if (this.settings.type == "quad")
68
+ tensor[0] = Math.sqrt((number - min) / (max - min))
69
+ return tf.tensor(tensor);
70
+ }
71
+
72
+ public async inverse(tensor: TF.Tensor): Promise<string> {
73
+ let min = this.aggrigatedInformation.min;
74
+ let max = this.aggrigatedInformation.max;
75
+
76
+ let base = tensor.arraySync() as number;
77
+ if (this.settings.type == "exp")
78
+ base = (Math.exp(base) - 1) / (Math.E - 1);
79
+ if (this.settings.type == "quad")
80
+ base = Math.pow(base, 2);
81
+
82
+ return String((base * (max - min) + min))
83
+ }
84
+
85
+ public getInputElement(id: string): TemplateResult {
86
+ return html`<number-input id=${id}></number-input>`
87
+ }
88
+ public getOutputElement(id: string): TemplateResult {
89
+ return html`<number-output id=${id}></number-output>`
90
+ }
91
+
92
+ public renderPredictionDifference(pred:TF.Tensor1D, label:TF.Tensor1D) {
93
+ return html`${until((async () => {
94
+ let predValue = await this.inverse(pred);
95
+ let labelValue = await this.inverse(label);
96
+ return html`${msg(str`Prediction: ${predValue} - Label: ${labelValue} = Delta: ${parseFloat(predValue) - parseFloat(labelValue)}`)}`;
97
+ })(), html`${msg("Visualizing Difference...")}`)}`;
98
+ }
99
+
100
+ public getSettingElement(changeCallback): TemplateResult {
101
+ let that = this;
102
+ function typechange(e: Event) {
103
+ let element = e.target as SlSelect;
104
+ let type = element.value;
105
+ that.settings.type = type;
106
+ changeCallback(that.settings);
107
+ }
108
+ return html`
109
+ <sl-select label=${msg("Value Scale")} @sl-change=${typechange} value=${this.settings.type}>
110
+ <sl-option value="linear">${msg("Linear")}</sl-option>
111
+ <sl-option value="exp">${msg("Exponential")}</sl-option>
112
+ <sl-option value="quad">${msg("Quadratic")}</sl-option>
113
+ </sl-select>`
114
+ }
115
+
116
+ public renderTransformedValue(value: string): TemplateResult {
117
+ return html`${until(
118
+ (async () => { return (await this.transform(value)).arraySync()[0].toFixed(3) })(), html`${msg("Loading")}`)}`;
119
+ }
120
+ }
@@ -0,0 +1,48 @@
1
+ import { SlSelect } from "@shoelace-style/shoelace";
2
+ import { TransformedDataset } from '../dataset/dataset';
3
+ import { Editor, Layer, SIZE_SEP } from "./index";
4
+ import { msg } from "@lit/localize";
5
+
6
+ import type * as TF from "@tensorflow/tfjs";
7
+ import getTF from "../../lib/tflib";
8
+ let tf: typeof TF;
9
+ (async () => {tf = await getTF()})()
10
+
11
+ type ActivationIdentifier = 'elu'|'hardSigmoid'|'linear'|'relu'|'relu6'|'selu'|'sigmoid'|'softmax'|'softplus'|'softsign'|'tanh'|'swish'|'mish'|'gelu'|'gelu_new';
12
+
13
+ export class ExportLayer extends Layer {
14
+ private typeSelect: SlSelect;
15
+
16
+ constructor(fields: TransformedDataset, editor: Editor) {
17
+ super(1, 1, "Activation", editor)
18
+
19
+ this.typeSelect = this.addSelect(msg("Function"), ["Identity", "relu", "tanh", "sigmoid", "Softmax", "normalize"])
20
+ this.typeSelect.value = "relu";
21
+ }
22
+ update() {
23
+ this.updateInputLabels();
24
+ this.getNodeOutputElement("output_1").innerText = this.getNodeInputElement("input_1").innerText;
25
+ this.notifyOutputChange();
26
+ }
27
+ getState() {
28
+ let state = super.getState();
29
+ state.type = "activation";
30
+ state.dim = this.getNodeInputElement("input_1").innerText.split(SIZE_SEP).map(v => parseInt(v));
31
+ state.act = this.typeSelect.value;
32
+ return state;
33
+ }
34
+ setState(state) {
35
+ super.setState(state);
36
+ this.typeSelect.value = state.act;
37
+ }
38
+ public forward(inputs: Record<string, TF.SymbolicTensor>): Record<string, TF.SymbolicTensor> {
39
+ if (this.typeSelect.value == "Identity")
40
+ return { output_1: inputs.input_1};
41
+ else if (this.typeSelect.value == "normalize")
42
+ return { output_1: tf.layers.layerNormalization().apply(inputs.input_1) as TF.SymbolicTensor};
43
+ else return { output_1: tf.layers.activation({ activation: this.typeSelect.value as ActivationIdentifier}).apply(inputs.input_1) as TF.SymbolicTensor };
44
+ }
45
+ protected getDisplayName(): string {
46
+ return msg("Activation");
47
+ }
48
+ }
@@ -0,0 +1,50 @@
1
+ import { TransformedDataset } from '../dataset/dataset';
2
+ import { DynamicInputLayer, Editor, SIZE_SEP } from "./index";
3
+ import { msg } from '@lit/localize';
4
+
5
+ import type * as TF from "@tensorflow/tfjs";
6
+ import getTF from "../../lib/tflib";
7
+ let tf: typeof TF;
8
+ (async () => {tf = await getTF()})()
9
+
10
+ type NonEmptyArray<T> = [T, ...T[]];
11
+
12
+ export class ExportLayer extends DynamicInputLayer {
13
+ constructor(fields: TransformedDataset, editor: Editor) {
14
+ super(1, "Elementwise Add", editor)
15
+ }
16
+ getOutputDim() {
17
+ let out = (this.getNodeInputElements()[0] as HTMLElement).innerText.split(SIZE_SEP).map(v => parseInt(v));
18
+ let i = 1;
19
+ for (let input of this.getNodeInputElements()) {
20
+ this.getNode().inputs
21
+ if (i >= Object.keys(this.getNode().inputs).length)
22
+ break;
23
+ (input as HTMLElement).innerHTML = out.join(SIZE_SEP);
24
+ i++;
25
+ }
26
+ if (out.length == 0)
27
+ out = [0];
28
+ return [out as NonEmptyArray<number>];
29
+ }
30
+ update() {
31
+ super.update();
32
+ this.checkInputs();
33
+ }
34
+ getState() {
35
+ let state = super.getState();
36
+ state.type = "add";
37
+ return state;
38
+ }
39
+ setState(state) {
40
+ super.setState(state);
41
+ }
42
+ public forward(inputs: Record<string, TF.SymbolicTensor>): Record<string, TF.SymbolicTensor> {
43
+ if (Object.keys(inputs).length == 1)
44
+ return { output_1: inputs.input_1 as TF.SymbolicTensor }
45
+ return { output_1: tf.layers.add().apply(Object.values(inputs)) as TF.SymbolicTensor };
46
+ }
47
+ protected getDisplayName(): string {
48
+ return msg("Elementwise Add");
49
+ }
50
+ }
@@ -0,0 +1,74 @@
1
+ import { TransformedDataset } from '../dataset/dataset';
2
+ import { Editor, Layer, SIZE_SEP } from "./index";
3
+ import { msg } from '@lit/localize';
4
+
5
+ import type * as TF from "@tensorflow/tfjs";
6
+ import getTF from "../../lib/tflib";
7
+ let tf: typeof TF;
8
+
9
+ let AttentionLayer;
10
+ (async () => {
11
+ tf = await getTF()
12
+
13
+ function scaledDotProductAttention(q, k, v, mask = null) {
14
+ const matmulQK = tf.matMul(q, k, false, true);
15
+ const dk = tf.scalar(q.shape[q.shape.length - 1], 'float32');
16
+ const scaledScores = tf.div(matmulQK, tf.sqrt(dk));
17
+
18
+ if (mask !== null) {
19
+ const NEG_INF = tf.scalar(-1e9);
20
+ const maskedScores = scaledScores.add(mask.mul(NEG_INF));
21
+ return tf.softmax(maskedScores, -1).matMul(v); // Weighted sum
22
+ }
23
+
24
+ const attentionWeights = tf.softmax(scaledScores, -1);
25
+ const output = tf.matMul(attentionWeights, v);
26
+
27
+ return output;
28
+ }
29
+
30
+ AttentionLayer = class AttentionLayer extends tf.layers.Layer {
31
+ static className = 'AttentionLayer'
32
+
33
+ constructor(config) {
34
+ super(config);
35
+ this.supportsMasking = true;
36
+ }
37
+
38
+ call(inputs, kwargs) {
39
+ const [q, k, v] = inputs;
40
+ return scaledDotProductAttention(q, k, v);
41
+ }
42
+
43
+ computeOutputShape(inputShape) {
44
+ return inputShape[0];
45
+ }
46
+ }
47
+ tf.serialization.registerClass(AttentionLayer);
48
+ })()
49
+
50
+ export class ExportLayer extends Layer {
51
+ constructor(fields: TransformedDataset, editor: Editor) {
52
+ super(3, 1, "Attention", editor)
53
+ }
54
+ update() {
55
+ this.updateInputLabels();
56
+ let inputs = [...this.getNodeInputElements()].map(input => (input as HTMLElement).innerText.split(SIZE_SEP).map(s => parseInt(s)));
57
+ this.getNodeOutputElement("output_1").innerText = [inputs[0][0], inputs[2][1]].join(SIZE_SEP)
58
+ this.notifyOutputChange();
59
+ }
60
+ getState() {
61
+ let state = super.getState();
62
+ state.type = "attention";
63
+ return state;
64
+ }
65
+ setState(state) {
66
+ super.setState(state);
67
+ }
68
+ public forward(inputs: Record<string, TF.SymbolicTensor>): Record<string, TF.SymbolicTensor> {
69
+ return { output_1: new AttentionLayer({}).apply(Object.values(inputs)) as TF.SymbolicTensor };
70
+ }
71
+ protected getDisplayName(): string {
72
+ return msg("Attention");
73
+ }
74
+ }
@@ -0,0 +1,50 @@
1
+ import { TransformedDataset } from '../dataset/dataset';
2
+ import { DynamicInputLayer, Editor, SIZE_SEP } from "./index";
3
+ import { msg } from '@lit/localize';
4
+
5
+ import type * as TF from "@tensorflow/tfjs";
6
+ import getTF from "../../lib/tflib";
7
+ let tf: typeof TF;
8
+ (async () => {tf = await getTF()})()
9
+
10
+ type NonEmptyArray<T> = [T, ...T[]];
11
+
12
+ export class ExportLayer extends DynamicInputLayer {
13
+ constructor(fields: TransformedDataset, editor: Editor) {
14
+ super(1, "Concatenation", editor)
15
+ }
16
+ getOutputDim() {
17
+ let out: NonEmptyArray<number> = [0]
18
+ for (let input of this.getNodeInputElements()) {
19
+ if ((input as HTMLElement).innerText != "") {
20
+ let dims = (input as HTMLElement).innerText.split(SIZE_SEP).map(v => parseInt(v))
21
+ dims = dims.filter(d => !isNaN(d));
22
+ let valid = out.length == dims.length;
23
+ for (let d = 0; d < dims.length - 1; d++) {
24
+ if (out[d] != dims[d])
25
+ valid = false;
26
+ }
27
+ if (valid) {
28
+ out[out.length - 1] += dims[out.length - 1];
29
+ } else {
30
+ (input as HTMLElement).innerText = out.join(SIZE_SEP);
31
+ }
32
+ }
33
+ }
34
+ return [out];
35
+ }
36
+ getState() {
37
+ let state = super.getState();
38
+ state.type = "concat";
39
+ return state;
40
+ }
41
+ setState(state) {
42
+ super.setState(state);
43
+ }
44
+ public forward(inputs: Record<string, TF.SymbolicTensor>): Record<string, TF.SymbolicTensor> {
45
+ return { output_1: tf.layers.concatenate().apply(Object.values(inputs)) as TF.SymbolicTensor };
46
+ }
47
+ protected getDisplayName(): string {
48
+ return msg("Concatenation");
49
+ }
50
+ }