Tag Archives: hard

[Solved] AttributeError: module ‘keras.preprocessing.image‘ has no attribute ‘load_img‘

Original code:

from keras.preprocessing import image
img         =   image.load_img(img_path,target_size=(224,224))
x           =   image.img_to_array(img)

report errors:

AttributeError: module 'keras.preprocessing.image' has no attribute 'load_img'

Reason: The keras version has been updated.

Solution:

from keras.utils import image_utils
img         =   image_utils.load_img(img_path,target_size=(224,224))
x           =   image_utils.img_to_array(img)

[Solved] RuntimeError: Cannot clone object <keras.wrappers.scikit_learn.KerasClassifier object…

Today, I debugged the code and found this error. The complete contents are as follows:

RuntimeError: Cannot clone object < keras. wrappers. scikit_ learn. KerasClassifier object at 0x000003A783733F33>, as the constructor either does not set or modifies parameter layers

No error is reported when the code is found. It is normal

The code is then investigated:

from keras.wrappers.scikit_learn import KerasRegressor

Change to:

from tensorflow.keras.wrappers.scikit_learn import KerasRegressor

Problem solved!

[Solved] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter st

When using tensorflow.keras, this error is often reported during model training:

tensorflow/core/kernels/data/generator_dataset_op.cc:107] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter state is not initialized. The process may be terminated.
	 [[{{node PyFunc}}]]
tensorflow/core/kernels/data/generator_dataset_op.cc:107] Error occurred when finalizing GeneratorDataset iterator: Failed precondition: Python interpreter state is not initialized. The process may be terminated.

       [[{{node PyFunc}}]]

 

According to my own experience, there are several reasons for this errory:

1. The input image_size and input_shape does not match or is not defined when the model is built. Note that the input_shape must be defined when defining the first layer of the convolutional layer, e.g.

    model = keras.models.Sequential([
        # Input image [None,224,224,3]
        # Convolution layer 1: 32 5*5*3 filters, step size set to 1, fill set to same
        # Output [None,32,32,3]
        keras.layers.Conv2D(32, kernel_size=5, strides=1, padding='same', data_format='channels_last',
                            activation='relu', input_shape=(224, 224, 3)),

2. There is also train_generator and validate_generator related parameters must be consistent, such as batch_size, target_size, class_mode, etc.

3. The configuration limit itself, try to change the batch_size to a smaller size, or even to 1

4. The last program did not finish completely, finish all python programs to see.

Keras import package error: importerror: cannot import name ‘get_ config‘

ImportError: cannot import name ‘get_config’

Traceback (most recent call last):
  File "siameseNet.py", line 6, in <module>
    from keras.layers import Merge
  File "/usr/local/lib/python3.6/site-packages/keras/__init__.py", line 25, in <module>
    from keras import models
  File "/usr/local/lib/python3.6/site-packages/keras/models.py", line 19, in <module>
    from keras import backend
  File "/usr/local/lib/python3.6/site-packages/keras/backend.py", line 39, in <module>
    from tensorflow.python.eager.context import get_config
ImportError: cannot import name 'get_config'

Solution:

pip install keras == 2.1.0 --force-reinstall

[Solved] original_keras_version = f.attrs[‘keras_version‘].decode(‘utf8‘)

windows system:
original_keras_version = f.attrs[‘keras_version’].decode(‘utf8’)
1. error:

load_weights_from_hdf5_group
    original_keras_version = f.attrs['keras_version'].decode('utf8')

AttributeError: 'str' object has no attribute 'decode'

2. Cause analysis

When installing tensorflow, the default installed h5py is 3.1.0, and an error is reported because the TF you installed does not support an excessively high version of h5py

3. Solutions

1. Uninstall h5py3 Version 1.0, installing h5py2.0 Version 10.0.2. Restart the compiler

pip install h5py==2.10.0

[Solved] Python Keras Error: AttributeError: ‘Sequential‘ object has no attribute ‘predict_classes‘

This article is about using Keras in Python to execute yhat_classes = model.predict_classes(X_test) code with an error: AttributeError: ‘Sequential’ object has no attribute ‘predict_classes’ solution.

model = Sequential()
model.add(Dense(24, input_dim=13, activation='relu'))
model.add(Dense(18, activation='relu'))
model.add(Dense(6, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
-
history = model.fit(X_train, y_train, batch_size = 256, epochs = 10, verbose = 2, validation_split = 0.2)
-
score, acc = model.evaluate(X_test, y_test,verbose=2, batch_size= 256)
print('test accuracy:', acc)
-
yhat_classes = model.predict_classes(X_test)

Cause of problem:

This predict was removed in tensorflow version 2.6_ Classes function.

Reference documents: https://keras.rstudio.com/reference/predict_proba.html#details

The following codes can be used:

predict_x=model.predict(X_test) 
classes_x=np.argmax(predict_x,axis=1)

Or

You can also try tensorflow 2.5 or other versions to solve this problem.

Using tensorflow version 2.5, there may be the following warning messages:

tensorflow\python\keras\engine\sequential.py:455: UserWarning: model.predict_classes() is deprecated and will be removed after 2021-01-01. Please use instead:* np.argmax(model.predict(x), axis=-1), if your model does multi-class classification (e.g. if it uses a softmax last-layer activation).* (model.predict(x) > 0.5).astype("int32"), if your model does binary classification (e.g. if it uses a sigmoid last-layer activation).

How to Solve Keras calls plot_model error

1. Error information

When building the neural network model, you can call plot in keras_ The model module draws a schematic diagram of the model to facilitate the adjustment of the model structure:

from tensorflow.keras.models import Model
from tensorflow.keras.utils import plot_model
model = Model(dense_inputs+sparse_inputs, output_layer)
plot_model(model, "fm_model.png", show_shapes=True)

As a result, the following error messages appear:

(‘Failed to import pydot. You must pip install pydot and install graphviz (ht

tps://graphviz.gitlab.io/download/ ), ‘, ‘for pydotprint to work.’)

Understand the error message: the installation is complete without pydot and graphviz packages

2. Solutions

2.1 installation of graphviz package

pip install graphviz

2.2 download and install graphviz Exe file and install

In Windows Environment

Download address: https://graphviz.gitlab.io/download/

2.3 configuring environment variables for graphviz

2.4 installing pydot package

pip install pydot-ng

2.5 restart development tools

Restart the IDE or other development tools (Jupiter notebook) with immediate effect.

3. Summary

1. Installing pydot and graphviz packages directly according to the error message does not work

2. You need to go to the website to download the corresponding EXE file or zip file. After installation, specify the environment variables

3. Don’t forget to restart your ide or other development tools

Internalerror: GPU sync failed error (How to Solve)

1. Error reporting: (from Python deep learning p178-179)

When vscode runs the following code in Jupiter notebook, an error is reported: internalerror: GPU sync failed

from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import RMSprop

model = Sequential()
model.add(layers.Flatten(input_shape=(lookback // step, float_data.shape[-1])))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(1))

model.compile(optimizer=RMSprop(), loss='mae')
history = model.fit_generator(train_gen,
                              steps_per_epoch=500,
                              epochs=20,
                              validation_data=val_gen,
                              validation_steps=val_steps)

2. Solution:

(1) Don’t open too many ipynb file windows. There is only one running window left. Restart and there should be no problem.

(2) Some friends said that they might have something to do with the wallpaper engine. Just turn it off. I haven’t verified this yet.

However, I found that when the wallpaper engine dynamic desktop is displayed, the GPU utilization will increase sharply:

[Solved] Keras Error: KeyError: ‘accuracy‘, KeyError: ‘val_acc‘, KeyError: ‘acc‘

Problem:
keyerror ‘ACC’ is reported when using keras

Reason:
this is a keras version problem. ACC and accuracy are intended to be the same, but different keras versions use different names, so they need to be replaced. val_ So is acc.

Solution:
Print history keyword
Print (history. History. Keys())
change the error part to the printed “K” and “V”“

[Solved] Tensorflow error or keras error and tf.keras error: oom video memory is insufficient

Hint: if you want to see a list of allocated tenants when oom happens, add Report_tensor_allocations_upon_oom to RunOptions for current allocation info.

Problem description

The problems encountered in today’s 50% off cross-validation and grid search are that the amount of data was too large or bitch_ It also occurs when the size is too large, as shown in the figure:
use the command: Watch – N 0.1 NVIDIA SMI in Linux to view the GPU usage

reason

Due to the lack of video memory, but it is not the real lack of video memory, but because TensorFlow has eaten up the video memory, but there is no actual effective utilization. Therefore, the required video memory can be allocated to TensorFlow. (keras based on TensorFlow is also applicable)

Solution:

1. Set small pitch_Size, although it can be used, the indicator does not cure the root cause
2. Manually set the GPU. In train.py:

(1) in tensorflow
import tensorflow as tf
import os

os.environ["CUDA_VISIBLE_DEVICES"] = "0" Specify which GPU to use
config = tf.ConfigProto()
config.gpu_options.allow_growth = True # Allocate video memory on demand
config.gpu_options.per_process_gpu_memory_fraction = 0.4 # Maximum memory usage 40%
session = tf.Session(config=config)) # Create tensorflow session
...
(2) in keras
import tensorflow as tf
from keras.models import Sequential
import os
from keras.backend.tensorflow_backend import set_session ## Different from tf.keras

os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.ConfigProto()
config.gpu_options.allow_growth = True  # Allocate video memory on demand
set_session(tf.Session(config=config)) # Pass the settings to keras

model = Sequential()
...
(3) in tf.keras
import tensorflow as tf
from tensorflow.keras.models import Sequential

import os
from tensorflow_core.python.keras.backend import set_session # Different from tf.keras

os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.ConfigProto()
config.gpu_options.allow_growth = True  # Allocate video memory on demand
config.gpu_options.per_process_gpu_memory_fraction = 0.4 # use 40% of the maximum video memory
set_session(tf.Session(config=config)) # Pass the settings to tf.keras

model = Sequential()
...

Supplement:
tf.keras can use data reading multithreading acceleration:

model.fit(x_train,y_train,use_multiprocessing=True, workers=4) # Enable multithreading, using 4 CPUs

Empty session:

from tensorflow import keras
keras.backend.clear_session() 

After emptying, you can continue to create a new session

[Solved] R Error: Python module tensorflow.keras was not found.

Scenario:

rstudio reported error R: Python module tensorflow.keras was not found.
at first, I suspected that I could not accurately locate the keras package of R, because I was using Anaconda to do other things, but later I saw other error reports and felt that they were not so complex… Later, I found that they were just simple and not installed properly… In short, the solution is as follows


Solution:

terminal input:

install.packages(tensorflow)
install_tensorflow()
library(tensorflow)
#Keras The R interface uses the TensorFlow backend engine.
# To install the core Keras library and TensorFlow backend, use the install_keras() function
install_keras()
library(keras)
# Run them all and then tune the package, if you have already done so, restart RStudio
-------------------------------------------
#Other solutions to this problem are as follows:
library(tensorflow)
library(keras)
use_condaenv("r-tensorflow")

ValueError: Negative dimension size caused by subtracting 2 from 1 for…

ValueError: Negative dimension size caused by subtracting 2 from 1 for ‘{{node max_pooling2d_1/MaxPool}} = MaxPoolT=DT_FLOAT, data_format=“NHWC”, explicit_paddings=[], ksize=[1, 2, 2, 1], padding=“VALID”, strides=[1, 2, 2, 1]’ with input shapes: [?,1,128,64].
channel Order problem
Add the code
from keras import backend as K
K.set_image_data_format(‘channel_first’)
Done!