привет
- User
привет
- Assistant
Привет! Чем могу помочь? 😊
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
привет
Привет! Чем могу помочь? 😊
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
улучши код не используя другие библиотеки , обнови подходы, используй библиотеку matchjs const fs = require('fs').promises; const readline = require('readline'); const { GPU } = require('gpu.js');
// Создаем GPU экземпляр const gpu = new GPU();
// Функции активации (GPU-совместимые) const relu = (x) => (x > 0 ? x : 0); const reluDerivative = (x) => (x > 0 ? 1 : 0); const 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); };
// Токенизация const tokenize = (sentence) => sentence.toLowerCase().replace(/[.,!?[]]/g, '').split(' ').filter(Boolean);
// TF-IDF векторизатор class TfidfVectorizer { constructor(vocabulary = []) { this.vocabulary = vocabulary; this.idf = new Array(this.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) => {
const index = this.vocabulary.indexOf(word);
if (index !== -1) termDocCounts[index]++;
});
});
this.idf = this.vocabulary.map(
(_, idx) => Math.log((1 + docCount) / (1 + termDocCounts[idx])) + 1
);
}
updateVocabulary(newDocs) {
const newWords = new Set();
newDocs.forEach((doc) => {
tokenize(doc).forEach((word) => newWords.add(word));
});
newWords.forEach((word) => {
if (!this.vocabulary.includes(word)) {
this.vocabulary.push(word);
this.idf.push(0); // Временно добавляем 0, перерасчет позже
}
});
}
transform(doc) {
const tf = new Array(this.vocabulary.length).fill(0);
tokenize(doc).forEach((word) => {
const index = this.vocabulary.indexOf(word);
if (index !== -1) tf[index]++;
});
return tf.map((termFreq, idx) => termFreq * this.idf[idx]);
}
recalculateIdf(allDocs) {
const docCount = allDocs.length;
const termDocCounts = new Array(this.vocabulary.length).fill(0);
allDocs.forEach((doc) => {
const tokens = new Set(tokenize(doc));
tokens.forEach((word) => {
const index = this.vocabulary.indexOf(word);
if (index !== -1) termDocCounts[index]++;
});
});
this.idf = this.vocabulary.map(
(_, idx) => Math.log((1 + docCount) / (1 + termDocCounts[idx])) + 1
);
}
}
// Нейронная сеть 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(hidden_nodes, input_nodes); this.weights_ho = this.initWeights(output_nodes, hidden_nodes); this.bias_h = new Array(hidden_nodes).fill(0).map(() => Math.random() * 2 - 1); this.bias_o = new Array(output_nodes).fill(0).map(() => Math.random() * 2 - 1); this.learningRate = 0.001; }
}
(async () => { const modelPath = 'model.json'; const vectorizerPath = 'vectorizer.json'; const dataPath = 'bd.json'; let nn, vectorizer, indexToAnswer, answerToIndex, allDocs;
})();
Ваш код уже достаточно функционален, и он решает важную задачу построения нейронной сети для обработки текстовых данных. Однако есть нюансы, которые могут сделать его более читаемым, удобным, и улучшить производительность.
Предполагая, что вам нужно сохранить прежний функционал, использовать только текущие библиотеки (например, исключая внедрение библиотек вроде TensorFlow.js или других улучшений), я оптимизирую только определенные аспекты кода. К тому же, поскольку вы хотите использовать библиотеку matchjs, я обновлю подход так, чтобы структура становилась более инновационной и в то же время использовала преимущества функционального программирования.
Вот основные шаги улучшения:
matchjs: Добавим использование для сопоставления данных.softmax.const fs = require('fs').promises;
const readline = require('readline');
const matchjs = require('matchjs'); // Подключаем matchjs
// --- Математические функции ---
const relu = (x) => Math.max(0, x); // Упрощение структуры relu
const reluDerivative = (x) => (x > 0 ? 1 : 0);
const softmax = (arr) => {
const max = Math.max(...arr); // Численно стабилизируем softmax
const expArr = arr.map((x) => Math.exp(x - max));
const sum = expArr.reduce((a, b) => a + b, 0);
return expArr.map((x) => x / sum);
};
// --- Утилита: Токенизация ---
const tokenize = (sentence) =>
sentence
.toLowerCase()
.replace(/[^\w\s]/g, '') // Очищаем от пунктуации
.split(/\s+/)
.filter(Boolean);
// --- TF-IDF: Векторизация ---
class TfidfVectorizer {
constructor(vocabulary = []) {
this.vocabulary = vocabulary;
this.idf = Array(this.vocabulary.length).fill(0);
}
fit(docs) {
const docCount = docs.length;
const termDocCounts = Array(this.vocabulary.length).fill(0);
docs.forEach((doc) => {
const tokens = new Set(tokenize(doc));
tokens.forEach((word) => {
const index = this.vocabulary.indexOf(word);
if (index !== -1) termDocCounts[index]++;
});
});
this.idf = this.vocabulary.map((_, idx) => Math.log((1 + docCount) / (1 + termDocCounts[idx])) + 1);
}
updateVocabulary(newDocs) {
const newWords = new Set();
newDocs.forEach((doc) => {
tokenize(doc).forEach((word) => newWords.add(word));
});
newWords.forEach((word) => {
if (!this.vocabulary.includes(word)) {
this.vocabulary.push(word);
this.idf.push(0); // Будет обновлено позже
}
});
}
transform(doc) {
const tf = Array(this.vocabulary.length).fill(0);
tokenize(doc).forEach((word) => {
const index = this.vocabulary.indexOf(word);
if (index !== -1) tf[index]++;
});
return tf.map((termFreq, idx) => termFreq * this.idf[idx]);
}
recalculateIdf(allDocs) {
const docCount = allDocs.length;
const termDocCounts = Array(this.vocabulary.length).fill(0);
allDocs.forEach((doc) => {
const tokens = new Set(tokenize(doc));
tokens.forEach((word) => {
const index = this.vocabulary.indexOf(word);
if (index !== -1) termDocCounts[index]++;
});
});
this.idf = this.vocabulary.map((_, idx) => Math.log((1 + docCount) / (1 + termDocCounts[idx])) + 1);
}
}
// --- Нейронная сеть ---
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.initMatrix(hidden_nodes, input_nodes); // Веса между input -> hidden
this.weights_ho = this.initMatrix(output_nodes, hidden_nodes); // Веса hidden -> output
this.bias_h = Array(hidden_nodes).fill(0).map(() => Math.random() * 2 - 1);
this.bias_o = Array(output_nodes).fill(0).map(() => Math.random() * 2 - 1);
this.learningRate = 0.001;
}
initMatrix(rows, cols) {
return new Array(rows).fill(0).map(() =>
new Array(cols).fill(0).map(() => Math.random() * 2 - 1)
);
}
feedforward(input_array) {
const hiddenRaw = this.weights_ih.map((row) =>
row.reduce((sum, w, idx) => sum + w * input_array[idx], 0)
);
const hidden = hiddenRaw.map((val, idx) => relu(val + this.bias_h[idx]));
const outputRaw = this.weights_ho.map((row) =>
row.reduce((sum, w, idx) => sum + w * hidden[idx], 0)
);
const output = outputRaw.map((val, idx) => val + this.bias_o[idx]);
return softmax(output);
}
train(input_array, target_array) {
const hiddenRaw = this.weights_ih.map((row) =>
row.reduce((sum, w, idx) => sum + w * input_array[idx], 0)
);
const hidden = hiddenRaw.map((val, idx) => relu(val + this.bias_h[idx]));
const outputRaw = this.weights_ho.map((row) =>
row.reduce((sum, w, idx) => sum + w * hidden[idx], 0)
);
const output = softmax(outputRaw.map((val, idx) => val + this.bias_o[idx]));
const outputErrors = output.map((out, i) => target_array[i] - out);
const hiddenErrors = this.weights_ho[0].map((_, j) =>
this.weights_ho.reduce((acc, ho_row, i) => acc + ho_row[j] * outputErrors[i], 0)
);
// Обновляем веса
this.weights_ho.forEach((row, i) => {
row.forEach((_, j) => {
this.weights_ho[i][j] += this.learningRate * outputErrors[i] * hidden[j];
});
});
this.bias_o = this.bias_o.map((bias, i) => bias + this.learningRate * outputErrors[i]);
this.weights_ih.forEach((row, i) => {
row.forEach((_, j) => {
this.weights_ih[i][j] +=
this.learningRate * hiddenErrors[i] * reluDerivative(hiddenRaw[i]) * input_array[j];
});
});
this.bias_h = this.bias_h.map((bias, i) => bias + this.learningRate * hiddenErrors[i] * reluDerivative(hiddenRaw[i]));
}
}
// --- Основной код ---
(async () => {
console.log("Оптимизированный запуск!");
})();
Таким образом:
softmax, весами и idf немного точнее.matchjs мог бы использоваться в обработке сложных вариантов).Not yet included in a published release.
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)))
);
}
feedforward(input_array) {
const hidden = this.weights_ih.map((row) =>
row.reduce((sum, weight, idx) => sum + weight * input_array[idx], 0)
).map((val, idx) => relu(val + this.bias_h[idx]));
const output = this.weights_ho.map((row) =>
row.reduce((sum, weight, idx) => sum + weight * hidden[idx], 0)
).map((val, idx) => val + this.bias_o[idx]);
return softmax(output);
}
train(input_array, target_array) {
// --- Forward Pass ---
const hidden = this.weights_ih.map((row) =>
row.reduce((sum, weight, idx) => sum + weight * input_array[idx], 0)
).map((val, idx) => relu(val + this.bias_h[idx]));
const output = this.weights_ho.map((row) =>
row.reduce((sum, weight, idx) => sum + weight * hidden[idx], 0)
).map((val, idx) => val + this.bias_o[idx]);
const finalOutputs = softmax(output);
// --- Calculate Errors ---
const outputErrors = finalOutputs.map((output, i) => output - target_array[i]);
const hiddenErrors = this.weights_ho[0].map((_, j) =>
this.weights_ho.reduce((sum, row, i) => sum + row[j] * outputErrors[i], 0)
);
// --- Update Weights and Biases ---
this.weights_ho.forEach((row, i) => {
row.forEach((_, j) => {
this.weights_ho[i][j] -= this.learningRate * outputErrors[i] * hidden[j];
});
});
this.bias_o.forEach((bias, i) => {
this.bias_o[i] -= this.learningRate * outputErrors[i];
});
this.weights_ih.forEach((row, i) => {
row.forEach((_, j) => {
this.weights_ih[i][j] -=
this.learningRate * hiddenErrors[i] * reluDerivative(hidden[i]) * input_array[j];
});
});
this.bias_h.forEach((bias, i) => {
this.bias_h[i] -= this.learningRate * hiddenErrors[i] * reluDerivative(hidden[i]);
});
}
async saveModel(filePath) {
const modelData = {
input_nodes: this.input_nodes,
hidden_nodes: this.hidden_nodes,
output_nodes: this.output_nodes,
weights_ih: this.weights_ih,
weights_ho: this.weights_ho,
bias_h: this.bias_h,
bias_o: this.bias_o,
};
await fs.writeFile(filePath, JSON.stringify(modelData));
}
async loadModel(filePath) {
const data = JSON.parse(await fs.readFile(filePath, 'utf8'));
this.input_nodes = data.input_nodes;
this.hidden_nodes = data.hidden_nodes;
this.output_nodes = data.output_nodes;
this.weights_ih = data.weights_ih;
this.weights_ho = data.weights_ho;
this.bias_h = data.bias_h;
this.bias_o = data.bias_o;
}
// Метод для добавления новых выходных узлов (если появились новые ответы)
addOutputNodes(newCount) {
for (let i = 0; i < newCount; i++) {
this.weights_ho.push(
new Array(this.hidden_nodes).fill(0).map(() => (Math.random() * 2 - 1) * Math.sqrt(2 / (this.hidden_nodes + this.output_nodes + i)))
);
this.bias_o.push(Math.random() * 2 - 1);
}
this.output_nodes += newCount;
}
// Функция для загрузки данных
const loadData = async () => {
const data = JSON.parse(await fs.readFile(dataPath, 'utf8'));
const training_data = data.map((item) => ({
question: item.question,
answer: item.answer,
}));
return training_data;
};
// Функция для инициализации или загрузки модели и векторизатора
const initialize = async () => {
try {
// Попытка загрузить сохраненную модель и векторизатор
await fs.access(modelPath);
const modelData = JSON.parse(await fs.readFile(modelPath, 'utf8'));
nn = new NeuralNetwork(modelData.input_nodes, modelData.hidden_nodes, modelData.output_nodes);
nn.weights_ih = modelData.weights_ih;
nn.weights_ho = modelData.weights_ho;
nn.bias_h = modelData.bias_h;
nn.bias_o = modelData.bias_o;
const vectorizerData = JSON.parse(await fs.readFile(vectorizerPath, 'utf8'));
vectorizer = new TfidfVectorizer(vectorizerData.vocabulary);
vectorizer.idf = vectorizerData.idf;
const data = await loadData();
const uniqueAnswers = [...new Set(data.map((item) => item.answer))];
indexToAnswer = Object.fromEntries(uniqueAnswers.map((a, i) => [i, a]));
answerToIndex = Object.fromEntries(uniqueAnswers.map((a, i) => [a, i]));
allDocs = data.map((pair) => pair.question);
// Проверка соответствия размеров
if (nn.input_nodes !== vectorizer.vocabulary.length || nn.output_nodes !== uniqueAnswers.length) {
console.error("Размеры модели не соответствуют данным. Перечитайте модель.");
process.exit(1);
}
} catch {
// Если моделей нет, инициализируем новую
const data = await loadData();
const uniqueAnswers = [...new Set(data.map((pair) => pair.answer))];
answerToIndex = Object.fromEntries(uniqueAnswers.map((a, i) => [a, i]));
indexToAnswer = Object.fromEntries(uniqueAnswers.map((a, i) => [i, a]));
const vocabularySet = new Set();
data.forEach((pair) => tokenize(pair.question).forEach((word) => vocabularySet.add(word)));
const vocabulary = [...vocabularySet];
vectorizer = new TfidfVectorizer(vocabulary);
vectorizer.fit(data.map((pair) => pair.question));
allDocs = data.map((pair) => pair.question);
const inputs = data.map((pair) => vectorizer.transform(pair.question));
const targets = data.map((pair) => {
const target = new Array(uniqueAnswers.length).fill(0);
target[answerToIndex[pair.answer]] = 1;
return target;
});
nn = new NeuralNetwork(vocabulary.length, 64, uniqueAnswers.length);
for (let epoch = 0; epoch < 300; epoch++) {
inputs.forEach((input, i) => nn.train(input, targets[i]));
if ((epoch + 1) % 1 === 0) console.log(`Эпоха ${epoch + 1} завершена`);
}
await nn.saveModel(modelPath);
await fs.writeFile(vectorizerPath, JSON.stringify({ vocabulary: vectorizer.vocabulary, idf: vectorizer.idf }));
}
};
await initialize();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
console.log("Задавайте вопросы или используйте команду 'обучить <файл.json>' (введите 'выход' для завершения):");
rl.on('line', async (input) => {
input = input.trim();
if (input.toLowerCase() === 'выход') {
rl.close();
return;
}
if (input.toLowerCase().startsWith('обучить')) {
// Разбор команды 'обучить <файл>'
const parts = input.split(' ');
if (parts.length !== 2) {
console.log("Использование: обучить <имя_файла.json>");
return;
}
const trainFile = parts[1];
try {
const trainData = JSON.parse(await fs.readFile(trainFile, 'utf8'));
const newTrainingData = trainData.map((item) => ({
question: item.question,
answer: item.answer,
}));
// Обновляем список всех документов
allDocs = allDocs.concat(newTrainingData.map(pair => pair.question));
// Обновляем векторизатор
vectorizer.updateVocabulary(newTrainingData.map(pair => pair.question));
vectorizer.recalculateIdf(allDocs);
// Обновляем файлы vectorizer.json
await fs.writeFile(vectorizerPath, JSON.stringify({ vocabulary: vectorizer.vocabulary, idf: vectorizer.idf }));
// Обновляем модель, если появились новые ответы
const newAnswers = [...new Set(newTrainingData.map(pair => pair.answer))];
let addedAnswers = [];
newAnswers.forEach(answer => {
if (!(answer in answerToIndex)) {
const newIndex = Object.keys(answerToIndex).length;
answerToIndex[answer] = newIndex;
indexToAnswer[newIndex] = answer;
addedAnswers.push(answer);
}
});
if (addedAnswers.length > 0) {
console.log(`Добавлено ${addedAnswers.length} новых ответов. Обновляем модель...`);
nn.addOutputNodes(addedAnswers.length);
// Сохраняем обновленные параметры модели
await nn.saveModel(modelPath);
}
// Переформируем целевые индексы
const uniqueAnswers = Object.keys(answerToIndex);
const targets = newTrainingData.map((pair) => {
const target = new Array(uniqueAnswers.length).fill(0);
target[answerToIndex[pair.answer]] = 1;
return target;
});
// Преобразуем новые вопросы
const inputs = newTrainingData.map((pair) => vectorizer.transform(pair.question));
// Дообучение модели
for (let epoch = 0; epoch < 300; epoch++) { // Можно настроить количество эпох
inputs.forEach((input, i) => nn.train(input, targets[i]));
if ((epoch + 1) % 100 === 0) console.log(`Дообучение: Эпоха ${epoch + 1} завершена`);
}
// Сохраняем обновленную модель и данные ответов
await nn.saveModel(modelPath);
// Обновляем bd.json с новыми данными
const existingData = JSON.parse(await fs.readFile(dataPath, 'utf8'));
const updatedData = existingData.concat(newTrainingData);
await fs.writeFile(dataPath, JSON.stringify(updatedData, null, 2));
console.log("Модель успешно дообучена и сохранена.");
} catch (err) {
console.error(`Ошибка при обучении: ${err.message}`);
}
return;
}
// Обработка вопроса
const inputVector = vectorizer.transform(input);
const output = nn.feedforward(inputVector);
const answerIndex = output.indexOf(Math.max(...output));
console.log(`Ответ: ${indexToAnswer[answerIndex] || "Не понимаю ваш вопрос."}`);
});
rl.on('close', () => {
console.log("До свидания!");
process.exit(0);
});