Сделай токенизацию через natural и напиши весь исправленый код целиком вот мой код const…
- User
Сделай токенизацию через natural и напиши весь исправленый код целиком вот мой код const fs = require('fs').promises; const { GPU } = require('gpu.js'); const gpu = new GPU();
// Функции активации и их производные function relu(x) { return x > 0 ? x : 0; }
function reluDerivative(x) { return x > 0 ? 1 : 0; }
function softmax(arr) { const max = Math.max(...arr); const exps = arr.map(x => Math.exp(x - max)); const sum = exps.reduce((a, b) => a + b, 0); return exps.map(x => x / sum); } it=0; // Функция для токенизации предложения function tokenize(sentence) { it++; // Проверить, кратен ли it 10000 if (it % 10000 === 0) { process.stdout.write(
\rтокен: ${it}); // Перезаписываем текущее значение токена } return sentence .toLowerCase() .replace(/[.,!?]/g, '') // Удаление знаков препинания .split(' ') .filter(word => word); }// Функция для создания TF-IDF векторов class TfidfVectorizer { constructor(vocabulary) { this.vocabulary = vocabulary; this.idf = new Array(vocabulary.length).fill(0); }
fit(docs) { const docCount = docs.length; const termDocCounts = new Array(this.vocabulary.length).fill(0); docs.forEach(doc => { const tokens = new Set(tokenize(doc)); tokens.forEach(word => { let index = this.vocabulary.indexOf(word); if (index !== -1) termDocCounts[index]++; }); }); this.idf = this.vocabulary.map((word, idx) => { return Math.log((1 + docCount) / (1 + termDocCounts[idx])) + 1; }); } transform(doc) { let tf = new Array(this.vocabulary.length).fill(0); tokenize(doc).forEach(word => { let index = this.vocabulary.indexOf(word); if (index !== -1) { tf[index]++; } }); let tfidf = tf.map((termFreq, idx) => termFreq * this.idf[idx]); return tfidf; }}
// Инициализация нейронной сети с Adam-оптимизатором и использованием gpu.js class NeuralNetwork { constructor(input_nodes, hidden_nodes, output_nodes) { this.input_nodes = input_nodes; this.hidden_nodes = hidden_nodes; this.output_nodes = output_nodes;
this.weights_ih = this.initWeights(this.hidden_nodes, this.input_nodes); this.weights_ho = this.initWeights(this.output_nodes, this.hidden_nodes); this.bias_h = new Array(this.hidden_nodes).fill(0).map(() => Math.random() * 2 - 1); this.bias_o = new Array(this.output_nodes).fill(0).map(() => Math.random() * 2 - 1); this.learningRate = 0.001; this.beta1 = 0.9; this.beta2 = 0.999; this.epsilon = 1e-8; this.m_ih = this.initZeroes(this.hidden_nodes, this.input_nodes); this.v_ih = this.initZeroes(this.hidden_nodes, this.input_nodes); this.m_ho = this.initZeroes(this.output_nodes, this.hidden_nodes); this.v_ho = this.initZeroes(this.output_nodes, this.hidden_nodes); // Компиляция функций для ускорения на GPU this.gpuMultiply = gpu.createKernel(function(a, b, bias_h) { let sum = bias_h[this.thread.x]; for (let i = 0; i < this.constants.size; i++) { sum += a[i] * b[this.thread.x][i]; } return sum; }, { output: [this.hidden_nodes], constants: { size: this.input_nodes } }); this.gpuMultiplyOutput = gpu.createKernel(function(a, b, bias_o) { let sum = bias_o[this.thread.x]; for (let i = 0; i < this.constants.size; i++) { sum += a[i] * b[this.thread.x][i]; } return sum; }, { output: [this.output_nodes], constants: { size: this.hidden_nodes } }); } initWeights(rows, cols) { return new Array(rows).fill(0).map(() => new Array(cols).fill(0).map(() => (Math.random() * 2 - 1) * Math.sqrt(2 / (rows + cols))) ); } initZeroes(rows, cols) { return new Array(rows).fill(0).map(() => new Array(cols).fill(0)); } feedforward(input_array) { // Прямой проход с использованием GPU для ускорения let hidden_inputs = this.gpuMultiply(input_array, this.weights_ih, this.bias_h); let hidden_outputs = hidden_inputs.map(x => relu(x)); let final_inputs = this.gpuMultiplyOutput(hidden_outputs, this.weights_ho, this.bias_o); let final_outputs = softmax(final_inputs); return final_outputs; } train(input_array, target_array, t) { // Прямой проход let hidden_inputs = this.gpuMultiply(input_array, this.weights_ih, this.bias_h); let hidden_outputs = hidden_inputs.map(x => relu(x)); let final_inputs = this.gpuMultiplyOutput(hidden_outputs, this.weights_ho, this.bias_o); let final_outputs = softmax(final_inputs); // Обратное распространение ошибок let output_errors = final_outputs.map((output, i) => final_outputs[i] - target_array[i]); let hidden_errors = new Array(this.hidden_nodes).fill(0); for (let i = 0; i < this.output_nodes; i++) { for (let j = 0; j < this.hidden_nodes; j++) { hidden_errors[j] += this.weights_ho[i][j] * output_errors[i]; } } let gradients_ho = this.initZeroes(this.output_nodes, this.hidden_nodes); for (let i = 0; i < this.output_nodes; i++) { for (let j = 0; j < this.hidden_nodes; j++) { gradients_ho[i][j] = output_errors[i] * hidden_outputs[j]; } this.bias_o[i] -= this.learningRate * output_errors[i]; } let gradients_ih = this.initZeroes(this.hidden_nodes, this.input_nodes); for (let i = 0; i < this.hidden_nodes; i++) { let hidden_gradient = hidden_errors[i] * reluDerivative(hidden_inputs[i]); for (let j = 0; j < this.input_nodes; j++) { gradients_ih[i][j] = hidden_gradient * input_array[j]; } this.bias_h[i] -= this.learningRate * hidden_gradient; } this.updateWeights(this.weights_ho, gradients_ho, this.m_ho, this.v_ho, t); this.updateWeights(this.weights_ih, gradients_ih, this.m_ih, this.v_ih, t); } updateWeights(weights, gradients, m, v, t) { for (let i = 0; i < weights.length; i++) { for (let j = 0; j < weights[i].length; j++) { m[i][j] = this.beta1 * m[i][j] + (1 - this.beta1) * gradients[i][j]; v[i][j] = this.beta2 * v[i][j] + (1 - this.beta2) * gradients[i][j] ** 2; let m_hat = m[i][j] / (1 - Math.pow(this.beta1, t)); let v_hat = v[i][j] / (1 - Math.pow(this.beta2, t)); weights[i][j] -= this.learningRate * m_hat / (Math.sqrt(v_hat) + this.epsilon); } } } - Assistant