File size: 21,320 Bytes
0b2295a f02caca 0b2295a f02caca 0b2295a f02caca 0b2295a f02caca 0b2295a f02caca 0b2295a f02caca 0b2295a fd832fc 0b2295a fd832fc 0b2295a fd832fc 0b2295a fd832fc 0b2295a fd832fc 0b2295a fd832fc 0b2295a fd832fc 0b2295a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 |
/**
* Neural Network Tools and Utilities
* Provides helper functions for managing neural network layers,
* calculating parameters, and managing network architecture
*/
(function() {
// Layer counters to track unique IDs for each layer type
const layerCounters = {
'input': 0,
'hidden': 0,
'output': 0,
'conv': 0,
'pool': 0,
'linear': 0
};
// Default configuration templates for different layer types
const nodeConfigTemplates = {
'input': {
units: 784,
shape: [28, 28, 1],
batchSize: 32,
description: 'Input layer for raw data',
parameters: 0,
inputShape: null,
outputShape: [784]
},
'hidden': {
units: 128,
activation: 'relu',
useBias: true,
kernelInitializer: 'glorotUniform',
biasInitializer: 'zeros',
dropoutRate: 0.2,
description: 'Dense hidden layer with ReLU activation',
inputShape: null,
outputShape: null
},
'output': {
units: 10,
activation: 'softmax',
useBias: true,
kernelInitializer: 'glorotUniform',
biasInitializer: 'zeros',
description: 'Output layer with Softmax activation for classification',
inputShape: null,
outputShape: [10]
},
'conv': {
filters: 32,
kernelSize: [3, 3],
strides: [1, 1],
padding: 'valid',
activation: 'relu',
useBias: true,
kernelInitializer: 'glorotUniform',
biasInitializer: 'zeros',
description: 'Convolutional layer for feature extraction',
inputShape: null,
outputShape: null
},
'pool': {
poolSize: [2, 2],
strides: [2, 2],
padding: 'valid',
description: 'Max pooling layer for spatial downsampling',
inputShape: null,
outputShape: null
},
'linear': {
inputFeatures: 1,
outputFeatures: 1,
useBias: true,
activation: 'linear',
learningRate: 0.01,
optimizer: 'sgd',
lossFunction: 'mse',
biasInitializer: 'zeros',
kernelInitializer: 'glorotUniform',
description: 'Linear regression layer for numerical prediction',
inputShape: [1],
outputShape: [1]
}
};
// Mock data structure for sample datasets
const sampleData = {
'mnist': {
name: 'MNIST Handwritten Digits',
inputShape: [28, 28, 1],
numClasses: 10,
trainSamples: 60000,
testSamples: 10000,
description: 'Dataset of handwritten digits for classification'
},
'cifar10': {
name: 'CIFAR-10',
inputShape: [32, 32, 3],
numClasses: 10,
trainSamples: 50000,
testSamples: 10000,
description: 'Dataset of common objects like airplanes, cars, birds, etc.'
},
'fashion': {
name: 'Fashion MNIST',
inputShape: [28, 28, 1],
numClasses: 10,
trainSamples: 60000,
testSamples: 10000,
description: 'Dataset of fashion items like shirts, shoes, bags, etc.'
}
};
/**
* Get the next unique ID for a specific layer type
* @param {string} layerType - The type of the layer (input, hidden, output, conv, pool)
* @returns {string} - A unique ID for the layer
*/
function getNextLayerId(layerType) {
layerCounters[layerType]++;
return `${layerType}-${layerCounters[layerType]}`;
}
/**
* Reset all layer counters
* Used when clearing the canvas
*/
function resetLayerCounter() {
for (let key in layerCounters) {
layerCounters[key] = 0;
}
}
/**
* Create a configuration object for a layer
* @param {string} layerType - The type of the layer
* @param {Object} customConfig - Custom configuration for the layer
* @returns {Object} - Complete layer configuration
*/
function createNodeConfig(layerType, customConfig = {}) {
const baseConfig = { ...nodeConfigTemplates[layerType] };
// Merge custom config with base config
const config = { ...baseConfig, ...customConfig };
// Calculate parameters if not provided
if (config.parameters === undefined) {
config.parameters = calculateParameters(layerType, config);
}
return config;
}
/**
* Calculate parameters for a layer
* @param {string} layerType - The type of the layer
* @param {Object} config - Layer configuration
* @param {Object} prevLayerConfig - Configuration of the previous connected layer
* @returns {number} - Number of trainable parameters
*/
function calculateParameters(layerType, config, prevLayerConfig = null) {
let parameters = 0;
switch(layerType) {
case 'input':
parameters = 0; // Input layer has no trainable parameters
break;
case 'hidden':
if (prevLayerConfig) {
// Calculate input units from previous layer shape or units
let inputUnits;
if (prevLayerConfig.outputShape && Array.isArray(prevLayerConfig.outputShape)) {
inputUnits = prevLayerConfig.outputShape.reduce((a, b) => a * b, 1);
} else if (prevLayerConfig.units) {
inputUnits = prevLayerConfig.units;
} else if (prevLayerConfig.shape) {
inputUnits = prevLayerConfig.shape.reduce((a, b) => a * b, 1);
} else {
inputUnits = 784; // Default fallback
}
// Weight parameters: input_units * output_units
parameters = inputUnits * config.units;
// Add bias parameters if using bias
if (config.useBias) {
parameters += config.units;
}
}
break;
case 'output':
if (prevLayerConfig) {
// Calculate input units from previous layer
let inputUnits;
if (prevLayerConfig.outputShape && Array.isArray(prevLayerConfig.outputShape)) {
inputUnits = prevLayerConfig.outputShape.reduce((a, b) => a * b, 1);
} else if (prevLayerConfig.units) {
inputUnits = prevLayerConfig.units;
} else {
inputUnits = 128; // Default fallback
}
// Weight parameters: input_units * output_units
parameters = inputUnits * config.units;
// Add bias parameters if using bias
if (config.useBias) {
parameters += config.units;
}
}
break;
case 'conv':
if (prevLayerConfig) {
// Get input channels from previous layer
let inputChannels;
if (prevLayerConfig.outputShape && prevLayerConfig.outputShape.length > 2) {
inputChannels = prevLayerConfig.outputShape[2];
} else if (prevLayerConfig.shape && prevLayerConfig.shape.length > 2) {
inputChannels = prevLayerConfig.shape[2];
} else if (prevLayerConfig.filters) {
inputChannels = prevLayerConfig.filters;
} else {
inputChannels = 1; // Default fallback
}
// Weight parameters: kernel_height * kernel_width * input_channels * filters
const kernelSize = Array.isArray(config.kernelSize) ?
config.kernelSize[0] * config.kernelSize[1] :
config.kernelSize * config.kernelSize;
parameters = kernelSize * inputChannels * config.filters;
// Add bias parameters if using bias
if (config.useBias) {
parameters += config.filters;
}
// Calculate and store output shape
if (prevLayerConfig.shape || prevLayerConfig.outputShape) {
const inputShape = prevLayerConfig.outputShape || prevLayerConfig.shape;
const padding = config.padding === 'same' ? Math.floor(config.kernelSize[0] / 2) : 0;
const outputHeight = Math.floor((inputShape[0] - config.kernelSize[0] + 2 * padding) / config.strides[0]) + 1;
const outputWidth = Math.floor((inputShape[1] - config.kernelSize[1] + 2 * padding) / config.strides[1]) + 1;
config.outputShape = [outputHeight, outputWidth, config.filters];
}
}
break;
case 'pool':
parameters = 0; // Pooling layers have no trainable parameters
// Calculate and store output shape
if (prevLayerConfig && (prevLayerConfig.shape || prevLayerConfig.outputShape)) {
const inputShape = prevLayerConfig.outputShape || prevLayerConfig.shape;
const padding = config.padding === 'same' ? Math.floor(config.poolSize[0] / 2) : 0;
const outputHeight = Math.floor((inputShape[0] - config.poolSize[0] + 2 * padding) / config.strides[0]) + 1;
const outputWidth = Math.floor((inputShape[1] - config.poolSize[1] + 2 * padding) / config.strides[1]) + 1;
config.outputShape = [outputHeight, outputWidth, inputShape[2]];
}
break;
default:
parameters = 0;
}
return parameters;
}
/**
* Calculate FLOPs (floating point operations) for a layer
* @param {string} layerType - The type of the layer
* @param {Object} config - Layer configuration
* @param {Object} inputDims - Input dimensions
* @returns {number} - Approximate FLOPs for forward pass
*/
function calculateFLOPs(layerType, config, inputDims) {
let flops = 0;
switch(layerType) {
case 'input':
flops = 0;
break;
case 'hidden':
// FLOPs = 2 * input_dim * output_dim (multiply-add operations)
flops = 2 * inputDims.reduce((a, b) => a * b, 1) * config.units;
break;
case 'output':
// Same as hidden layer
flops = 2 * inputDims.reduce((a, b) => a * b, 1) * config.units;
break;
case 'conv':
// Output dimensions after convolution
const outputHeight = Math.floor((inputDims[0] - config.kernelSize[0] + 2 *
(config.padding === 'same' ? config.kernelSize[0] / 2 : 0)) /
config.strides[0] + 1);
const outputWidth = Math.floor((inputDims[1] - config.kernelSize[1] + 2 *
(config.padding === 'same' ? config.kernelSize[1] / 2 : 0)) /
config.strides[1] + 1);
// FLOPs per output point = 2 * kernel_height * kernel_width * input_channels
const flopsPerPoint = 2 * config.kernelSize[0] * config.kernelSize[1] * inputDims[2];
// Total FLOPs = output_points * flops_per_point * output_channels
flops = outputHeight * outputWidth * flopsPerPoint * config.filters;
break;
case 'pool':
// Output dimensions after pooling
const poolOutputHeight = Math.floor((inputDims[0] - config.poolSize[0]) /
config.strides[0] + 1);
const poolOutputWidth = Math.floor((inputDims[1] - config.poolSize[1]) /
config.strides[1] + 1);
// For max pooling, approximately one comparison per element in the pooling window
flops = poolOutputHeight * poolOutputWidth * inputDims[2] *
config.poolSize[0] * config.poolSize[1];
break;
default:
flops = 0;
}
return flops;
}
/**
* Calculate memory usage for a layer
* @param {string} layerType - The type of the layer
* @param {Object} config - Layer configuration
* @param {Object} batchSize - Batch size for calculation
* @returns {Object} - Memory usage statistics
*/
function calculateMemoryUsage(layerType, config, batchSize = 32) {
// Assume 4 bytes per parameter (float32)
const bytesPerParam = 4;
let outputShape = [];
let parameters = 0;
let activationMemory = 0;
switch(layerType) {
case 'input':
outputShape = config.shape || [28, 28, 1];
parameters = 0;
break;
case 'hidden':
outputShape = [config.units];
parameters = config.parameters || 0;
break;
case 'output':
outputShape = [config.units];
parameters = config.parameters || 0;
break;
case 'conv':
// This is a simplified calculation, actual dimensions depend on padding and strides
const inputShape = config.inputShape || [28, 28, 1];
const outputHeight = Math.floor((inputShape[0] - config.kernelSize[0] + 2 *
(config.padding === 'same' ? config.kernelSize[0] / 2 : 0)) /
config.strides[0] + 1);
const outputWidth = Math.floor((inputShape[1] - config.kernelSize[1] + 2 *
(config.padding === 'same' ? config.kernelSize[1] / 2 : 0)) /
config.strides[1] + 1);
outputShape = [outputHeight, outputWidth, config.filters];
parameters = config.parameters || 0;
break;
case 'pool':
const poolInputShape = config.inputShape || [28, 28, 32];
const poolOutputHeight = Math.floor((poolInputShape[0] - config.poolSize[0]) /
config.strides[0] + 1);
const poolOutputWidth = Math.floor((poolInputShape[1] - config.poolSize[1]) /
config.strides[1] + 1);
outputShape = [poolOutputHeight, poolOutputWidth, poolInputShape[2]];
parameters = 0;
break;
default:
outputShape = [0];
parameters = 0;
}
// Calculate memory for the activations (output of this layer)
activationMemory = batchSize * outputShape.reduce((a, b) => a * b, 1) * bytesPerParam;
// Calculate memory for the parameters
const paramMemory = parameters * bytesPerParam;
return {
parameters: parameters,
paramMemory: paramMemory, // in bytes
activationMemory: activationMemory, // in bytes
totalMemory: paramMemory + activationMemory, // in bytes
outputShape: outputShape
};
}
/**
* Generate a human-readable description of a layer
* @param {string} layerType - The type of the layer
* @param {Object} config - Layer configuration
* @returns {string} - Description of the layer
*/
function generateLayerDescription(layerType, config) {
let description = '';
switch(layerType) {
case 'input':
description = `Input Layer: Shape=${config.shape.join('×')}`;
break;
case 'hidden':
description = `Dense Layer: ${config.units} units, ${config.activation} activation`;
if (config.dropoutRate > 0) {
description += `, dropout ${config.dropoutRate}`;
}
break;
case 'output':
description = `Output Layer: ${config.units} units, ${config.activation} activation`;
break;
case 'conv':
description = `Conv2D: ${config.filters} filters, ${config.kernelSize.join('×')} kernel, ${config.activation} activation`;
break;
case 'pool':
description = `MaxPooling2D: ${config.poolSize.join('×')} pool size`;
break;
default:
description = 'Unknown layer type';
}
return description;
}
/**
* Validate a network architecture
* @param {Object} layers - Array of layer configurations
* @param {Object} connections - Array of connections between layers
* @returns {Object} - Validation result with errors if any
*/
function validateNetwork(layers, connections) {
const errors = [];
// Check if there's exactly one input layer
const inputLayers = layers.filter(layer => layer.type === 'input');
if (inputLayers.length === 0) {
errors.push('Network must have at least one input layer');
} else if (inputLayers.length > 1) {
errors.push('Network can have only one input layer');
}
// Check if there's at least one output layer
const outputLayers = layers.filter(layer => layer.type === 'output');
if (outputLayers.length === 0) {
errors.push('Network must have at least one output layer');
}
// Check for isolated nodes (nodes with no connections)
const connectedNodes = new Set();
connections.forEach(conn => {
connectedNodes.add(conn.source);
connectedNodes.add(conn.target);
});
const isolatedNodes = layers.filter(layer => !connectedNodes.has(layer.id));
if (isolatedNodes.length > 0) {
isolatedNodes.forEach(node => {
if (node.type !== 'input' && node.type !== 'output') {
errors.push(`Layer "${node.name}" (${node.id}) is isolated`);
}
});
}
// Check if input layer has incoming connections
inputLayers.forEach(layer => {
const incomingConnections = connections.filter(conn => conn.target === layer.id);
if (incomingConnections.length > 0) {
errors.push(`Input layer "${layer.name}" cannot have incoming connections`);
}
});
// Check if output layer has outgoing connections
outputLayers.forEach(layer => {
const outgoingConnections = connections.filter(conn => conn.source === layer.id);
if (outgoingConnections.length > 0) {
errors.push(`Output layer "${layer.name}" cannot have outgoing connections`);
}
});
return {
valid: errors.length === 0,
errors: errors
};
}
// Expose functions to the global scope
window.neuralNetwork = {
getNextLayerId,
resetLayerCounter,
createNodeConfig,
calculateParameters,
calculateFLOPs,
calculateMemoryUsage,
generateLayerDescription,
validateNetwork,
nodeConfigTemplates,
sampleData
};
})(); |