Я работал над приложением в Android Studio, которое имеет модель tflite классификатора приложений.
К сожалению, всякий раз, когда звук отправляется через модель tflite, он постоянно выдает один и тот же результат. , при тестировании на Python этого не происходит. Я создал модель tflite в Edge импульсе из-за отсутствия знаний о тензорном потоке и не знаю, могу ли я использовать необработанный звук для файла tflite или необработанный звук.
private void classifyAudio() throws IOException {
// Load the .wav file
File wavFile = new File(new File(getExternalFilesDir(null), "AudioCaptures"), "audio.wav");
float[] inputAudio = extractAudioFeatures(wavFile);
// Prepare input tensor
float[][] inputTensor = new float[1][5088]; // Model expects an input of shape [1, 1040]
System.arraycopy(inputAudio, 0, inputTensor[0], 0, 1040); // Copy extracted features
// Run inference
float[][] output = new float[1][2]; // Model output is [1, 2] (fake or real)
tflite.run(inputTensor, output);
Log.d("ModelOutput", "Fake probability: " + output[0][0] + ", Real probability: " + output[0][1]);
float fakeProbability = output[0][0]; // Probability for "fake"
float realProbability = output[0][1]; // Probability for "real"
//probabilities to percentages
float fakePercentage = fakeProbability * 100;
float realPercentage = realProbability * 100;
//result as a percentage
String resultText = String.format("Fake: %.2f%%\nReal: %.2f%%", fakePercentage, realPercentage);
//result in the TextView
resultTextView.setText(resultText);
}
private float[] extractAudioFeatures(File wavFile) throws IOException {
// For simplicity, this is a placeholder method.
// Ensure that this method extracts the correct MFCC features from the audio file.
// Placeholder for feature extraction:
float[] features = new float[5088]; // Size should match the model input (1040)
// Implement actual feature extraction logic based on the .wav file (MFCC, etc.)
return features;
}
private int argmax(float[][] array) {
int maxIndex = 0;
float maxVal = Float.NEGATIVE_INFINITY;
for (int i = 0; i < array[0].length; i++) {
if (array[0] > maxVal) {
maxVal = array[0];
maxIndex = i;
}
}
return maxIndex;
}
private MappedByteBuffer loadModelFile(Context context, String fileName) throws IOException {
AssetFileDescriptor fileDescriptor = context.getAssets().openFd(fileName);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... -the-input
Модель Tflite дает одинаковый результат независимо от ввода ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1733760115
Anonymous
Я работал над приложением в Android Studio, которое имеет модель tflite классификатора приложений.
К сожалению, всякий раз, когда звук отправляется через модель tflite, он постоянно выдает один и тот же результат. , при тестировании на Python этого не происходит. Я создал модель tflite в Edge импульсе из-за отсутствия знаний о тензорном потоке и не знаю, могу ли я использовать необработанный звук для файла tflite или необработанный звук.
private void classifyAudio() throws IOException {
// Load the .wav file
File wavFile = new File(new File(getExternalFilesDir(null), "AudioCaptures"), "audio.wav");
float[] inputAudio = extractAudioFeatures(wavFile);
// Prepare input tensor
float[][] inputTensor = new float[1][5088]; // Model expects an input of shape [1, 1040]
System.arraycopy(inputAudio, 0, inputTensor[0], 0, 1040); // Copy extracted features
// Run inference
float[][] output = new float[1][2]; // Model output is [1, 2] (fake or real)
tflite.run(inputTensor, output);
Log.d("ModelOutput", "Fake probability: " + output[0][0] + ", Real probability: " + output[0][1]);
float fakeProbability = output[0][0]; // Probability for "fake"
float realProbability = output[0][1]; // Probability for "real"
//probabilities to percentages
float fakePercentage = fakeProbability * 100;
float realPercentage = realProbability * 100;
//result as a percentage
String resultText = String.format("Fake: %.2f%%\nReal: %.2f%%", fakePercentage, realPercentage);
//result in the TextView
resultTextView.setText(resultText);
}
private float[] extractAudioFeatures(File wavFile) throws IOException {
// For simplicity, this is a placeholder method.
// Ensure that this method extracts the correct MFCC features from the audio file.
// Placeholder for feature extraction:
float[] features = new float[5088]; // Size should match the model input (1040)
// Implement actual feature extraction logic based on the .wav file (MFCC, etc.)
return features;
}
private int argmax(float[][] array) {
int maxIndex = 0;
float maxVal = Float.NEGATIVE_INFINITY;
for (int i = 0; i < array[0].length; i++) {
if (array[0][i] > maxVal) {
maxVal = array[0][i];
maxIndex = i;
}
}
return maxIndex;
}
private MappedByteBuffer loadModelFile(Context context, String fileName) throws IOException {
AssetFileDescriptor fileDescriptor = context.getAssets().openFd(fileName);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79265669/tflite-model-gives-same-output-nomatter-the-input[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия