Python 3.8, TF 2.2.2 y no consigo que compile correctamente

#------------------------------- Importamos librerias ---------------------------------
import cv2
import os


#---------------------------------Importamos las fotos tomadas-----------------------------
import tensorflow.keras.optimizers
#------------------------------ Crear modelo y entrenarlo ---------------------------------------
from tensorflow import keras
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator  #Nos ayuda a preprocesar las imagenes que le entreguemos al modelo
from tensorflow.python.keras.preprocessing import optimizer #Optimizador con el que vamos a entrenar el modelo
from tensorflow.python.keras.models import Sequential  #Nos permite hacer redes neuronales secuenciales
from tensorflow.python.keras.layers import Dropout, Flatten, Dense, Activation #
from tensorflow.python.keras.layers import Convolution2D, MaxPooling2D  #Capas para hacer las convoluciones
from tensorflow.python.keras import backend as K       #Si hay una sesion de keras, lo cerramos para tener todo limpio


K.clear_session()  #Limpiamos todo

datos_entrenamiento = 'C:/Users/elles/PycharmProjects/Nuevo proyecto/Deteccion-y-Clasificacion-de-Manos-main/Fotos/Entrenamiento'
datos_validacion = 'C:/Users/elles/PycharmProjects/Nuevo proyecto/Deteccion-y-Clasificacion-de-Manos-main/Fotos/Validación'

#Parametros
iteraciones = 20  #Numero de iteraciones para ajustar nuestro modelo
altura, longitud = 200, 200 #Tamaño de las imagenes de entrenamiento
batch_size = 1  #Numero de imagenes que vamos a enviar
pasos = 300/1  #Numero de veces que se va a procesar la informacion en cada iteracion
pasos_validacion = 300/1 #Despues de cada iteracion, validamos lo anterior
filtrosconv1 = 32
filtrosconv2 = 64     #Numero de filtros que vamos a aplicar en cada convolucion
tam_filtro1 = (3,3)
tam_filtro2 = (2,2)   #Tamaños de los filtros 1 y 2
tam_pool = (2,2)  #Tamaño del filtro en max pooling
clases = 2  #Mano abierta y cerrada (5 dedos y 0 dedos)
lr = 0.0005  #ajustes de la red neuronal para acercarse a una solucion optima

#Pre-Procesamiento de las imagenes
preprocesamiento_entre = ImageDataGenerator(
    rescale= 1./255,   #Pasar los pixeles de 0 a 255 | 0 a 1
    shear_range = 0.3, #Generar nuestras imagenes inclinadas para un  mejor entrenamiento
    zoom_range = 0.3,  #Genera imagenes con zoom para un mejor entrenamiento
    horizontal_flip=True #Invierte las imagenes para mejor entrenamiento
)

preprocesamiento_vali = ImageDataGenerator(
    rescale = 1./255
)

imagen_entreno = preprocesamiento_entre.flow_from_directory(
    datos_entrenamiento,       #Va a tomar las fotos que ya almacenamos
    target_size = (altura, longitud),
    batch_size = batch_size,
    class_mode = 'categorical',  #Clasificacion categorica = por clases
)

imagen_validacion = preprocesamiento_vali.flow_from_directory(
    datos_validacion,
    target_size=(altura,longitud),
    batch_size= batch_size,
    class_mode='categorical'
)

#Creamos la red neuronal convolucional (CNN)
cnn = Sequential()  #Red neuronal secuencial
#Agregamos filtros con el fin de volver nuestra imagen muy profunda pero pequeña
cnn.add(Convolution2D(filtrosconv1, tam_filtro1, padding = 'same', input_shape=(altura,longitud,3), activation = 'relu')) #Agregamos la primera capa
         #Es una convolucion y realizamos config
cnn.add(MaxPooling2D(pool_size=tam_pool)) #Despues de la primera capa vamos a tener una capa de max pooling y asignamos el tamaño

cnn.add(Convolution2D(filtrosconv2, tam_filtro2, padding = 'same', activation='relu')) #Agregamos nueva capa

cnn.add(MaxPooling2D(pool_size=tam_pool))

#Ahora vamos a convertir esa imagen profunda a una plana, para tener 1 dimension con toda la info
cnn.add(Flatten())  #Aplanamos la imagen
cnn.add(Dense(256,activation='relu'))  #Asignamos 256 neuronas
cnn.add(Dropout(0.5)) #Apagamos el 50% de las neuronas en la funcion anterior para no sobreajustar la red
cnn.add(Dense(clases, activation='softmax'))  #Es nuestra ultima capa, es la que nos dice la probabilidad de que sea alguna de las clases

#Agregamos parametros para optimizar el modelo
#Durante el entrenamiento tenga una autoevalucion, que se optimice con Adam, y la metrica sera accuracy
optimizar = tensorflow.keras.optimizers.Adam(learning_rate= lr)
cnn.compile(loss = 'categorical_crossentropy', optimizer= optimizar, metrics=['accuracy'])

#Entrenaremos nuestra red
cnn.fit(imagen_entreno, steps_per_epoch=pasos, epochs= iteraciones, validation_data= imagen_validacion, validation_steps=pasos_validacion)

#Guardamos el modelo
cnn.save('Modelo.h5')
cnn.save_weights('pesos.h5')

Me salta el error:

Traceback (most recent call last):
File “C:\Users\elles\PycharmProjects\Nuevo proyecto\Deteccion-y-Clasificacion-de-Manos-main\Entrenamiento.py”, line 7, in
import tensorflow.keras.optimizers
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow_init_.py”, line 38, in
from tensorflow.python.tools import module_util as module_util
File "C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python_init
.py", line 44, in
from tensorflow.python.feature_column import feature_column_lib as feature_column
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\feature_column\feature_column_lib.py”, line 18, in
from tensorflow.python.feature_column.feature_column import *
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\feature_column\feature_column.py”, line 143, in
from tensorflow.python.layers import base
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\layers\base.py”, line 16, in
from tensorflow.python.keras.legacy_tf_layers import base
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras_init_.py”, line 25, in
from tensorflow.python.keras import models
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\models.py”, line 22, in
from tensorflow.python.keras.engine import functional
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\functional.py”, line 32, in
from tensorflow.python.keras.engine import training as training_lib
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\engine\training.py”, line 53, in
from tensorflow.python.keras.saving import hdf5_format
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\keras\saving\hdf5_format.py”, line 37, in
import h5py
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\h5py_init_.py”, line 46, in
from ._conv import register_converters as _register_converters
File “h5py\h5t.pxd”, line 14, in init h5py.conv
File “h5py\h5t.pyx”, line 293, in init h5py.h5t
File "C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy_init
.py", line 320, in getattr
raise AttributeError("module {!r} has no attribute "
AttributeError: module ‘numpy’ has no attribute ‘typeDict’

@Jorge_Garrido_Mach,

Welcome to the Tensorflow Forum!

AttributeError: module ‘numpy’ has no attribute ‘typeDict’

You can install Numpy 1.21 as shown below

!pip install numpy==1.21

Note: Please replace from tensorflow.python.keras.* with from tensorflow.keras.*

Thank you!

I just did it right now.
The errors have changed minimally, it still doesn’t process tensorflow.keras.

Also now I get errors with this description:

RuntimeError: module compiled against API version 0xf but this version of numpy is 0xe
ImportError: numpy.core.multiarray failed to import

The above exception was the direct cause of the following exception:

SystemError: <built-in method contains of dict object at 0x000001CC39FFF800> returned a result with a set error.

@Jorge_Garrido_Mach,

Have you restarted the python environment ensure that the changes take effect ?

If you are still facing the problem, Since you are using TF2.2, please install numpy as mentioned here

Thank you!

I keep getting the same error.

C:\Users\elles\AppData\Local\Programs\Python\Python38\python.exe “C:\Users\elles\PycharmProjects\Nuevo proyecto\Deteccion-y-Clasificacion-de-Manos-main\Entrenamiento.py”
RuntimeError: module compiled against API version 0xf but this version of numpy is 0xd
ImportError: numpy.core.multiarray failed to import

The above exception was the direct cause of the following exception:

SystemError: <built-in method contains of dict object at 0x000001C5E881EEC0> returned a result with an error set

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File “C:\Users\elles\PycharmProjects\Nuevo proyecto\Deteccion-y-Clasificacion-de-Manos-main\Entrenamiento.py”, line 8, in
import tensorflow.keras.optimizers
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow_init_.py”, line 38, in
from tensorflow.python.tools import module_util as module_util
File "C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python_init
.py", line 37, in
from tensorflow.python.eager import context
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\eager\context.py”, line 35, in
from tensorflow.python.client import pywrap_tf_session
File “C:\Users\elles\AppData\Local\Programs\Python\Python38\lib\site-packages\tensorflow\python\client\pywrap_tf_session.py”, line 19, in
from tensorflow.python.client._pywrap_tf_session import *
ImportError: initialization failed

Process finished with exit code 1

@Jorge_Garrido_Mach,

All these errors are due to version mismatch between Tensorflow and Numpy.

Do you have any specific reasons to use Tensorflow 2.2 ?

Otherwise, please upgrade Tensorflow to the latest version (i.e 2.12) , which will resolve all these version conflicts.

Thank you!

I just installed the version you told me about. The errors have been reduced considerably. I have installed the packages suggested by Pycharm that were necessary for that version. Now only this error persists:

C:\Users\elles\AppData\Local\Programs\Python\Python38\python.exe “C:\Users\elles\PycharmProjects\Nuevo proyecto\Deteccion-y-Clasificacion-de-Manos-main\Entrenamiento.py”
Traceback (most recent call last):
File “C:\Users\elles\PycharmProjects\Nuevo proyecto\Deteccion-y-Clasificacion-de-Manos-main\Entrenamiento.py”, line 8, in
import tensorflow.keras.optimizers
ModuleNotFoundError: No module named ‘tensorflow.keras’

Process finished with exit code 1

@Jorge_Garrido_Mach,

ModuleNotFoundError: No module named ‘tensorflow.keras’

You can use

from tensorflow.keras import optimizers

One more suggestion, tf.keras.preprocessing.image.ImageDataGenerator is deprecated. Prefer loading images with tf.keras.utils.image_dataset_from_directory and transforming the output tf.data.Dataset with preprocessing layers.

For more information, see the tutorials for loading images and augmenting images as well as the preprocessing layer guide.

Thank you!