ImportError: cannot import name 'persist' - deep-learning

I want to persist a trained model in CNTK and found the 'persist' functionality after some amount of searching. However, there seems to be some error in importing it.
from cntk import persist
This is throwing ImportError.
Am I doing something the wrong way? Or is this no longer supported? Is there an alternate way to persist a model?

persist is from an earlier beta. save_model is now a method of every CNTK function. So instead of doing save_model(z, filename) you do z.save_model(filename). Load_model works the same as before but you import it from cntk.ops.functions. For an example, see: https://github.com/Microsoft/CNTK/blob/v2.0.beta7.0/Tutorials/CNTK_203_Reinforcement_Learning_Basics.ipynb or https://github.com/Microsoft/CNTK/blob/v2.0.beta7.0/bindings/python/cntk/tests/persist_test.py

The functionality has moved to cntk functions. The new way is mynetwork.save_model(...) where mynetwork represents the root of your computation (typically the prediction). For loading the model you can just say mynetwork = C.load_model(...)

Related

opening old xgboost pickles with the new xgboost version 'XGBClassifier' object has no attribute 'kwargs'

I was using xgboost version 0.6 when I pickled some pickle objects.
Now I upgraded to version 0.82 and when I'm trying to unpickle the old models I get:
AttributeError: 'XGBClassifier' object has no attribute 'kwargs'
I would really like to use these model without re training them, is there any way to open these pickles?
The new xgboost requires that objects will have a "kwargs" attribute, which old models do not have. One way to solve this is to downgrade to the old xgboost version, open them, add to each model the model.kwargs=None and then save them again, they should now work...
Another workaround is to hack the pickle file. You will load the pickle as a string, add the needed attribute and then load the pickle:
import re
xg_str = open('path_to_old_model.pkl').read()
kwargs_value= "kwargs'\np8\nNsS'"
new_xgboost = re.sub('colsample_bylevel', kwargs_value+"""colsample_bylevel""", xg_str)
new_model = pkl.loads(new_xgboost)
this adds "None" as the self.kwargs for your models. regex finds where the object attributes are declared, by searching for a known attribute in the model, "colsample_bylevel" and then adds before it another attribute.
To see how pickle encodes attributes you can create any class with some attributes and apply pkl.dumps to an instance. if it's a short class it will be pretty easy to read, that's how I got that "kwargs'\np8\nNsS'" means "kwargs=None".
Worked for me! I'm sure this can help with similar backwards compatibility issues with pickles, not neccesarily with this specific attribute.

Django MySQL Error (1146, "Table 'db_name.django_content_type' doesn't exist")

I am getting the error
django.db.utils.ProgrammingError: (1146, "Table 'db_name.django_content_type' doesn't exist")
when trying to do the initial migration for a django project with a new database that I'm deploying on the production server for the first time.
I suspected the problem might be because one of the the apps had a directory full of old migrations from a SQLite3 development environment; I cleared those out but it didn't help. I also searched and found references to people having the problem with multiple databases, but I only have one.
Django version is 1.11.6 on python 3.5.4, mysqlclient 1.3.12
Some considerations:
Are you calling ContentType.objects manager anywhere in your code that may be called before the db has been built?
I am currently facing this issue and need a way to check the db table has been built before I can look up any ContentTypes
I ended up creating a method to check the tables to see if it had been created, not sure if it will also help you:
def get_content_type(cls):
from django.contrib.contenttypes.models import ContentType
from django.db import connection
if 'django_content_type' in connection.introspection.table_names():
return ContentType.objects.get_for_model(cls)
else:
return None
As for migrations, my understanding is that they should always belong in your version control repo, however you can squash, or edit as required, or even rebuild them, this linked helps me with some migrations problems:
Reset Migrations
Answering my own question:
UMDA's comment was right. I have some initialization code for the django-import-export module that looks at content_types, and evidently I have never deployed the app from scratch in a new environment since I wrote it.
Lessons learned / solution:
will wrap the offending code in an exception block, since I should
only have this exception once when deploying in a new environment
test clean deployments in a new environment more regularly.
(edit to add) consider whether your migrationsdirectories belong in .gitignore. For my purposes they do.
(Relatively new to stackoverflow etiquette - how do I credit UMDA's comment for putting me on the right track?)
I had the same issue when trying to create a generic ModelView (where the model name would be passed as a variable in urls.py). I was handling this in a kind of silly way:
Bad idea: a function that returns a generic class-based view
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.contenttypes.models import ContentType
from django.views.generic.edit import DeleteView
def get_generic_delete_view(model_name):
model_type = ContentType.objects.get(app_label='myapp', model=model_name)
class _GenericDelete(LoginRequiredMixin, DeleteView):
model = model_type.model_class()
template_name = "confirm_delete.html"
return _GenericDelete.as_view()
urls.py
from django.urls import path, include
from my_app import views
urlpatterns = [
path("mymodels/<name>/delete/", views.get_generic_delete_view("MyModel"),
]
Anyway. Let's not dwell in the past.
This was fixable by properly switching to a class-based view, instead of whatever infernal hybrid is outlined above, since (according to this SO post) a class-based view isn't instantiated until request-time.
Better idea: actual generic class-based view
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.contenttypes.models import ContentType
from django.views.generic.edit import DeleteView
class GenericDelete(LoginRequiredMixin, DeleteView):
template_name = "confirm_delete.html"
def __init__(self, **kwargs):
model = kwargs.pop("model")
model_type = ContentType.objects.get(app_label='myapp', model=model)
self.model = model_type.model_class()
super().__init__()
urls.py
from django.urls import path, include
from my_app import views
urlpatterns = [
path("mymodels/<name>/delete/", views.GenericDelete.as_view(model="MyModel"),
]
May you make new and better mistakes.
Chipping in because maybe this option will appeal better in some scenarios.
Most of the project's imports usually cascade down from your urls.py. What I usually do, is wrap the urls.py imports in a try/except statement and only create the routes if all imports were successful.
What this accomplishes is to create your project's / app's routes only if the modules were imported. If there is an error because the tables do not yet exist, it will be ignored, and the migrations will be done. In the next run, hopefully, you will have no errors in your imports and everything will run smoothly. But if you do, it's easy to spot because you won't have any URLs. Also, I usually add an error log to guide me through the issue in those cases.
A simplified version would look like this:
# Workaround to avoid programming errors on greenfield migrations
register_routes = True
try:
from myapp.views import CoolViewSet
# More imports...
except Exception as e:
register_routes = False
logger.error("Avoiding creation of routes. Error on import: {}".format(e))
if register_routes:
# Add yout url paterns here
Now, maybe you can combine Omar's answer for a more sensible, less catch-all solution.

How to use flask-migrate with other declarative_bases

I'm trying to implement python-social-auth in Flask. I've ironed out tons of kinks whilst trying to interpret about 4 tutorials and a full Flask-book at the same time, and feel I've reached sort of an impasse with Flask-migrate.
I'm currently using the following code to create the tables necessary for python-social-auth to function in a flask-sqlalchemy environment.
from social.apps.flask_app.default import models
models.PSABase.metadata.create_all(db.engine)
Now, they're obviously using some form of their own Base, not related to my actual db-object. This in turn causes Flask-Migrate to completely miss out on these tables and remove them in migrations. Now, obviously I can remove these db-drops from every removal, but I can imagine it being one of those things that at one point is going to get forgotten about and all of a sudden I have no OAuth-ties anymore.
I've gotten this solution to work with the usage (and modification) of the manage.py-command syncdb as suggested by the python-social-auth Flask example
Miguel Grinberg, the author of Flask-Migrate replies here to an issue that seems to very closely resemble mine.
The closest I could find on stack overflow was this, but it doesn't shed too much light on the entire thing for me, and the answer was never accepted (and I can't get it to work, I have tried a few times)
For reference, here is my manage.py:
#!/usr/bin/env python
from flask.ext.script import Server, Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from app import app, db
manager = Manager(app)
manager.add_command('runserver', Server())
manager.add_command('shell', Shell(make_context=lambda: {
'app': app,
'db_session': db.session
}))
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
#manager.command
def syncdb():
from social.apps.flask_app.default import models
models.PSABase.metadata.create_all(db.engine)
db.create_all()
if __name__ == '__main__':
manager.run()
And to clarify, the db init / migrate / upgrade commands only create my user table (and the migration one obviously), but not the social auth ones, while the syncdb command works for the python-social-auth tables.
I understand from the github response that this isn't supported by Flask-Migrate, but I'm wondering if there's a way to fiddle in the PSABase-tables so they are picked up by the db-object sent into Migrate.
Any suggestions welcome.
(Also, first-time poster. I feel I've done a lot of research and tried quite a few solutions before I finally came here to post. If I've missed something obvious in the guidelines of SO, don't hesitate to point that out to me in a private message and I'll happily oblige)
After the helpful answer from Miguel here I got some new keywords to research. I ended up at a helpful github-page which had further references to, amongst others, the Alembic bitbucket site which helped immensely.
In the end I did this to my Alembic migration env.py-file:
from sqlalchemy import engine_from_config, pool, MetaData
[...]
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option('sqlalchemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
def combine_metadata(*args):
m = MetaData()
for metadata in args:
for t in metadata.tables.values():
t.tometadata(m)
return m
from social.apps.flask_app.default import models
target_metadata = combine_metadata(
current_app.extensions['migrate'].db.metadata,
models.PSABase.metadata)
This seems to work absolutely perfectly.
The problem is that you have two sets of models, each with a different SQLAlchemy metadata object. The models from PSA were generated directly from SQLAlchemy, while your own models were generated through Flask-SQLAlchemy.
Flask-Migrate only sees the models that are defined via Flask-SQLAlchemy, because the db object that you give it only knows about the metadata for those models, it knows nothing about these other PSA models that bypassed Flask-SQLAlchemy.
So yeah, end result is that each time you generate a migration, Flask-Migrate/Alembic find these PSA tables in the db and decides to delete them, because it does not see any models for them.
I think the best solution for your problem is to configure Alembic to ignore certain tables. For this you can use the include_object configuration in the env.py module stored in the migrations directory. Basically you are going to write a function that Alembic will call every time it comes upon a new entity while generating a migration script. The function will return False when the object in question is one of these PSA tables, and True for every thing else.
Update: Another option, which you included in the response you wrote, is to merge the two metadata objects into one, then the models from your application and PSA are inspected by Alembic together.
I have nothing against the technique of merging multiple metadata objects into one, but I think it is not a good idea for an application to track migrations in models that aren't yours. Many times Alembic will not be able to capture a migration accurately, so you may need to make minor corrections on the generated script before you apply it. For models that are yours, you are capable of detecting these inaccuracies that sometimes show up in migration scripts, but when the models aren't yours I think you can miss stuff, because you will not be familiar enough with the changes that went into those models to do a good review of the Alembic generated script.
For this reason, I think it is a better idea to use my proposed include_object configuration to leave the third party models out of your migrations. Those models should be migrated according to the third party project's instructions instead.
I use two models as following:-
One which is use using db as
db = SQLAlchemy()
app['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:' + POSTGRES_PASSWORD + '#localhost/Flask'
db.init_app(app)
class User(db.Model):
pass
the other with Base as
Base = declarative_base()
uri = 'postgresql://postgres:' + POSTGRES_PASSWORD + '#localhost/Flask'
engine = create_engine(uri)
metadata = MetaData(engine)
Session = sessionmaker(bind=engine)
session = Session()
class Address(Base):
pass
Since you created user with db.Model you can use flask migrate on User and class Address used Base which handles fetching pre-existing table from the database.

Using JUnit in Jython - NameError for assertTrue

Environment Details
Mac OS X 10.9
Oracle JDK 1.7.0_55 64-bit
jython-standalone-2.5.3.jar
junit-4.11
What I have done so far
I have added the junit jar to /Library/Java/Extensions.
I invoked Jython as follows java -jar jython-standalone-2.5.3.jar
In the Jython interpreter, I imported the following import org.junit.Assert, and this import was successful.
Problem
When I tried to use assertTrue, I got a NameError in the interpreter. Why is this so?
I understand that assertTrue is a static method. Not sure what implication this has when I try to use it in Jython.
Additional Context
I am using XMLUnit in Jython. Was able to successfully import the Diff class from org.custommonkey.xmlunit in Jython. Also able to use the methods in this class, and call them on a Diff object. The result of this method call is what I am trying to pass to assertTrue, when it throws the error.
from org.custommonkey.xmlunit import Diff
import org.junit.Assert
xml1 = ...some XML string...
xml2 = ...some XML string...
myDiff = Diff(xml1, xml2)
assertTrue(myDiff.similar())
Hope this additional information is useful in identifying a solution to this problem.
Latest Status
I narrowed it down to setting this property python.security.respectJavaAccessibility = false, since the Assert() constructor is protected.
Still trying to get it to work. Any help is greatly appreciated.
Figured it out.
In addition to junit.jar file, the hamcrest-core.jar file also needed to be copied to /Library/Java/Extensions.
Then I got rid of the jython.jar file, and instead installed it using the jython installer.
After the installation was completed, I updated the registry file in the installation folder, specifically setting this property python.security.respectJavaAccessibility = false.
Now I am able to see the assertTrue method, and no longer getting a NameError.

How to pass arguments to create_engine in Pylons application?

I'd like to customize database connection in Pylons application.
I'm interested in changing these arguments:
pool_size
pool_recycle
In SqlAlchemy the arguments are passed to *create_engine* call, like here:
http://docs.sqlalchemy.org/en/rel_0_9/core/engines.html?highlight=pool_size#sqlalchemy.create_engine
How can I change those params in Pylons?
you should be able to do it right in your ini file, it's been a while since I did pylons but IIRC, assuming you said yes to the sqlalchemy question when you created the project, all items prefixed with "slqalchemy." are given as keywords to the engine_from_config method in sqlalchemy. see the config/environment.py file for more.
sqlalchemy.url=<your db connection info>
sqlalchemy.pool_size= ??
sqlalchemy.pool_recycle= ??