神经网络正则化器L1和L2

如何解决神经网络正则化器L1和L2

我正在对音乐类型进行分类。 我用我的模型(即神经网络)构建了文件.h5。 现在我要使用它。 这是预测音乐类型的代码:

#%%
import librosa
import tensorflow as tf
import numpy as np

from collections import Counter

SAVED_MODEL_PATH = "modelLast.h5"
SAMPLES_TO_CONSIDER = 22050
DURATION = 30
SAMPLE_PER_TRACK = SAMPLES_TO_CONSIDER * DURATION

#%%
class _Keyword_Spotting_Service:
    """Singleton class for keyword spotting inference with trained models.
    :param model: Trained model
    """

    model = None
_mapping = [
    "blues","classical","country","disco","hiphop","jazz","metal","pop","reggae","rock"
]
_instance = None

def predict(self,file_path,num_mfcc=13,n_fft=2048,hop_length=512):
        """Extract MFCCs from audio file.
        :param file_path (str): Path of audio file
        :param num_mfcc (int): # of coefficients to extract
        :param n_fft (int): Interval we consider to apply STFT. Measured in # of samples
        :param hop_length (int): Sliding window for STFT. Measured in # of samples
        :return MFCCs (ndarray): 2-dim array with MFCC data of shape (# time steps,# coefficients)
        """
        num_segments = 10
        num_samples_per_segment = int(SAMPLE_PER_TRACK / num_segments) # num  of segments
        # load audio file
        signal,sample_rate = librosa.load(file_path)
        
        # a faire
        predicted_indexes = [0] * num_segments
        predicted_mfcc = [0] * num_segments
        for s in range(num_segments):
            start_sample = num_samples_per_segment * s  # s=0 -> 0
            finish_sample = start_sample + num_samples_per_segment  # s=0 -> num_samples_per_segment
            mfcc = librosa.feature.mfcc(signal[start_sample:finish_sample],sample_rate,n_fft=n_fft,n_mfcc=num_mfcc,hop_length=hop_length)
            MFCCs = mfcc.T
            MFCCs = MFCCs[np.newaxis,...,np.newaxis]
            
            # get the predicted label
            predictions = self.model.predict(MFCCs)                
            print ("\nPredictions: {}".format(predictions))
            
            predicted_indexes [s] = np.argmax(predictions)
            predicted_mfcc [s] = np.max(predictions)
        
        print("\nIndex list: {}".format(predicted_indexes))
        print("\nIndex list Mfccs : {}".format(predicted_mfcc))
        
       
        #predicted_index = np.bincount(predicted_indexes).argmax()   # Méthode pour avoir l'index qui se répète le plus de fois
        
        # Ajout de précision du code : 
        """
        Nous ressort de la liste les indexs qui se répètent le plus de fois et s'il y a plusieurs doublons
        triplés,compare la valeurs des indexs et choisi l'index à la valeur la plus élevée
        Voir le code python Liste.py pour plus de précision
        """
        
        indices = list(map(lambda x: x[0],Counter(predicted_indexes).most_common()))
        counts = list(map(lambda x: x[1],Counter(predicted_indexes).most_common()))
        
        print("\nIndices présents dans la liste : ",indices)
        print("\nNombre d'apparition des indices : ",counts)
       
        max_indices = [indices[i] for i,x in enumerate(counts) if x == max(counts)]
        result_mcfccs = []

        for idx,id in enumerate(predicted_indexes):
            if id in max_indices:
                result_mcfccs.append(predicted_mfcc[idx])
            
        result = max(result_mcfccs)
        
        print("\n Indice se répétant le plus : ",max_indices)
        print("\nValeur maximale de l'indice se répétant le plus : ",result)
        
        
        indice = predicted_mfcc.index(result)
        print("\nEmplacement de la valeur dans la lsite :",indice)
        F= predicted_indexes.pop(indice)
        print("\nRésultat final : ",F)
        
        predicted_keyword = self._mapping[F]
        
        return predicted_keyword
    
def Keyword_Spotting_Service():
     """Factory function for Keyword_Spotting_Service class.
    :return _Keyword_Spotting_Service._instance (_Keyword_Spotting_Service):
    """

    # ensure an instance is created only the first time the factory function is called
    if _Keyword_Spotting_Service._instance is None:
        _Keyword_Spotting_Service._instance = _Keyword_Spotting_Service()
       _Keyword_Spotting_Service.model = tf.keras.models.load_model(SAVED_MODEL_PATH)
    return _Keyword_Spotting_Service._instance


if __name__ == "__main__":

    # create 2 instances of the keyword spotting service
    kss = Keyword_Spotting_Service()
    kss1 = Keyword_Spotting_Service()

    # check that different instances of the keyword spotting service point back to the same object (singleton)
    assert kss is kss1

# make a prediction
    keyword = kss.predict("discoTrain.wav")                        # Disco
    #keyword = kss.predict("TheRiversGoingWildCUT.mp3")             # Blues
    #keyword = kss.predict("QuantumJazz.mp3")                       # Jazz
    #keyword = kss.predict("QuantumJazzCUT.mp3")                    # Jazz
    #keyword = kss.predict("AbsconseResilience.mp3")                # Metal
    #keyword = kss.predict("Nature.wav")
    #keyword = kss.predict("elvis-presley-jailhouse-rock-music-video.mp3")           # Rock
    #keyword = kss.predict("bob-marley-no-woman-no-cry-official-video.mp3")              # Reggae
    #keyword = kss.predict("alan-jackson-chattahoochee-official-music-videoCUT.mp3")    # Country
    print(keyword)

问题是它返回了一个我在任何论坛上都从未见过的值错误:

File "C:\ProgramData\Anaconda3\envs\PMI\lib\site-packages\tensorflow_core\python\keras\utils\generic_utils.py",line 165,in class_and_config_for_serialized_keras_object
raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)

ValueError: Unknown regularizer: L2

我该如何解决?

解决方法

我终于找到了为什么出现此错误。 它来自我的路径变量。 从互联网下载文件夹后,只需在路径变量中添加“ ffmpeg”即可。 这是链接:https://ffmpeg.org/download.html 我将文件夹直接复制到我的“ C”盘中,并将路径添加到路径变量中。

祝你好运!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-