module 'tensorflow' has no attribute 'variable_scope' with TFANN in Colab - python-3.x

i start using Colab to create ANN and try out the TFANN package and receive error with the following simple sample code from https://github.com/nicholastoddsmith/pythonml#tfann:
pip install TFANN
import numpy as np
from TFANN import ANNR
A = np.random.rand(32, 4)
Y = np.random.rand(32, 1)
a = ANNR([4], [('F', 4), ('AF', 'tanh'), ('F', 1)], maxIter = 16, name = 'mlpr1')
a.fit(A, Y)
S = a.score(A, Y)
YH = a.predict(A)
The error i received is: AttributeError: module 'tensorflow' has no attribute 'variable_scope'
Can someone tell me why i received this error and how can i fix this?
Many thanks!

Related

AttributeError: type object 'PartialDependenceDisplay' has no attribute 'from_estimator'

I'm trying to implement Partial Dependence Plot using the following example:
from sklearn.inspection import PartialDependenceDisplay
from sklearn.datasets import make_friedman1
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
X, y = make_friedman1()
est1 = LinearRegression().fit(X, y)
est2 = RandomForestRegressor().fit(X, y)
disp1 = PartialDependenceDisplay.from_estimator(est1, X,
[1, 2])
disp2 = PartialDependenceDisplay.from_estimator(est2, X, [1, 2],
ax=disp1.axes_)
But I get the following error:
AttributeError Traceback (most recent call last)
<ipython-input-7-e98f23dac323> in <module>
6 est1 = LinearRegression().fit(X, y)
7 est2 = RandomForestRegressor().fit(X, y)
----> 8 disp1 = PartialDependenceDisplay.from_estimator(est1, X,
9 [1, 2])
10 disp2 = PartialDependenceDisplay.from_estimator(est2, X, [1, 2],
AttributeError: type object 'PartialDependenceDisplay' has no attribute 'from_estimator'
Is there any solution for this?
Thanks
I had same issue (Windows 10, Python 3.9.7 on Anaconda).
Issue resolved with upgrade sklearn package
!pip install --upgrade scikit-learn

Numpy in VS Code Ubuntu 20.04

I am new to Ubuntu and is trying to get Numpy working on VS Code. Following is my code:
import matplotlib.pyplot as plt
import numpy as np
x = [1,2,3,4]
y = [3,5,7,9]
plt.grid(True)
plt.xlabel("My X values")
plt.ylabel("My Y values")
plt.plot(x,y, 'b-^', lineWidth = 3, markersize = 7, label = "Blue Line")
plt.legend(loc = "upper center")
plt.show()
But the debugger gives me the following error:
No module named 'numpy.core._multiarray_umath'
Does anyone knows how to install that module? Thank you so much in advance.

Error:'NoneType' object has no attribute '_inbound_nodes'

I've been trying to encode a model that uses a squeeze-exctitation block.
I'm cluless about the error. Please suggest alternatives.
import keras
from keras.models import Sequential,Model
from keras.layers import,Input,Dense,Conv2D,MaxPooling2D,Flatten,GlobalAveragePooling2D,BatchNormalization,Lambda,Conv2DTranspose,Reshape,Add,Multiply
import numpy as np
import io
x_inp=Input(shape=(6,8,128))
print(np.shape(x_inp))
def SEblock(x,cn):
sh_x=x
x=GlobalAveragePooling2D()(x)
x=Dense(cn//16,activation='relu')(x)
x=Dense(cn,activation='sigmoid')(x)
x=Reshape((1,1,cn))(x)
x=sh_x*x
y=GlobalAveragePooling2D()(x)
return y
y=SEblock(x_inp,128)
model=Model(inputs=x_inp,outputs=y)
Error message when the above code was run:
node = layer._inbound_nodes[node_index]
AttributeError: 'NoneType' object has no attribute '_inbound_nodes'
Replace
x=sh_x*x
with
x = Multiply()([sh_x, x])

Save and load a Pytorch model

i am trying to train a pytorch model on colab then save the model parameters and load it on my local computer.
After training, the model parameters are stored as below:
torch.save(Model.state_dict(),PATH)
loaded as below:
device = torch.device('cpu')
Model.load_state_dict(torch.load(PATH, map_location=device))
error:
AttributeError: 'Sequential' object has no attribute 'copy'
Does anyone know how to solve this issue?
Your question does not provide sufficient details to be answered correctly. If you are trying to save and load your own model and have a class definition for it see this well known answer and clarify why that's not sufficient for your use.
If you are loading a torch.nn.Sequential model then as far as I know simply loading the model directly and just using it should be sufficient. If it's not post on the pytorch forum what error you get.
For now look at my example show casing loading a sequential model and then using it without error:
# test for saving everything with torch.save
import torch
import torch.nn as nn
from pathlib import Path
from collections import OrderedDict
import numpy as np
import pickle
path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)
num_samples = 3
Din, Dout = 1, 1
lb, ub = -1, 1
x = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples, Din))
f = nn.Sequential(OrderedDict([
('f1', nn.Linear(Din,Dout)),
('out', nn.SELU())
]))
y = f(x)
# save data torch to numpy
x_np, y_np = x.detach().cpu().numpy(), y.detach().cpu().numpy()
db2 = {'f': f, 'x': x_np, 'y': y_np}
torch.save(db2, path / 'db_f_x_y')
db3 = torch.load(path / 'db_f_x_y')
f3 = db3['f']
x3 = db3['x']
y3 = db3['y']
xx = torch.tensor(x3)
yy3 = f3(xx)
print(yy3)
there should be an official answer how to save and load nn.Sequential models How does one save torch.nn.Sequential models in pytorch properly? but for now torch.save and torch.load seem to work just fine.

Creating PDF using pydot

I got the below code from Visualizing a Decision Tree - Machine Learning
import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
test_idx = [0, 50 , 100]
train_target = np.delete(iris.target, test_idx)
train_data = np.delete(iris.data, test_idx , axis=0)
test_target = iris.target[test_idx]
test_data = iris.data[test_idx]
clf = tree.DecisionTreeClassifier()
clf.fit(train_data, train_target)
print(test_target)
print(clf.predict(test_data))
#viz_code
from sklearn.externals.six import StringIO
import pydot
dot_data = StringIO()
tree.export_graphviz(clf,
out_file=dot_data,
feature_names = iris.feature_names,
class_names = iris.target_names,
filled = True, rounded = True,
impurity = False)
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph.write_pdf("iris.pdf")
I tried to run it in my python 3.5 but i get an error saying that graph is a list.
Traceback (most recent call last):
File "Iris.py", line 31, in <module>
graph.write_pdf("iris.pdf")
AttributeError: 'list' object has no attribute 'write_pdf'
Press any key to continue . . .
How come graph here is a list?
I think this is a duplicate, here is answered the same question link
because pydot.graph_from_dot_data return a list the solution is:
graph = pydot.graph_from_dot_data(dot_data.getvalue())
graph[0].write_pdf("iris.pdf")
This solved the problem for me with Python 3.6.5 :: Anaconda, Inc.
Pydot will not work in Python3.
You can use Pydotplus (graph.write_pdf("iris.pdf") AttributeError: 'list' object has no attribute 'write_pdf'") for python3 instead of pydot.
Although, the code shown on youtube is for Python2. So, it will be better if you use Python2.

Resources