I am using Jupyter Notebooks on VSCode to create a U-Net.
Here is a quick snippet of my code that generates the error:
# PREPARE U-NET MODEL
from tensorflow.keras import Input, Model
from tensorflow.keras.backend import clear_session
from tensorflow.keras.layers import Activation, Add, BatchNormalization, Concatenate, Convolution2DTranspose, MaxPool2D, SeparableConv2D
from tensorflow.math import reduce_mean
With the new update, Pylance is now integrated into Jupyter notebooks. However, it gives me an error saying that tensorflow.math cannot be resolved. I obviously did not explicitly not install the math part in TensorFlow.
The specific error given is Pylance(reportMissingImports).
Can you try
from tensorflow._api.v2.math import reduce_mean
Related
Trying to convert a keras model (Thumbs.h5) into an onnx model on Google Colab, however I am getting an "AttributeError: module 'tensorflow.python.keras' has no attribute 'applications'" error when I run the code.
My code:
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.models import load_model
import onnx
import keras2onnx
onnx_model_name = 'fish-resnet50.onnx'
model = load_model('model-resnet50-final.h5')
onnx_model = keras2onnx.convert_keras(model, model.name)
onnx.save_model(onnx_model, onnx_model_name)
What I've tried:
Updating keras with !pip install keras --upgrade (already updated)
Running it locally with a jupyter notebook on my M1 Mac (V12.4) to get the same error
Pointers or solutions greatly appreciated.
As per the documentation
keras2onnx has been tested on Python 3.5 - 3.8, with tensorflow
1.x/2.0 - 2.2
So install compatible version of tensorflow.
Also keras-onnx is not under active development so use tf2onnx as per the documentation
I'm taking a Microsoft PyTorch course and trying to implement on Kaggle Notebooks but I kept having the same error message over and over again: "ModuleNotFoundError: No module named 'onnxruntime'". I've checked everywhere possible if I could find a solution to it but none, I even tried installing it manually using pip in the notebook, but it's still not working. I've checked the official onnxruntime website and documentation but there's nowhere it states anything about something being outdated or any other issue. Someone help. My code won't run because it says "onnxruntime is not defined". Here are my imports:
%matplotlib inline
import torch
import onnxruntime
from torch import nn
import torch.onnx as onnx
import torchvision.models as models
from torchvision import datasets
from torchvision.transforms import ToTensor
and the code cell I'm trying to run
session = onnxruntime.InferenceSession(onnx_model, None)
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
result = session.run([output_name], {input_name: x.numpy()})
predicted, actual = classes[result[0][0].argmax(0)], classes[y]
print(f'Predicted: "{predicted}", Actual: "{actual}"')
And you can find the complete notebook here: https://www.kaggle.com/faisalalbasu/complete-model
the error occurs because "import" cannot find onnxruntime in any of the paths, check where import is searching and see if onnxruntime is in there.
check what path pip install installs to, that way in the future you won't have the same problem! :)
I have been trying to run a machine learning training program on an HPC cluster using MobaXterm for a while now and have been getting
ImportError: cannot import name 'Adam' from 'keras.optimizers'
and similar errors when I run the main file which should train a model and then output a file of trained weights. I am making sure to import the necessary package relevant to the error through the line: "from keras.optimizers import Adam", so it's a mystery as to why this won't go away.
Someone in another thread suggested tensorflow.keras.optimizers instead of keras.optimizers, but that just gives me the alternative error:
ValueError: Could not interpret optimizer identifier: <tensorflow.python.keras.optimizer_v2.adam.Adam object at 0x2aab0e2dd828>
Interestingly, the program, which is almost unedited from a github download, runs perfectly when running it on my computer locally, and also works great on Google Colab. As soon as I began sending it to the cluster the issues appear. Wonder if anyone has experience with this kind of thing and knows what I should be paying attention to. Thanks in advance!
Edit: I realized it may be helpful to show all the imports i'm doing at the beginning of the file, they are here:
from __future__ import print_function
import numpy as np
import os
import skimage.io as io
import skimage.transform as trans
import numpy as np
from keras.models import *
from keras.layers import *
from keras.optimizers import * #I have tried commenting out this line but still face the same error
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as keras
from keras.preprocessing.image import ImageDataGenerator
import glob
from keras.optimizers import Adam
I was initially suggested to check my package versions. My Keras version was for some reason causing issues, so I did a pip uninstall keras and changed all my imports from, for example:
from keras.callbacks import
to like
from tensorflow.keras.callbacks import
And this change fixed the problem
I had a similar problem and I simply replaced this:
from keras.optimizers import Adam
With this:
from tensorflow.keras.optimizers import Adam
To deal with this error in newer version of tensorflow, we can skip importing Adam. We do not have to implicitly import the optimizer. We can just mention:
model.compile(optimizer= "adam", loss='mse')
I can't import anything from keras if I import it from tensorflow.
I installed tensorflow 2.0 with pip install tensorflow, and while I'm able to write something like:
import tensorflow as tf
from tensorflow import keras
model = keras.Sequential()
If I try to import Sequential from keras
import tensorflow as tf
from tensorflow import keras
from keras import Sequential
I got Unresolved reference 'keras'.
I've looked into every other post I could find and the information is contradictory, some say you have to install keras separately other says you just need to install tensorflow.
So far I've tried:
from tensorflow.python import keras
from tensorflow.contrib import keras
import tensorflow.keras as keras
from tensorflow.keras import Sequential
Plus a bunch of combination of the above, none of these work.
Sorry if it's a dumb question but I've never struggled so much with a simple import before.
Edit: Additionnal info, I'm on ubuntu 18.04, with Pycharm and a Python 3.6 virtual environment.
Answer:
It is actually a PyCharm bug !
Link here: https://youtrack.jetbrains.com/issue/PY-38220
I tried the snippet of code proposed by #AYI here
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten
example_model = Sequential()
example_model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(100, 100, 1)))
example_model.add(MaxPooling2D((2, 2)))
example_model.add(Flatten())
example_model.summary()
And actually runs normally despite the warning and error displayed by Pycharm !
Try in this way should help you "from tensorflow.keras.xxx import xxx"
Example of how to import Sequential in tensorflow 2.0:
from tensorflow.keras.models import Sequential
good luck~
Here is the Demo:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten
example_model = Sequential()
example_model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(100, 100, 1)))
example_model.add(MaxPooling2D((2, 2)))
example_model.add(Flatten())
example_model.summary()
I've some trouble with tensorflow-gpu 1.6.0.
I'm doing the final assignment of "bayesan methods in machine learning" class on coursera.
https://www.coursera.org/learn/bayesian-methods-in-machine-learning
When I run the code on GPU with tensorflow-gpu (pip install tensorflow-gpu), python crashes, but if I run the same code on CPU with the standard tensorflow (pip isntall tensorflow), the code runs fast without errors or crashes. Obviously I unistalled the gpu version before I installed the standard version and vice versa.
About the python crash, the debugger shows this message:
Unhandled exception at 0x00007FFDAB4DB79E (ucrtbase.dll) in python.exe
This is the starter code:
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output
import tensorflow as tf
import GPy
import GPyOpt
import keras
from keras.layers import Input, Dense, Lambda, InputLayer, concatenate, Activation, Flatten, Reshape
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import Conv2D, Deconv2D
from keras.losses import MSE
from keras.models import Model, Sequential
from keras import backend as K
from keras import metrics
from keras.datasets import mnist
from keras.utils import np_utils
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
import utils
import os
%matplotlib inline
sess = tf.InteractiveSession()
K.set_session(sess)
latent_size = 8
vae, encoder, decoder = utils.create_vae(batch_size=128, latent=latent_size)
sess.run(tf.global_variables_initializer())
vae.load_weights('CelebA_VAE_small_8.h5')
K.set_learning_phase(False)
latent_placeholder = tf.placeholder(tf.float32, (1, latent_size))
decode = decoder(latent_placeholder)
This code causes python crash when is executed on GPU but NOT on CPU:
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i+1)
image = sess.run(decode, feed_dict={latent_placeholder: np.random.normal([0]*latent_size,[1]*latent_size)[:, np.newaxis].T})[0]### YOUR CODE HERE
plt.imshow(np.clip(image, 0, 1))
plt.axis('off')
Additional Information:
python version 3.6.4
tensorflow 1.6.0
tensorflow-gpu 1.6.0
cuDNN 7.1.1 for CUDA 9.0
CUDA 9.0 with patch 1 and 2
GPU 1080ti with driver 391.01
You can find the python notebook and the weights on wetransfer:
https://wetransfer.com/downloads/59b9011823d38c204b5ef5a2b58f5e8e20180311201808/32c900
I found the issue. cuDNN 7.1.1 doesn't work yet with tensorflow-gpu. I downgraded cuDNN to 7.0.5 and now the code works as expected.
If you have a issue like me, you have to downgrade cuDNN!