I am new to Dymola and I want to run a linearized model with initial conditions.
I know how to Linearize it. I can get the StateSpace object in Command window or get the dslin.mat.
Now I want to run it with initial conditions. I found them in the dsin.txt file, but cant bring them together.
Is there an implemented way or do I need to write it on my own?
Best regards,
Axel
You can use the block Modelica.Blocks.Continuous.StateSpace to build a model containing a state-space description, as shown below:
The respective code is:
model StateSpaceModel
Modelica.Blocks.Continuous.StateSpace sys annotation (Placement(transformation(extent={{-10,-10},{10,10}})));
Modelica.Blocks.Sources.Step step(startTime=0.5) annotation (Placement(transformation(extent={{-60,-10},{-40,10}})));
equation
connect(step.y, sys.u[1]) annotation (Line(points={{-39,0},{-12,0}}, color={0,0,127}));
annotation (uses(Modelica(version="4.0.0")));
end StateSpaceModel;
Additionally you can use a script (or a Modelica function) that does some work for you. More precisely, it
linearizes any suitable model. I've used the state-space model from the MSL itself, so you can be sure the result is correct.
translates the above model to be able to set the parameters from the command line
sets the parameters of the state-space block called sys. This includes the ones for the initial conditions in x_start
simulates the model with the new parameters
// Get state-space description of a model
ss = Modelica_LinearSystems2.ModelAnalysis.Linearize("Modelica.Blocks.Continuous.StateSpace");
// Translate custom example, set parameters to result of the above linearization, add initial conditions for states and simulate
translateModel("StateSpaceModel")
sys.A = ss.A;
sys.B = ss.B;
sys.C = ss.C; // in case of an error here, check if 'OutputCPUtime == false;'
sys.D = ss.D;
sys.x_start = ones(size(sys.A,1));
simulateModel("StateSpaceModel", resultFile="StateSpaceModel");
Related
I have a model which I trained using a specific dataset. I did not originally break the set up into a train and test set (which I should have). With that said, I want to do some adhoc testing to see how the model performs when I give it specific images. I tried doing something like Images.load("/Users/logankilpatrick/Desktop/train/dog.10697.jpg") to load the image and then pass it directly to the model but I get inout size mismatch errors. What is the correct way to load the image?
To use an image for inference, you need to do a few steps as shown below:
x = Images.load("/Users/logankilpatrick/Desktop/train/dog.10697.jpg")
x = Images.imresize(x, (224,224)...) # 224x224 depends on the model size
x = permutedims(channelview(x), (3,2,1))
# Channelview returns a view of A, splitting out (if necessary) the color channels of A into a new first dimension.
x = reshape(x, size(x)..., 1) # Add an extra dim to show we only have 1 image
float32.(x) # Convert to float32 instead of float64
model(x)
Note that a few of these may change depending on the model you are using and other factors but this is the general idea of what you need to do. It is likely work it to write up a simple function that does this for you.
In RWeka classifiers, there is an attribute "options" in the classifier's function call, e.g. Bagging(formula, data, subset, na.action, control = Weka_control(), options = NULL). Could some one please give an example (a sample R code) on how to define these options?
I would be interested in passing on some options (such as the number of iterations and size of each bag) to Bagging meta learner of RWeka. Thanks in advance!
You can get at the features that you mentioned, but not through options.
First, what does options do? According to the help page ?Bagging
Argument options allows further customization. Currently, options model and instances (or partial matches for these) are used: if set to TRUE, the model frame or the corresponding Weka instances, respectively, are included in the fitted model object, possibly speeding up subsequent computations on the object. By default, neither is included.
So options simply stores more information in the returned result. To get at the features that you want, you need to use control. You will need to construct the value for control using the function Weka_control. Without some help, it is hard to know how to use that, but luckily, help is available through WOW the Weka Option Wizard. Because there are many options, the output is long. I am going to truncate it to just the part about the features that you mentioned - the number of iterations and size of each bag. But do look at what else is available.
WOW(Bagging)
-P Size of each bag, as a percentage of the training set size. (default 100)
-I <num>
Number of iterations. (current value 10)
Number of arguments: 1.
Repeating: I have truncated the output to show just these two options.
Example: Iris data
Suppose that I wanted to use bagging with the iris data with the bag size being 90% of the data (instead of the default 100%) and with 20 iterations (instead of the default 10). First, I would build the Weka_control, then include that in my call to Bagging.
WC = Weka_control(P=90, I=20)
BagOfIrises = Bagging(Species ~ ., data=iris, control=WC)
I hope that this helps.
I have two graphs, which I suppose to train them independently, which means I have two different optimizers, but at the same time one of them is using the tensor values of the other graph. As a result, I need to be able to stop specific tensors being updated while training one of the graphs. I have assigned two different namescopes two my tensors and using this code to control updates over tensors for different optimizers:
mentor_training_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "mentor")
train_op_mentor = mnist.training(loss_mentor, FLAGS.learning_rate, mentor_training_vars)
mentee_training_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "mentee")
train_op_mentee = mnist.training(loss_mentee, FLAGS.learning_rate, mentee_training_vars)
the vars variable is being used like below, in the training method of mnist object:
def training(loss, learning_rate, var_list):
# Add a scalar summary for the snapshot loss.
tf.summary.scalar('loss', loss)
# Create the gradient descent optimizer with the given learning rate.
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
# Create a variable to track the global step.
global_step = tf.Variable(0, name='global_step', trainable=False)
# Use the optimizer to apply the gradients that minimize the loss
# (and also increment the global step counter) as a single training step.
train_op = optimizer.minimize(loss, global_step=global_step, var_list=var_list)
return train_op
I'm using the var_list attribute of the optimizer class in order to control vars being updated by the optimizer.
Right now I'm confused whether I have done what I supposed to do appropriately, and even if there is anyway to check if any optimizer would only update partial of a graph?
I would appreciate if anyone can help me with this issue.
Thanks!
I have had a similar problem and used the same approach as you, i.e. via the var_list argument of the optimizer. I then checked whether the variables not intended for training stayed the same using:
the_var_np = sess.run(tf.get_default_graph().get_tensor_by_name('the_var:0'))
assert np.equal(the_var_np, pretrained_weights['the_var']).all()
pretrained_weights is a dictionary returned by np.load('some_file.npz') which I used to store the pre-trained weights to disk.
Just in case you need that as well, here is how you can override a tensor with a given value:
value = pretrained_weights['the_var']
variable = tf.get_default_graph().get_tensor_by_name('the_var:0')
sess.run(tf.assign(variable, value))
I am trying to use h2o to create an autoencoder using its deeplearning function. I am feeding a set of data about 4000x50 in size to the deeplearning function (hidden node c(200)) and then using h2o.mse to check its error and I am getting about 0.4, a fairly high value.
Is there anyway to reduce that error by changing something in the deeplearning function?
I assume everything is the defaults, except defining a single hidden layer with 200 nodes?
Your first set of things to try are:
Use more epochs (or use less aggressive early stopping criteria)
Use a 2nd hidden layer
Use more nodes in your hidden layer(s)
Get more training data
Note that all of those will increase your training time.
You can use H2OGridSearch to find the best autoencoder model with the smallest MSE.
Below is an example in Python. Here you can find example in R.
def tuneAndTrain(hyperParameters, model, trainDataFrame):
h2o.init()
trainData=trainDataFrame.values
trainDataHex=h2o.H2OFrame(trainData)
modelGrid = H2OGridSearch(model,hyper_params=hyperParameters)
modelGrid.train(x=list(range(0,int(len(trainDataFrame.columns)))),training_frame=trainDataHex)
gridperf1 = modelGrid.get_grid(sort_by='mse', decreasing=True)
bestModel = gridperf1.models[0]
return bestModel
And you can call the above function to find and train the best model:
hiddenOpt = [[50,50],[100,100], [5,5,5],[50,50,50]]
l2Opt = [1e-4,1e-2]
hyperParameters = {"hidden":hiddenOpt, "l2":l2Opt}
bestModel=tuneAndTrain(hyperParameters,H2OAutoEncoderEstimator(activation="Tanh", ignore_const_cols=False, epochs=200),dataFrameTrainPreprocessed)
Here is a snippet of R script doing beta regression on data "GasolineYield":
library("betareg")
data("GasolineYield", package = "betareg")
gy_logit <- betareg(yield ~ batch + temp, data = GasolineYield)
gy_logit4 <- update(gy_logit, subset = -4)
The 4th line magically deletes the 4th observation and update the fit automatically, but I don't quite understand the why this parameter works in the update function here, because I tried to look up the documentation by ?update, but couldn't find there's such parameter.
I'm curious about how to find right documentation in this case, because maybe I want to add some new observation instead of removing it. Any help?
subset in betareg works the same as subset in lm, therefore you can read lm documentation.
From the help file you can find:
subset an optional vector specifying a subset of observations to be used in the fitting process.
Hence by setting select=-4 you are lefting out the fourth row in the estimation.
update() contains the ... parameter, which means any parameters that are not matched in your call to update() are passed on to the function that does the estimation. In this case, that is betareg(), which does have the subset argument.
This type of thing is very common in R. Many higher-level function that call other user-visible functions will have the three dot parameter and pass any unmatched parameters on, so you have to search all the user-visible functions that get called in order to know all possible options.
You can check out the help file for the top level function (update() in this case) to get an idea of which functions get the leftover parameters.