Trained model (in session) and save-load model results differ by huge margin (very high MAE in session trained model) - tf.keras

Problem:
If I save and load model (ANN model) in the same session, the result from the loaded model is different to the model already in the session (prior to saving)
Ideally shouldn’t a trained model (in session/memory) and loaded model (post save and load) be identical?
I searched but have not found any leads yet. Any help/leads would be appreciated. Thanks in advance
Error Message:
There is no error message
But in my case, the results from the session model (ANN) are very bad (unreasonable with very high MAE) and the results from the loaded model (saved session model) are satisfactory (Fairly good MAE). Am not able to understand, why such a huge difference?
Code as below
#This give bad results
xyz_forecast = xyzDemandForecast(variable_collection)
modelframe_dict, history_dict = xyz_forecast.fit(
['train_1','train_2','train_3'],
['validation'],
train_test_config=pipeline_config,
)
result_df = xyz_forecast.predict(
[test_df], "xyz_DEMAND_POT", predict_config=pipeline_config
)
#This gives good result
xyz_forecast = xyzDemandForecast(variable_collection)
modelframe_dict, history_dict = xyz_forecast.fit(
['train_1','train_2','train_3'],
['validation'],
train_test_config=pipeline_config,
)
save_model(f"_forecaster_model_{EXPERIMENT_NAME}", xyz_forecast)
xyz_forecast = load_model(f"_forecaster_model_{EXPERIMENT_NAME}")
result_df = xyz_forecast.predict(
[test_df], "xyz_DEMAND_POT", predict_config=pipeline_config
)
#Save Code
def save_model(dir_name: str, forecaster_object: xyzDemandForecast):
if not os.path.isdir(dir_name):
os.mkdir(dir_name)
temp_model_dict = dict()
for model_name, model in forecaster_object.modelframe_dict.items():
file_name = _get_model_filename(model_name)
model.model_object.save(dir_name + f"/{file_name}") # model name
temp_model_dict[model_name] = tf.keras.models.clone_model(model.model_object)
model.model_object = None
pickle.dump(forecaster_object, open(dir_name + "/forecaster_object.pkl", "wb"))
for model_name, model in forecaster_object.modelframe_dict.items():
model.model_object = temp_model_dict[model_name] # model name
#Load Code
def load_model(dir_name: str):
forecaster_object = pickle.load(
open(dir_name + "/forecaster_object.pkl", "rb")
)
for model_name, model in forecaster_object.modelframe_dict.items():
file_name = _get_model_filename(model_name)
model.model_object = tf.keras.models.load_model(
dir_name + f"/{file_name}"
)
return forecaster_object

Related

STK MATLAB interface. Trying to access Range Rate data

I'm trying to get the Range Rate data between a satellite and ground site and everything works up until the last line. I've followed the online example but I get the error (below) when running this MATLAB script:
stk = stkApp.Personality2;
stkScenario = stk.CurrentScenario;
if isempty(stkScenario)
error('Please load a scenario');
end
facility = stk.GetObjectFromPath('Facility/RRFac');
satellite = stk.GetObjectFromPath('Satellite/P02S01');
access = satellite.GetAccessToObject(facility);
access.ComputeAccess;
accessDP = access.DataProviders.Item('Access Data').Exec(stkScenario.StartTime,stkScenario.StopTime);
accessStartTimes = accessDP.DataSets.GetDataSetByName('Start Time').GetValues;
accessStopTimes = accessDP.DataSets.GetDataSetByName('Stop Time').GetValues;
accessIntervals = access.ComputedAccessIntervalTimes;
accessDataProvider = access.DataProviders.Item('Access Data');
dataProviderElements = {'Start Time';'Stop Time'};
accessIntervals = access.ComputedAccessIntervalTimes;
for i = 1:1:accessIntervals.Count
[start, stop] = accessIntervals.GetInterval(i-1);
satelliteDP = satellite.DataProviders.Item('DeckAccess Data').Group.Item('Start Time LocalHorizontal Geometry').ExecElements(accessStartTimes{1},accessStopTimes{1},{'Time';'Range Rate'});
satelliteAlt = satelliteDP.DataSets.GetDataSetByName('Range Rate').GetValues;
end
Error using Interface.AGI_STK_Objects_12_IAgDrDataSetCollection/GetDataSetByName Invoke Error, Dispatch Exception: The parameter is incorrect.
Error in GenRRreport (line 37)
satelliteAlt = satelliteDP.DataSets.GetDataSetByName('Range Rate').GetValues
Why does it throw this error and how to avoid that?

Error when reloading new Plugin code in QGIS

I am nooby to Plugin Development but I'm trying to create a plugin in QGIS, for a Uni-subject, with its own graphical interface, which will receive a zipcode from the user and return the name of the corresponding location.
I already created the plugin skeleton, through the Plugin Builder and have designed the graphical interface with QtDesigner https://i.stack.imgur.com/h6k6Q.png . I also added the .txt file that contains the zipcodes database to the plugin folder as a resource.
From what I understand, the file to edit is the one that ends in dialog.py, through the init() method, in order to establish the connections between the signals emitted by the elements of the graphical interface and the corresponding callbacks.
However, when I change the code in the dialog.py and reload the plugin, it gives me an error, and when starting the QGIS it pop-ups an error message, and the plugin no longer appears. Error message after plugin reload
Could you give me some guidance here and maybe point me to where the problem could be? Thanks
The code is this one:
import os
import sys
import qgis.core
from qgis.PyQt import uic
from qgis.PyQt import (
QtCore,
QtWidgets
)
import geocoder
sys.path.append(os.path.dirname(__file__))
FORM_CLASS, _ = uic.loadUiType(
os.path.join(
os.path.dirname(__file__),
"example_dialog_base.ui"
),
resource_suffix=""
)
class ExampleDialog(QtWidgets.QDialog, FORM_CLASS):
POSTAL_CODES_PATH = ":/plugins/example/todos_cp.txt"
def __init__(self, parent=None):
"""Constructor."""
super(ExampleDialog, self).__init__(parent)
self.setupUi(self)
# connect signals
self.postal_code_le.textChanged.connect(self.toggle_find_button)
self.find_code_btn.clicked.connect(self.execute)
# set initial state
self.find_code_btn.setEnabled(False)
def toggle_find_button(self):
if self.postal_code_le.text() == "":
self.find_code_btn.setEnabled(False)
else:
self.find_code_btn.setEnabled(True)
def execute(self):
self.address_te.clear()
try:
raw_postal_code = self.postal_code_le.text()
main_code, extension = validate_postal_code(raw_postal_code)
record = self.find_record(main_code, extension)
place_name = record[3]
self.address_te.setPlainText(place_name)
if self.create_layer_chb.isChecked():
self.handle_layer_creation(record)
except (ValueError, RuntimeError) as err:
self.show_error(str(err))
def find_record(self, main_code, extension):
file_handler = QtCore.QFile(self.POSTAL_CODES_PATH)
file_handler.open(QtCore.QIODevice.ReadOnly)
stream = QtCore.QTextStream(file_handler)
while not stream.atEnd():
line = stream.readLine()
info = line.split(";")
code1 = info[-3]
code2 = info[-2]
if code1 == main_code and code2 == extension:
result = info
break
else:
raise RuntimeError("Sem resultados")
return result
def handle_layer_creation(self, record):
place_name = record[3]
point = geocode_place_name(place_name)
print("lon: {} - lat: {}".format(point.x(), point.y()))
layer = create_point_layer(
point,
f"found_location_for_{record[-3]}_{record[-2]}",
place_name
)
current_project = qgis.core.QgsProject.instance()
current_project.addMapLayer(layer)
def show_error(self, message):
message_bar = self.iface.messageBar()
message_bar.pushMessage("Error", message, level=message_bar.Critical)
def validate_postal_code(raw_postal_code):
code1, code2 = raw_postal_code.partition("-")[::2]
if code1 == "" or code2 == "":
raise ValueError(
"Incorrect postal code: {!r}".format(raw_postal_code))
return code1, code2
def geocode_place_name(place_name):
geocoder_object = geocoder.osm(place_name)
lon = geocoder_object.json.get("lng")
lat = geocoder_object.json.get("lat")
if lat is None or lon is None:
raise RuntimeError(
"Could not retrieve lon/lat for "
"place: {!r}".format(place_name)
)
point = qgis.core.QgsPointXY(lon, lat)
return point
def create_point_layer(point, layer_name, place_name):
layer = qgis.core.QgsVectorLayer(
"Point?crs=epsg:4326&field=address:string(100)",
layer_name,
"memory"
)
provider = layer.dataProvider()
geometry = qgis.core.QgsGeometry.fromPointXY(point)
feature = qgis.core.QgsFeature()
feature.setGeometry(geometry)
feature.setAttributes([place_name])
provider.addFeatures([feature])
layer.updateExtents()
return layer

Combination of Map Container and Structure in matlab

i would like to visualize what i will get after concatenation of map and struct in matlab , for instance let us consider following Map Container
ticketMap = containers.Map(...
{'2R175', 'B7398', 'A479GY', 'NZ1452'}, ...
{'James Enright', 'Carl Haynes', 'Sarah Latham', ...
'Bradley Reid'});
key/value structure of this map is clear for me, now let us suppose we have following structure
s1.ticketNum = '2S185'; s1.destination = 'Barbados';
s1.reserved = '06-May-2008'; s1.origin = 'La Guardia';
s2.ticketNum = '947F4'; s2.destination = 'St. John';
s2.reserved = '14-Apr-2008'; s2.origin = 'Oakland';
s3.ticketNum = 'A479GY'; s3.destination = 'St. Lucia';
s3.reserved = '28-Mar-2008'; s3.origin = 'JFK';
s4.ticketNum = 'B7398'; s4.destination = 'Granada';
s4.reserved = '30-Apr-2008'; s4.origin = 'JFK';
s5.ticketNum = 'NZ1452'; s5.destination = 'Aruba';
s5.reserved = '01-May-2008'; s5.origin = 'Denver';
we have 5 structure with different fields, now following commands
seatingMap = containers.Map( ...
{'23F', '15C', '15B', '09C', '12D'}, ...
{s5, s1, s3, s4, s2});
make sense for me because for instance using key 23F i can access fields of s1 structure, for instance
>> seatingMap('23F').origin
ans =
'Denver'
all those parts are clear for me, now Using ticketMap and seatingMap together, you can find the name of the person who has reserved seat 15B
ticket = seatingMap('15B').ticketNum;
passenger = ticketMap(ticket)
but is that optimal way?thanks in advance

loading data in bulk into a postgreSQL table that has a ForeignKey using SQLAlchemy

I have the following code in PostgreSQL/SQLAlchemy.
def load_books():
with open('C:\\Users\\books_raw.csv', 'r') as file:
for line in file.readlines():
record = line.split('$') # split at delimiter
book_isbn = record[0].strip('"')
book_title = record[1]
book_authors = record[2]
book_avg_rating = record[2]
book_format = record[4]
book_img_url = record[5]
book_num_pages = record[6]
book_pub_date = record[7]
book_publisher = record[8].strip() # ESTABLISH RELATIONSHIP
book = Books(title=book_title, isbn=book_isbn, authors=book_authors, avg_rating=book_avg_rating, format=book_format,
img_url=book_img_url, num_pages=book_num_pages, pub_date=book_pub_date, publisher=Publication(name=book_publisher))
session.add(book)
session.commit()
count = session.query(Books).count()
print(count, ' books added to the database')
My problem was with the relationship. If you see this part of the code:
publisher=Publication(name=book_publisher))
here i don't want the record to be inserted into the table, but just establish a relation with an existing record in the main table. Any ideas how i can achieve this ?
In for loop check if publisher in db or not if not in db then can create new one and save book with this publisher:
for line in file.readlines():
...
publisher=Publication.query.filter(name=book_publisher).first()
if not publisher:
publisher=Publication(name=book_publisher)
book = Books(..., publisher=publisher)
r = session.query(Publication).filter(Publication.name == book_publisher).first()
book = Books(title=book_title, isbn=book_isbn, authors=book_authors, avg_rating=book_avg_rating, format=book_format,
img_url=book_img_url, num_pages=book_num_pages, pub_date=book_pub_date, pub_id=r.id)
session.add(book)

How can you populate a WTForms FieldList after the validate_on_submit() block?

There is a real lack of documentation on how to work with WTForms' FieldList. So thanks to the internet I've been able to hack together the following:
Form:
class BranchForm(Form):
name = StringField('Name', validators = [Required()])
equipment = FieldList(SelectField('Equipment', validators=[Required()], coerce=int,
choices = [(x.id, x.name) for x in Equipment.query.all()]))
mod = FieldList(StringField('Method of Delivery', validators = [Optional()]))
View:
def edit_branch(id):
branch = Branch.query.filter_by(id=id).first()
#populate data_in to be used by BranchForm
data_in = []
for eq_obj in branch.equipment_assoc:
data_in.append(('equipment', eq_obj.equipment.id))
data_in.append(('mod', eq_obj.mod))
editform = BranchForm(data=MultiDict(data_in))
if editform.validate_on_submit():
branch.name = editform.name.data
db.session.add(branch)
db.session.commit()
return redirect('/admin/branches/' + str(branch.id))
editform.name.data = branch.name
return render_template("branch_edit.html",
title="Edit Branch",
branch = branch,
editform = editform)
What's throwing me off is that everywhere else that I've used a WTForm Form and populated the fields with data from my db (like for edit forms), I've had to populate these form fields after the form.validate_on_submit() block, because if not, then the form will never update as whatever is submitted is immediately overwritten.
See "editform.name.data = branch.name" (this is how I've always done it)
From every example I've found online about populating a FieldList, it apparently must be done during instantiation, but the form has to be instantiated before the validate_on_submit() as well because validate_on_submit() is a method of the form object.
See "editform = BranchForm(data=MultiDict(data_in))" (this is how I've seen FieldLists populated in all the examples I've seen.)
How can I go about populating my form with its field lists?
Alright, so a buddy helped me figure this one out. Here's what I ended up with:
Form:
class BranchForm(Form):
name = StringField('Name', validators = [Required()])
equipment = FieldList(SelectField('Equipment', validators=[Required()], coerce=int,
choices = [(x.id, x.name) for x in Equipment.query.all()]))
mod = FieldList(StringField('Method of Delivery', validators = [Optional()]))
def populate_assoc(self, branch_obj):
i = 0
branch_obj.name = self.name.data
for assoc_obj in branch_obj.equipment_assoc:
assoc_obj.equipment_id = self.equipment[i].data
assoc_obj.mod = self.mod[i].data
i += 1
View:
def edit_branch(id):
branch = Branch.query.filter_by(id=id).first()
if request.method == 'POST':
editform = BranchForm()
if editform.validate_on_submit():
editform.populate_assoc(branch)
db.session.add(branch)
db.session.commit()
return redirect('/admin/branches/' + str(branch.id))
#populate data_in to be used
data_in = []
for eq_obj in branch.equipment_assoc:
data_in.append(('equipment', eq_obj.equipment.id))
data_in.append(('mod', eq_obj.mod))
editform = BranchForm(data=MultiDict(data_in))
editform.name.data = branch.name
return render_template("branch_edit.html",
title="Edit Branch",
branch = branch,
editform = editform)
The trick was really to step away from using form.validate_on_submit() as my logic separator, since it relies on the form object. His idea was to use the if request.method == 'POST': for this purpose. This way I can instantiate my form in two different ways. One gets populated for display, the other is only instantiated if the request method is POST, thus retaining the information submitted in the form.
To finish the job I added the populate_assoc method to my form class so that I can easily place the information from the form into my association model.
WtForms has a populate_obj() method. Maybe that's what you're after?
def edit_branch(id):
branch = Branch.query.filter_by(id=id).first()
editform = BranchForm(obj=branch)
if editform.validate_on_submit():
editform.populate_obj(branch)
db.session.commit()
return redirect('/admin/branches/' + str(branch.id))
return render_template("branch_edit.html",
title="Edit Branch",
branch = branch,
editform = editform)