graph-tool - 'NestedBlockState' object has no attribute 'get_nonempty_B' - python

I am trying to replicate a section of code from the graph-tool cookbook to find the marginal probablity of the number of groups in a graph when using hierarchical partitioning. I however get an error telling me that 'NestedBlockState' object has no attribute 'get_nonempty_B' so presumably I have made a mistake somewhere. Does anybody know where I went wrong?
import graph_tool.all as gt
import cPickle as pickle
g = gt.load_graph('graph_no_multi_reac_type.gt')
gt.remove_parallel_edges(g)
state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
state = state.copy(sampling=True)
with open('state_mcmc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
print 'equilibrating Markov chain'
gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
h = np.zeros(g.num_vertices() + 1)
def collect_num_groups(s):
B = s.get_nonempty_B()
h[B] += 1
print 'colleting marginals'
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
callback=collect_num_groups)
with open('state_ncnc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
with open('hist.pkl','wb') as h_pkl:
pickle.dump(h,h_pkl,-1)
The error I get looks as follows:
Traceback (most recent call last):
File "num_groups_marg_prob.py", line 42, in <module>
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
File "/usr/lib/python2.7/dist-packages/graph_tool/inference/mcmc.py", line 172, in mcmc_equilibrate
extra = callback(state)
File "num_groups_marg_prob.py", line 35, in collect_num_groups
def collect_num_groups(s):
AttributeError: 'NestedBlockState' object has no attribute 'get_nonempty_B'

Quoting from an answer from the graph-tool mailing list:
"The error message is clear. This attribute belongs to BlockState, not
NestedBlockState. What you wish to do is:
s.levels[0].get_nonempty_B()
"
http://main-discussion-list-for-the-graph-tool-project.982480.n3.nabble.com/self-state-couple-state-state-state-entropy-args-Python-argument-types-did-not-match-C-signature-td4026975.html

Related

Uber Ludwig: Issue Making Predictions

I decided to mess with Uber Ludwig again. I wanted to make a simple demo using the python API that learns to add 1 to the input number. I have successfully produced a model, but the issue arises when predicting. I am running on the newest release from github on PopOS 19.10 on CPU TensorFlow.
Thank you for any help.
Edit: I have reproduced the issue on windows as well.
The error is as follows
Traceback (most recent call last):
File "predict.py", line 3, in <module>
x = model.predict({"numberIn":[1]}, return_type='dict')
File "/home/user/.local/lib/python3.7/site-packages/ludwig/api.py", line 914, in predict
gpu_fraction=gpu_fraction,
File "/home/user/.local/lib/python3.7/site-packages/ludwig/api.py", line 772, in _predict
self.model_definition['preprocessing']
File "/home/user/.local/lib/python3.7/site-packages/ludwig/data/preprocessing.py", line 159, in build_data
preprocessing_parameters
File "/home/user/.local/lib/python3.7/site-packages/ludwig/data/preprocessing.py", line 180, in handle_missing_values
dataset_df[feature['name']] = dataset_df[feature['name']].fillna(
AttributeError: 'list' object has no attribute 'fillna'
Here is my prediction script
from ludwig.api import LudwigModel
model = LudwigModel.load("/home/user/Documents/ludwig-test/plus1/results/api_experiment_run_0/model")
x = model.predict({"numberIn":[1]}, return_type='dict')
#x = model.predict({"numberIn":[1]}, return_type=<class 'dict'>) I tried this with no success
print(x)
Here is the contents of my training script.
mydata = {"numberIn":[], "value":[]}
for x in range(10000):
mydata["numberIn"].append(x)
mydata["value"].append(x + 1)
from ludwig.api import LudwigModel
print("Imported Ludwig")
modelobject = LudwigModel(model_definition_file="modeldef.yaml")
stats = modelobject.train(data_dict=mydata)
modelobject.close()
modeldef.yaml
input_features:
-
name: numberIn
type: numerical
output_features:
-
name: value
type: numerical
Solution: Input argument of predict function is not positional and data_dict needs to be specified in this case.
x = modelobject.predict(data_dict=mydictionary)

Code error with variable storage from selected feature

I'm using QGIS 3.6 with the built in Python text editor. I have found a snippet of code that I'm trying to make work, and I've modified it to the best of my abilities to fit my specific needs. I have a point layer called "Regulators" and it contains a field called "Town". The idea of the code is that when I select a single feature on the "Regulators" layer, the code will look at the "Town" field, and select all other features that match that field's value. I select a feature, run this code:
layer = iface.activeLayer()
field_name = 'Town'
values = []
for feat in layer.selectedFeatures():
tmp_value = feat[field_name]
if tmp_value not in values:
values.append(str(tmp_value))
strings = []
for val in values:
if val != values[-1]:
string = field_name + ' = ' + val + ' or '
strings.append(string)
else:
last_string = field_name + ' = ' + val
strings.append(last_string)
query = ''.join(strings)
request = QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry)
request.setSubsetOfAttributes([]).setFilterExpression(query)
selection = layer.getFeatures(request)
layer.setSelectedFeatures([k.id() for k in selection])
and I get this error:
Traceback (most recent call last):
File "C:\PROGRA~1\QGIS3~1.6\apps\Python37\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "<string>", line 24, in <module>
AttributeError: 'QgsVectorLayer' object has no attribute 'setSelectedFeatures'
I'm very much new to python, and see nothing wrong with line 1 or 5. I have found some other codes that do what I'm attempting here, but they also return errors, so I'm wondering if there is some method or function that has changed since this code was posted. The integrated compiler with QGIS is also much different than I am used to.
EDIT: I've updated the code and the error message based on feedback I've received on the post so far. I assume that QgsVectorLayer is the generic term for a vector layer being referenced, in this case the "Regulators" layer. but I don't understand why it's trying to use the setSelectedFeatures method as an attribute.

Python - Delete from Array while enumerating

Error:
Traceback (most recent call last):
File "<string>", line 10, in <module>
File "/Users/georg/Programmierung/Glyphs/Glyphs/Glyphs/Scripts/GlyphsApp.py", line 59, in __iter__
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_convenience.py", line 589, in enumeratorGenerator
yield container_unwrap(anEnumerator.nextObject(), StopIteration)
objc.error: NSGenericException - *** Collection <__NSArrayM: 0x7f9906245480> was mutated while being enumerated.
I know this error occurs because I'm trying to delete objects from the array while also enumerating these objects. But I don't know how to solve it. I'm fairly new to object orientated programming and am limiting myself to scripting.
I searched the web and it seems to solve the error, I have to copy the array before deleting objects from it. When I'm tying to copy the array via deepcopy
import copy
pathcopy = copy.deepcopy(thisLayer.paths)
right before for path in thisLayer.paths:
But in this case I get the following error:
Cannot pickle Objective-C objects
Usually the program crashes after the first Glyph. For clarification: I work in Glyphsapp, a Typedesigning software.
Here is the Code:
# loops through every Glyph and deletes every path with nodes on the left half
for myGlyph in Glyphs.font.glyphs:
glname = myGlyph.name
thisLayer = Glyphs.font.glyphs[glname].layers[1]
middle = thisLayer.bounds.size.width/2+thisLayer.LSB
thisGlyph = thisLayer.parent
for path in thisLayer.paths: # this is where the code crashes
for thisNode in path.nodes:
if thisNode.position.x < middle:
#print thisNode.position.x
try:
thisLayer = path.parent()
except Exception as e:
thisLayer = path.parent
try:
thisLayer.removePath_ ( thisNode.parent() )
except AttributeError:
pass
Thank you in advance
Thank you very much Andreas,
with your help I was able to fix my code :-)
Here is the outcome:
for myGlyph in Glyphs.font.glyphs:
glname = myGlyph.name
thisLayer = Glyphs.font.glyphs[glname].layers[1]
middle = thisLayer.bounds.size.width/2+thisLayer.LSB
thisGlyph = thisLayer.parent
for path in thisLayer.paths:
for thisNode in path.nodes:
if thisNode.position.x < middle:
nodeList = []
nodeList.append(thisNode.parent())
nLCopy = nodeList[:]
for ncontainer in nLCopy:
thisLayer.removePath_ ( ncontainer )

Gettin error message 'NameError: global name 'randint' is not defined'

I have written a module memories.py using Python 2.7 (unfortunately, I cannot use the latest version due to some restriction). It looks as follows.
import random
def get_a_random_memory(length, upper_sum_range, lower_sum_range):
# Start with a blank memory
memory = list()
# For each bit along the length we add a random value
for i in range(0, length):
memory.append((2 * random.randint(0, 1) - 1))
return memory
The error message is as follows.
>>> import memories
>>> print memories.get_a_random_memory(5, 0, 10)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "xyz\memories.py", line 21, in get_a_random_memory
# For each bit along the length we add a random value
NameError: global name 'randint' is not defined
Could anyone please help me out here?

Python TypeError: 'float' object has no attribute '__getitem__'

Anybody knows how to solve this problem? I'm studying collective intelligence now, and I compared with another example when I made this code. But It's getting error like this:
Traceback (most recent call last): File "<pyshell#8>", line 1, in
<module>
clust=clusters.hcluster(data) File "D:\Kuliah\smt1\Phyton Class\contoh coding\coding-collective
intelligence\myself_Maulida\bab3-documentClustering\clusters.py", line
78, in hcluster
for i in range(len(clust[0].vec))] TypeError: 'float' object has no attribute '__getitem__'
Here is my code, anybody can help? Thank you.
def hcluster(rows,distance=pearson):
distances={}
currentclustid=-1
#clusters are initially just the rows
clust=[bicluster(rows[i],id=i) for i in range(len(rows))]
while len(clust)>1:
lowestpair=(0.1)
closest=distance(clust[0].vec,clust[1].vec)
#loop through every pair looking for the smallest distance
for i in range(len(clust)):
for j in range(i+1,len(clust)):
#distance is the cache of distance calculations
if(clust[i].id,clust[j].id) not in distances:
distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec)
d=distances[(clust[i].id,clust[j].id)]
if d<closest:
closest=d
lowestpair=(i,j)
#calculate the average of the two cluster
mergevec=[
(clust[lowestpair[0]].vec[i]+clust[lowestpair[1]].vec[i])/2.0
for i in range(len(clust[0].vec))]
#create the new cluster
newcluster=bicluster(mergevec,left=clust[lowestpair[0]],
right=clust[lowestpair[1]],
distance=closest,id=currentclustid)
#cluster ids that weren't in the original set are negative
currentclustid-=1
del clust[lowestpair[1]]
del clust[lowestpair[0]]
clust.append(newcluster)
return clust[0]
lowestpair=(0.1)
That's a period, not a comma. lowestpair is a float, rather than a tuple. (While it looks like the error comes from clust[0], Python tracebacks aren't very good at pointing out which physical line of a logical line an error comes from.)

Categories