- 14.2. Create a Model¶
- 14.2.1. Create a Model Class — Video¶
- 14.2.2. Create a Model Class — Text¶
- 14.2.3. Add a Model Property — Video¶
- 14.2.4. Add a Model Property — Text¶
- Model Class in Java
- Model Class
- Arguments
- Input
- Output
- Name
- Instantiation
- Simplified Approach
- Arguments
- line_length
- Positions
- Print_fn
- get_layer Approach
- Arguments
- Name
- Index
- Output
14.2. Create a Model¶
In the next several pages, we will be making updates to coding-events to demonstrate model creation, how models relate to data, and the practice of model binding. The first of these steps is to move data handling out of our controller classes and into a model class. As we discussed on the previous page, the controller class is not responsible for holding data.
In coding-events , we’ll remove the ArrayList data from EventController and create a proper Java class to deal with event items. We’ll then update our controller methods to take advantage of the new model and its properties, rather than the strings stored in the list. Lastly, because the controller is updating, the template variables it relies upon will also need to change to reflect the model properties.
14.2.1. Create a Model Class — Video¶
The starter code for this video is found at the add-bootstrap branch of coding-events-demo . The final code presented in this video is found on the create-model branch . As always, code along with the videos on your own coding-events project.
14.2.2. Create a Model Class — Text¶
Like controllers, model classes are conventionally located in a models package. Structurally, model classes most closely resemble the kinds of classes we practiced making at the start of this course, before introducing Spring Boot. In other words, models are plain old Java objects, or POJOs.
To create a model to shape event data, we include a field for name . Of course, we’ll also like at least one constructor and some getters and setters.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
public class Event private String name; public Event(String name) this.name = name; > public String getName() return name; > public void setName(String name) this.name = name; > @Override public String toString() return name; > >
Now that we’re working to move the data handling out from the controller classes and into a class of its own, we’ll need to update the POST handler that creates new events. Update the .add() method inside of processCreateEventForm to add a new Event instance:
@PostMapping("create") public String processCreateEventForm(@RequestParam String eventName) events.add(new Event(eventName)); return "redirect:"; >
And you’ll notice, we’re adding a different type of data to the ArrayList , so we’ll have to update that too:
private static ListEvent> events = new ArrayList<>();
Back in the events/index.html template, update the HTML to use the Event object’s fields, rather than simply strings.
The syntax event.fieldName runs a getter method behind the scenes in order to access a field.
14.2.3. Add a Model Property — Video¶
The starter code for this video is found at the create-model branch of the coding-events-demo repo. The final code presented in this video is found on the add-property branch . As always, code along to the videos on your own coding-events project.
14.2.4. Add a Model Property — Text¶
To round out the Event class, we’ll add a description field to showcase what our events are all about.
Updates to models/Event.java :
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
public class Event private String name; private String description; public Event(String name, String description) this.name = name; this.description = description; > public String getName() return name; > public void setName(String name) this.name = name; > public String getDescription() return description; > public void setDescription(String description) this.description = description; > @Override public String toString() return name; > >
Now that our data is object-oriented, it’s quick and easy to add a new property affiliated with an event. If after this, we decide to add a date or location field, we would simply follow the pattern established. Before, with events stored as name strings, we would have had more changes to make in order to add other information fields to the shape of the data.
Update both the events/create.html and events/index.html templates to create an event object with a description field and to display that description along with the event’s name.
label> Description input type="text" name="eventDescription" class="form-control"> label>
Model Class in Java
In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java.
Model Class
To «model» the content in your application, a model class is often required. You could, for instance, create a Model class which replicates a database table or a JSON. These classes’ objects could be utilized as means of sending and receiving data. In contrast to the arithmetic and scientific models, which are both more abstract models of the system, a modeling approach is a concrete illustration.
The layers can be combined into an object that has aspects like training and inference, which is particularly advantageous. Before to design or programming, it permits the establishment of a structural software or system model.
Let us discuss a simple example for better understanding.
For instance, using this tool, you may create model Java classes on JSON. See this. Because models are just plain old java objects, a model class is typically a POJO. However, you are free to create a POJO without employing it as the model.
Arguments
It possesses various arguments like
Input
It can be described as something of an input that the model receives. It can either be a list containing objects, such as keras.Input, or an object of input.
Output
It references to the model’s results.
Name
It could be a string which specifies the name of the model.
Instantiation
The two methods for instantiating the models are as follows:
- We’ll use «Functional API» to assist us in the first method. We will begin with the input, then connect the layer calls to indicate with a forward pass of a model, and then create the model by employing the inputs and outputs.
import tensorflow as tf inputs = tf.keras.Input(shape=(3,)) x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs) outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x) model = tf.keras.Model(inputs=inputs, outputs=outputs)
- By customizing the Model class, we will accomplish this in the second approach. Here, we’ll define the layers in _init_ before running the model’s forward pass in the call.
import tensorflow as tf class MyModel(tf.keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) def call(self, inputs): x = self.dense1(inputs) return self.dense2(x) model = MyModel()
In order to specify distinct behaviour in both training and inference, we can also subclass the Model and add an optional Boolean training argument to the call:
import tensorflow as tf class MyModel(tf.keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) self.dropout = tf.keras.layers.Dropout(0.5) def call(self, inputs, training=False): x = self.dense1(inputs) if training: x = self.dropout(x, training=training) return self.dense2(x) model = MyModel()
After building the model, we may configure it by adding losses and model-specific metrics. compile(). Using the model, the model could be trained. fit() and model assistance. The prediction function in the model can be used.
Simplified Approach
Model.summary(line_length=None, positions=None, print_fn=None)
Mostly in form of a string, it could be utilized to print the network summary.
Arguments
line_length
It is characterized as the total length of both the printed lines. Additionally, it can be configured to adjust for showing different terminals’ window sizes.
Positions
It refers to the position of each and every log element in a line, which may be either relative or absolute. If it isn’t given, the default value is set to [.33,.55,.67, 1.].
Print_fn
It can be used as a default print function that prints and is invoked after each line of a summary. It can be changed to the customized function in order to obtain the string summary.
Note: It may generate the value error if we call the summary() before building the model.
get_layer Approach
Model.get_layer(name=None, index=None)
It facilitates the discovery of a layer using either its distinctive name or index. In the event that both the name and the index are previously provided, the value will take precedence, allowing for the use of indices that are built from the bottom up (horizontal traversal graph).
Arguments
Name
It can be described as the name of the layer as a string.
Index
It references to that of an integer which represents the index of the layer.
Output
It generates an instance of a layer.
Note: If the layer’s name or index are incorrect, a value error gets displayed.