Loading hdf5 file Error - python-2.7

Here is my my code
import theano
import numpy
import os
from keras.models import Sequential
model2 = Sequential()
model2.load_weights("/home/console/Desktop/Apu_code/_epoch_0_e199-0.04.hdf5")
'''model = loaded_models('.)'''
print('loaded')
and getting error :
Using Theano backend.
Traceback (most recent call last):
File "try.py", line 7, in <module>
model2.load_weights("/home/console/Desktop/Apu_code/_epoch_0_e199-0.04.hdf5")
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 2369, in load_weights
str(len(flattened_layers)) + ' layers.')
Exception: You are trying to load a weight file containing 12 layers into a model with 0 layers.

I just do
model0 = keras.models.load_model(hdf5Fname)
to load the file into the variable model0 in order to do sth like
prediction0 = model0.predict( image)[0][0]
and so on...

Related

Pyomo generates "OSError: Unknown file format 'xls'" when trying to read an excel file in Spyder

My code is:
from __future__ import division
from pyomo.environ import *
import openpyxl
import xlrd
import pyutillib
import win32com
model = AbstractModel()
data = DataPortal()
model.A = Set(dimen=2)
model.p = Param(model.A)
data.load(filename='excel.xls', range='PPtable', param=model.p, index=model.A)
instance = model.create_instance(data)
The error I get:
runfile('C:/Users/faube/.spyder-py3/Pyomo Excel test.py', > > >wdir='C:/Users/faube/.spyder-py3')
Traceback (most recent call last):
File ~.spyder-py3\Pyomo Excel test.py:20 in
data.load(filename='excel.xls', range='PPtable',
File ~\Anaconda3\envs\LTSP\lib\site->packages\pyomo\dataportal\DataPortal.py:146 in load
self.connect(**kwds)
File ~\Anaconda3\envs\LTSP\lib\site-> packages\pyomo\dataportal\DataPortal.py:107 in connect
raise IOError("Unknown file format '%s'" % tmp)
OSError: Unknown file format 'xls'
Any idea? Thanks!

Error while loading .h5 model in Flask using keras

I have built a horse human detector using keras CNN on Google colab the model worked and loaded perfectly on colab. Now I am building a flask application while loading he .h5 model file I was getting error
TypeError: __init__() got an unexpected keyword argument 'ragged'
I reinstall keras 2.3.1 using pip and now I am getting a library error
NameError: name 'six' is not defined
my App.py
#Import necessary libraries
from flask import Flask, render_template, request
import numpy as np
import os
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model
#load model
model = load_model("predictor.h5" )
print("## model loaded")
def pred_human_horse(model , horse_or_human):
test_image = load_img(horse_or_human , target_size=(150,150)) #resize
print("## Got Image for predicton")
test_image = img_to_array(test_image)/255 #numpy array between 0-1
test_image = np.expand_dims(test_image,axis=0) #4 dimension
result= model.predict(test_image).round(3) #rounding off
pred =np.argmax(result)
print("## Raw results = ",result)
print("## class = ", pred)
if pred==0:
return "Horse"
else:
return "Human"
# Crate flask app
app = Flask(__name__)
#app.route("/",methods=["GET","POST"])
def home():
return render_template("index.html")
#app.route("/predict",methods=["GET","POST"])
def predict():
if request.method=="POST":
#get input image file
file = request.files["image"]
filename= file.filename
print("## File recieved",filename)
#save the file
file_path= os.path.join("static/user_uploaded",filename)
file.save(file_path)
print("## Prediction...")
pred=pred_human_horse(horse_or_human=file_path )
return render_template("predict.html" ,pred_output= pred , user_image=file_path )
if __name__=="__main__":
app.run(threaded=False)
Error I am getting
runfile('F:/INTERNSHIP/Crisp-Metric-MAY21/Human-horse-prediction/app.py', wdir='F:/INTERNSHIP/Crisp-Metric-MAY21/Human-horse-prediction')
Traceback (most recent call last):
File "<ipython-input-26-df590f092cb6>", line 1, in <module>
runfile('F:/INTERNSHIP/Crisp-Metric-MAY21/Human-horse-prediction/app.py', wdir='F:/INTERNSHIP/Crisp-Metric-MAY21/Human-horse-prediction')
File "C:\Users\DANIA NIAZI\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\Users\DANIA NIAZI\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "F:/INTERNSHIP/Crisp-Metric-MAY21/Human-horse-prediction/app.py", line 13, in <module>
model = load_model("predictor.h5" )
File "C:\Users\DANIA NIAZI\Anaconda3\lib\site-packages\keras\engine\saving.py", line 492, in load_wrapper
File "C:\Users\DANIA NIAZI\Anaconda3\lib\site-packages\keras\engine\saving.py", line 582, in load_model
File "C:\Users\DANIA NIAZI\Anaconda3\lib\site-packages\keras\utils\io_utils.py", line 211, in is_supported_type
NameError: name 'six' is not defined
Maybe you should try installing the six package which will be installed when installing Django. Anyway you can install it using:
pip install six

tensorflow SKCompat is not compatible with cross_val_score

I'm trying to use a tensorflow classifier with some tools from scikit learn, namely model_selection.cross_val_score. When I run the following code (adapted from this example from the tensorflow docs), I get a TypeError (see full traceback below).
From what I can tell the problem is that cross_val_score tries to clone the estimator by performing what amounts to estimator.__class__(**estimator.get_params(deep=True)). For some reason, SKCompat.get_params returns {}, the init method on the class requires one argument (as shown in the example code) so the operation blows up.
Am I doing something wrong? Or is this a bug with tensorflow?
Failing example
"""Example of DNNClassifier for Iris plant dataset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from sklearn import metrics
from sklearn import model_selection
import tensorflow as tf
def main(unused_argv):
# Load dataset.
iris = tf.contrib.learn.datasets.load_dataset('iris')
# Build 3 layer DNN with 10, 20, 10 units respectively.
feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input(
iris.data)
classifier = tf.contrib.learn.SKCompat(
tf.contrib.learn.DNNClassifier(
feature_columns=feature_columns,
hidden_units=[10, 20, 10],
n_classes=3
)
)
# Fit and predict.
scores = model_selection.cross_val_score(classifier, iris.data, iris.target,
scoring='accuracy')
print('Accuracy: {0:f}'.format(scores.mean()))
if __name__ == '__main__':
tf.app.run()
Traceback
Traceback (most recent call last):
File "iris.py", line 49, in <module>
tf.app.run()
File "/Users/Matt/.virtualenvs/numerai/lib/python2.7/site-packages/tensorflow/python/platform/app.py", line 48, in run
_sys.exit(main(_sys.argv[:1] + flags_passthrough))
File "iris.py", line 44, in main
scoring='accuracy')
File "/Users/Matt/.virtualenvs/numerai/lib/python2.7/site-packages/sklearn/model_selection/_validation.py", line 140, in cross_val_score
for train, test in cv_iter)
File "/Users/Matt/.virtualenvs/numerai/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 758, in __call__
while self.dispatch_one_batch(iterator):
File "/Users/Matt/.virtualenvs/numerai/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 603, in dispatch_one_batch
tasks = BatchedCalls(itertools.islice(iterator, batch_size))
File "/Users/Matt/.virtualenvs/numerai/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 127, in __init__
self.items = list(iterator_slice)
File "/Users/Matt/.virtualenvs/numerai/lib/python2.7/site-packages/sklearn/model_selection/_validation.py", line 140, in <genexpr>
for train, test in cv_iter)
File "/Users/Matt/.virtualenvs/numerai/lib/python2.7/site-packages/sklearn/base.py", line 70, in clone
new_object = klass(**new_object_params)
TypeError: __init__() takes exactly 2 arguments (1 given)
Versions
python: 2.7.3
tensorflow: 1.1.0
scikit-learn: 0.18.1

Got EOFError during loading doc2vec model

I could not load a doc2vec model on my computer and I got the following error. But, when I load that model on other computers, I can use that model.Therefore, I know the model was built correctly.
what should I do.
This is the code:
# coding: utf-8
from gensim.models.doc2vec import Doc2Vec
import gensim.models.doc2vec
from gensim.models.doc2vec import LabeledSentence
import os
import pickle
pth='/home/fatemeh/Step2/input-output/model/iterator'
model= Doc2Vec.load(pth+'/my_model.doc2vec')
This is the error:
Traceback (most recent call last):
File "CreateAnnoyIndex.py", line 16, in <module>
model= Doc2Vec.load(pth+'/my_model.doc2vec')
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/models/word2vec.py", line 1762, in load
model = super(Word2Vec, cls).load(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/utils.py", line 248, in load
obj = unpickle(fname)
File "/usr/local/lib/python2.7/dist-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/utils.py", line 912, in unpickle
return _pickle.loads(f.read())
EOFError
I think your model causes the problem. Are you check with same model? I mean build in a same way. please see this page

'module' object has no attribute 'DataReader

import pandas as pd
import pandas.io.data as web # as we have to use only pandas function
#Second, retrieve the data from, say, Google itself:
stock = web.DataReader('IBM',data_source='yahoo',start='01/01/2011', end='01/01/2013')
# end of question 1
print type(stock) # Class Type is pandas.core.frame.DataFrame
IBM_dataframe = pd.DataFrame(stock)
Traceback (most recent call last):
File "", line 2, in
import pandas.io.data as web # as we have to use only pandas function
File "C:\Anaconda2\lib\site-packages\pandas\io\data.py", line 2, in
"The pandas.io.data module is moved to a separate package "
ImportError: The pandas.io.data module is moved to a separate package (pandas-datareader). After installing the pandas-datareader package (https://github.com/pydata/pandas-datareader), you can change the import from pandas.io import data, wb to from pandas_datareader import data, wb.
import pandas_datareader as web
stock = web.DataReader('IBM',data_source='yahoo',start='01/01/2011', end='01/01/2013')
Traceback (most recent call last):
File "", line 1, in
stock = web.DataReader('IBM',data_source='yahoo',start='01/01/2011', end='01/01/2013')
AttributeError: 'module' object has no attribute 'DataReader'
change the import pandas.io.data as web to import pandas_datareader as web but now not able to get data plz suggest getting error
'module' object has no attribute 'DataReader'
Use the following:
from pandas_datareader import data, wb
DAX = data.DataReader(name='^GDAXI', data_source='yahoo',start='2000-1-1')