python - "from keras.utils import to_categorical"中的错误

标签 python keras

我对这段代码有疑问,为什么?
代码:

import cv2
import numpy as np
from PIL import Image
import os
import numpy as np
import cv2
import os
import h5py
import dlib
from imutils import face_utils
from keras.models import load_model
import sys
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D,Dropout
from keras.layers import Dense, Activation, Flatten
from keras.utils import to_categorical
from keras import backend as K 
from sklearn.model_selection import train_test_split
from Model import model
from keras import callbacks

# Path for face image database
path = 'dataset'

recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");


def downsample_image(img):
    img = Image.fromarray(img.astype('uint8'), 'L')
    img = img.resize((32,32), Image.ANTIALIAS)
    return np.array(img)



# function to get the images and label data
def getImagesAndLabels(path):
    
    path = 'dataset'
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
    faceSamples=[]
    ids = []

    for imagePath in imagePaths:
        
        #if there is an error saving any jpegs
        try:
            PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
        except:
            continue    
        img_numpy = np.array(PIL_img,'uint8')

        id = int(os.path.split(imagePath)[-1].split(".")[1])
        faceSamples.append(img_numpy)
        ids.append(id)
    return faceSamples,ids

print ("\n [INFO] Training faces now.")
faces,ids = getImagesAndLabels(path)

K.clear_session()
n_faces = len(set(ids))
model = model((32,32,1),n_faces)
faces = np.asarray(faces)
faces = np.array([downsample_image(ab) for ab in faces])
ids = np.asarray(ids)
faces = faces[:,:,:,np.newaxis]
print("Shape of Data: " + str(faces.shape))
print("Number of unique faces : " + str(n_faces))


ids = to_categorical(ids)

faces = faces.astype('float32')
faces /= 255.

x_train, x_test, y_train, y_test = train_test_split(faces,ids, test_size = 0.2, random_state = 0)

checkpoint = callbacks.ModelCheckpoint('trained_model.h5', monitor='val_acc',
                                           save_best_only=True, save_weights_only=True, verbose=1)
                                    
model.fit(x_train, y_train,
             batch_size=32,
             epochs=10,
             validation_data=(x_test, y_test),
             shuffle=True,callbacks=[checkpoint])
             

# Print the numer of faces trained and end program
print("enter code here`\n [INFO] " + str(n_faces) + " faces trained. Exiting Program")
the output:
------------------
File "D:\my hard sam\ماجستير\سنة ثانية\البحث\python\Real-Time-Face-Recognition-Using-CNN-master\Real-Time-Face-Recognition-Using-CNN-master\02_face_training.py", line 16, in <module>
    from keras.utils import to_categorical
ImportError: cannot import name 'to_categorical' from 'keras.utils' (C:\Users\omar\PycharmProjects\SnakGame\venv\lib\site-packages\keras\utils\__init__.py)

最佳答案

凯拉斯 现在已完全集成到 tensorflow .所以,只导入 凯拉斯 导致错误。
它应该被导入为:

from tensorflow.keras.utils import to_categorical

避免 导入为:
from keras.utils import to_categorical

使用安全from tensorflow.keras.而不是 from keras.同时导入所有必要的模块。
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D,Dropout
from tensorflow.keras.layers import Dense, Activation, Flatten
from tensorflow.keras.utils import to_categorical
from tensorflow.keras import backend as K 
from sklearn.model_selection import train_test_split
from tensorflow.keras import callbacks

关于python - "from keras.utils import to_categorical"中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67018079/

相关文章:

python - 如何使用 sqlalchemy 有效地管理频繁的模式更改?

python - 值错误: Unsupported or invalid CSS selector: "unit-4" python

python - numpy.vectorize 返回不正确的值

python - Keras——使用 LSTM 层时精度较低,但不使用 LSTM 时精度很好

python - keras.losses.binary_crossentropy 输出张量的形状

python - 如何将 MNIST 数据加载到 Google Colab Jupyter Notebook 中?

python - DataGenerator在Google云端硬盘中找不到文件

python - Tensorflow - 训练后检索训练后的前馈神经网络的权重/偏差

python - 在 Keras 中合并,类型错误 : module object not callable?

machine-learning - 如何在神经网络的输出中执行诸如国际象棋走棋合法性之类的规则?