You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复在Google Colab运行Teachable Machine音频模型代码的问题

修复Teachable Machine音频模型在Colab运行的问题

1. 验证文件路径与加载逻辑

  • 先确认所有导出文件(model.json、权重文件、meta.json)都已上传到Colab,用命令检查:
    !ls /content/
    
  • 加载模型时路径必须精准,示例代码:
    import tensorflow as tf
    from tensorflow.keras.models import model_from_json
    
    # 加载模型拓扑
    with open('/content/model.json', 'r') as f:
        model_json = f.read()
    model = model_from_json(model_json)
    
    # 加载权重,确保文件名和weightsManifest中的一致
    model.load_weights('/content/weights.h5')
    

2. 对齐依赖版本

Teachable Machine导出的音频模型对TensorFlow/TensorFlow.js版本有要求,Colab默认版本可能不兼容,指定安装适配版本:

!pip install tensorflow==2.10.0 tensorflowjs==3.19.0

安装后重启Colab运行时再执行代码。

3. 匹配音频预处理流程

必须严格遵循meta.json中定义的音频参数(采样率、时长、特征类型)做预处理,示例:

import librosa
import numpy as np

# 从meta.json中读取参数,比如采样率16000、音频时长1秒
sample_rate = 16000
audio_duration = 1

def preprocess_input_audio(file_path):
    # 加载音频并统一采样率
    audio, sr = librosa.load(file_path, sr=sample_rate)
    # 补零或截断到指定时长
    target_length = sample_rate * audio_duration
    if len(audio) < target_length:
        audio = np.pad(audio, (0, target_length - len(audio)), mode='constant')
    else:
        audio = audio[:target_length]
    # 提取MFCC特征(与Teachable Machine训练时一致)
    mfcc_features = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40)
    # 调整维度匹配模型输入要求
    return mfcc_features[np.newaxis, ..., np.newaxis]

4. 修正模型加载语法

如果使用TensorFlow.js的加载方式,注意本地路径的写法:

import tensorflowjs as tfjs

# 加载TensorFlow.js格式的模型
model = tfjs.converters.load_keras_model('/content/model.json')

5. 检查文件完整性

如果以上步骤无效,重新从Teachable Machine导出模型,避免文件传输过程中损坏,再重新上传到Colab。

内容的提问来源于stack exchange,提问作者Irene giring

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:15:33