Pylance "layers" is not a known member of "None" when calling model.layers in Tensorflow v2? - tensorflow

I'm getting this Pylance warning in the 2nd code line when I call model.layers and I have no idea why.
Yet, I can't find any questions regardin the same issue.
Although it is just a warning, I'd like to understant it.
Does anyone have any solution to this?
import tensorflow as tf
from tensorflow import keras
from keras.models import load_model
model = load_model('my_model_final.h5', compile=False)
for layer in model.layers[0:20]:
layer.trainable = False

Related

Irreproducible results Tensorflow

I have a very basic code that tries to create a single-layered Dense neural net and predicts the output for a deterministic input. The code is as follows:
import tensorflow as tf
from tensorflow.keras import layers
model = tf.keras.models.Sequential()
model.add(layers.Dense(units = 10))
import numpy as np
inp = np.ones((1,10))
model.predict(inp)
But the output that I am getting isn't being deterministic. I think it is related to initializing the weights and biases. So, how do I fix this without writing the initializing function from scratch?
Set global seed before initializing model tf.random.set_seed(42)
You can also set seed for specific parts of model, e.g. kernel_initializer in Dense layer, but with this approach, you may miss initializers that will still be nondeterministic. In your case setting it globally will be the best solution.

Custom Layer not supporting serialized custom activation function

since the release of version 2.6 of Tensorflow I am having a issue I did not have with version 2.5.
The following code works OK:
from tensorflow.keras.utils import get_custom_objects
from tensorflow.keras.layers import Dense
def my_act(x):
return x
get_custom_objects().update({"my_act": my_act})
dense = Dense(3, activation="my_act")
However, if I try to do the same but with a custom layer instead of Tensorflow built-in layers, I have the error:
ValueError: Unknown activation function: my_act. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.
Here you have the minimum code to reproduce plus I show that with version 2.5 works ok (You need to restart the runtime to run it tho).
Try to import activations like this:
from tensorflow.keras import activations
instead of from tensorflow.python.keras import activations.
In tensorflow 2.7 and later versions tensorflow.python will no longer exist, and it seems in TF 2.6 already it is not compatible with some other functions.

AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'tf2'

enter image description here
Above is the image:
The error is this:
LOCAL.GENERATED_WITH_V2 = tf.__internal__.tf2.enabled()
AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'tf2'
Thanks
From Tensorflow 2.x onward, keras is no longer maintained and it became a part of Tensorflow. I would recommend instead of import keras, you should try from tensorflow import keras or import tensorflow as tf and use tf.keras.
You can import Sequential module from tensorflow as shown below
import tensorflow as tf
from tf.keras import Sequential
For more information you can refer this and this

still same error, module 'tensorflow' has no attribute 'get_default_graph'

Could you please help me with tensorflow? I have been very frustrated with tensorflow for many months. I know they don't work well with python 3.7. Now I am using python 3.6 with tensorflow 2.0.
What the heck this tensorflow? It is so frustrated to use tensorflow.
Here is my code:
import keras
import keras.backend as K
from keras.layers.core import Activation
from keras.models import Sequential,load_model
from keras.layers import Dense, Dropout, LSTM
The error of AttributeError: module 'tensorflow' has no attribute 'get_default_graph' is for next line:
model = Sequential()
Thank you so much.
Try importing libraries like that:
from tensorflow.keras.layers import Dense, Dropout, LSTM
I solved it. I downgraded tensorflow from 2.0 to 1.8. then it runs fine.

An error ocurred while starting the kernel . I think because of two python version but unable to figure out

I am trying to fit a model here but thing is that every time I fit a model my kernel dies I tried every other method but it did't worked.
I think there may be possibility of having two python versions installed but I don't know how to fix that or even verify that.
Also I am using MAC
I have tried updating reinstalling everything
#Importing libraries
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder,OneHotEncoder,StandardScaler
from sklearn.model_selection import train_test_split,cross_val_score
from keras.layers import Dense
import keras
from sklearn.metrics import confusion_matrix,accuracy_score
from keras.wrappers.scikit_learn import KerasClassifier
#Importing Datasets
dataset=pd.read_csv('Churn_Modelling.csv')
X=dataset.iloc[:,3:13].values
y=dataset.iloc[:,13].values
#Data preprocessing
le1=LabelEncoder()
X[:,1]=le1.fit_transform(X[:,1])
le2=LabelEncoder()
X[:,2]=le2.fit_transform(X[:,2])
h1=OneHotEncoder(categorical_features=[1])
X=h1.fit_transform(X).toarray()
X=X[:,1:]
#Splitting Dataset
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=0)
#Feature Scaling
sc=StandardScaler()
X_train=sc.fit_transform(X_train)
X_test=sc.transform(X_test)
#Making ANN hidden layer
classifier=keras.models.Sequential()
classifier.add(Dense(units=6,activation="relu",kernel_initializer="uniform",input_shape=(11,)))
#Adding second hidden layer
classifier.add(Dense(units=6,activation='relu',kernel_initializer='uniform'))
#Adding output layer
classifier.add(Dense(units=1,activation='sigmoid',kernel_initializer='uniform'))
#Compiling ANN
classifier.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
Till here it works like a charm with some warnings
#Making predictions and evaluating it
classifier.fit(X_train,y_train,epochs=100,batch_size=10)
But when I execute this it shows
An error ocurred while starting the kernel
b''
Any one knows how to solve this ?
Maybe this might help you: https://github.com/spyder-ide/spyder/issues/2812
If you are using Spyder, try:
conda update setuptools