Deep Training
Train the complete graph for your model.
Clarifai offers a variety of prebuilt models that are designed to help you build AI solutions quickly and efficiently. Clarifai Models are the recommended starting point for many users because they offer incredibly fast training times when you customize them using the "Context-Based Classifier" type in Portal's Model Mode.
But there are many cases where accuracy and the ability to carefully target solutions takes priority over speed and ease of use. Additionally, you may need a model to learn new features not recognized by existing Clarifai Models. For these cases, it is possible to "deep train" your custom models and integrate them directly within your workflows.
In general, deep trained models need more data than ones trained on top of Clarifai Models. For most applications you’ll need at least 1000 training inputs, but it could be much more than this depending on your specific use case.
You might consider deep training if you have:
    A custom tailored dataset
    Accurate labels
    Expertise and time to fine tune models
Deep training is in early access preview. To request access, contact us.

Template types

You can take advantage of a variety of templates when building your deep trained models. Templates give you the control to choose the specific architecture used by your neural network, and also define a set of hyperparameters that you can use to fine-tune the way that your model learns.

Visual Classifier

Classification templates let you classify what is in your images or videos.

Visual Detector

Detection templates make it easy to build models that can identify objects within a region of your images or videos. Detection models return concepts and bounding boxes.

Visual Embedder

Embedding models can be useful in their own right (for applications like clustering and visual search), or as an input to a machine learning model for a supervised task. In effect, embedding templates enable you to create your own "base models" that you can then use in your workflows.

Hyperparameters

Deep training gives you the power to tune the hyperparameters that affect “how” your model learns. Model Mode dynamically changes the available hyperparameters based on the template selected.
    average_horizontal_flips Provides basic data augmentation for your dataset. If set to true, there is a 0.5 probability that current image and associated ground truth will flip horizontally.
    base_gradient_multiplier This sets the learning rate of the pre-initialized base (also sometimes called "backbone") model that generates embeddings. Learning rate controls how the weights of our network are adjusted with respect to the loss gradient. The lower the value, the slower the trip along the downward slope. A low learning rate can help ensure that local minima are not missed, but can take a long time to converge — especially if the model gets stuck on a plateau region.
    batch_size The number of images used to make updates to the model. Increased batch size allows for a better approximation of gradient over those samples. Batches allow for stochastic gradient descent, by choosing a random set of X images for each training update. You may want to increase batch size if the model is large and taking a long time to train. You also may want to increase the batch size if your total number of model concepts is larger than the batch size (you may want to increase to around 2x the category count).
    detection_score_threshold Only bounding boxes with a detection score above this threshold will be returned.
    image_size The size of images used for training. Images are scaled for efficient processing, and a lower number will take up less memory and run faster. A higher number will have more pixel information to train on and will increase accuracy.
    init_epochs The initial number of epochs before the first step/change in the lrate.
    logreg Set to True to use logistic regression, set to False to use softmax (for binary classification).
    lrate The learning rate is a tuning parameter in an optimization algorithm that determines the step size at each iteration while moving toward a minimum of a loss function.
    num_epochs An epoch is defined as one-pass over the entire dataset. If you increase it, it will take longer to train but it could make the model more robust.
    num_items_per_epoch The number of training examples per "epoch". An epoch would be defined as one-pass over this amount of examples.
    per_128_lrate Total change in lrate after 128 images processed. This is calculated as lrate = per_128_lrate * (batch_size / 128).
    per_item_lrate The rate that model weights are changed per item.
    step_epochs The number of epochs between applications of the step/change in lrate scheduler.
    test_freq The number of epochs should you run before evaluation of the test set. Increased frequency can allow for more granular testing but will extend processing time.
    use_perclass_regression Enables box coordinate local regression on a per-class basis. When set to True there will be num_classes sets of regressors for each anchor location, when set to False, there will be one coordinate regressor for each anchor location.

Create

Create a Visual Classifier

Use a visual classifier model if you would like to classify images and videos frames into set of concepts.
Java
NodeJS
Python
cURL
1
import com.clarifai.grpc.api.*;
2
import com.clarifai.grpc.api.status.*;
3
4
// Insert here the initialization code as outlined on this page:
5
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
6
7
Struct.Builder trainInfoParams = Struct.newBuilder()
8
.putFields(
9
"num_epochs", Value.newBuilder().setNumberValue(2).build()
10
11
)
12
.putFields(
13
"template", Value.newBuilder().setStringValue("classification_cifar10_v1").build()
14
);
15
16
SingleModelResponse postModelsResponse = stub.postModels(
17
PostModelsRequest.newBuilder()
18
.addModels(
19
Model.newBuilder()
20
.setId("lawrence-1591638385")
21
.setModelTypeId("visual-classifier")
22
.setTrainInfo(TrainInfo.newBuilder().setParams(trainInfoParams))
23
.setOutputInfo(
24
OutputInfo.newBuilder()
25
.setData(
26
Data.newBuilder()
27
.addConcepts(Concept.newBuilder().setId("ferrari23"))
28
.addConcepts(Concept.newBuilder().setId("outdoors23"))
29
)
30
.setOutputConfig(
31
OutputConfig.newBuilder()
32
.setClosedEnvironment(true)
33
)
34
)
35
)
36
.build()
37
);
38
39
if (postModelsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
40
throw new RuntimeException("Post models failed, status: " + postModelsResponse.getStatus());
41
}
Copied!
1
// Insert here the initialization code as outlined on this page:
2
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
stub.PostModels(
5
{
6
models: [
7
{
8
id: "lawrence-1591638385",
9
model_type_id: "visual-classifier",
10
train_info: {
11
params: {
12
num_epoch: 2,
13
template: "classification_cifar10_v1"
14
}
15
},
16
output_info: {
17
data: {
18
concepts: [
19
{id: "ferrari23"},
20
{id: "outdoors23"}
21
]
22
},
23
output_config: {
24
closed_environment: true
25
}
26
}
27
}
28
]
29
},
30
metadata,
31
(err, response) => {
32
if (err) {
33
done(err);
34
return;
35
}
36
37
if (response.status.code !== 10000) {
38
done(new Error("Received status: " + response.status.description + "\n" + response.status.details));
39
}
40
41
done();
42
}
43
);
Copied!
1
from google.protobuf.struct_pb2 import Struct
2
3
# Insert here the initialization code as outlined on this page:
4
# https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
5
6
train_params = Struct()
7
train_params.update(
8
{
9
"template": "classification_cifar10_v1",
10
"num_epochs": 2
11
}
12
)
13
14
post_models_response = stub.PostModels(
15
service_pb2.PostModelsRequest(
16
models=[
17
resources_pb2.Model(
18
id="lawrence-1591638385",
19
model_type_id="visual-classifier",
20
train_info=resources_pb2.TrainInfo(params=train_params),
21
output_info=resources_pb2.OutputInfo(
22
data=resources_pb2.Data(
23
concepts=[
24
resources_pb2.Concept(id="ferrari23"),
25
resources_pb2.Concept(id="outdoors23")
26
]
27
),
28
output_config=resources_pb2.OutputConfig(closed_environment=True)
29
)
30
)
31
]
32
),
33
metadata=metadata
34
)
35
36
if post_models_response.status.code != status_code_pb2.SUCCESS:
37
print("There was an error with your request!")
38
print("\tCode: {}".format(post_models_response.outputs[0].status.code))
39
print("\tDescription: {}".format(post_models_response.outputs[0].status.description))
40
print("\tDetails: {}".format(post_models_response.outputs[0].status.details))
41
raise Exception("Post models failed, status: " + post_models_response.status.description)
Copied!
1
curl -X POST 'https://api.clarifai.com/v2/models' \
2
-H 'Authorization: Key YOUR_API_KEY' \
3
-H 'Content-Type: application/json' \
4
--data-raw '{
5
"model": {
6
"id": "lawrence-1591638385",
7
"model_type_id": "visual-classifier",
8
"train_info": {
9
"params": {
10
"template": "classification_cifar10_v1",
11
"num_epochs": 2
12
}
13
},
14
"output_info": {
15
"data": {
16
"concepts": [
17
{"id":"ferrari23"},
18
{"id":"outdoors23"}
19
]
20
},
21
"output_config": {
22
"closed_environment" : true
23
}
24
}
25
}
26
}'
Copied!

Create a Visual Detector

Create a visual detector to detect bounding box regions in images or video frames and then classify the detected images. You can also send the image regions to an image cropper model to create a new cropped image.
Java
NodeJS
Python
cURL
1
import com.clarifai.grpc.api.*;
2
import com.clarifai.grpc.api.status.*;
3
4
// Insert here the initialization code as outlined on this page:
5
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
6
7
Struct.Builder trainInfoParams = Struct.newBuilder()
8
.putFields(
9
"num_epochs", Value.newBuilder().setNumberValue(2).build()
10
11
)
12
.putFields(
13
"template", Value.newBuilder().setStringValue("Clarifai-InceptionV2").build()
14
);
15
16
SingleModelResponse postModelsResponse = stub.postModels(
17
PostModelsRequest.newBuilder()
18
.addModels(
19
Model.newBuilder()
20
.setId("detection-test-1591638385")
21
.setModelTypeId("visual-detector")
22
.setTrainInfo(TrainInfo.newBuilder().setParams(trainInfoParams))
23
.setOutputInfo(
24
OutputInfo.newBuilder()
25
.setData(
26
Data.newBuilder()
27
.addConcepts(Concept.newBuilder().setId("ferrari23"))
28
.addConcepts(Concept.newBuilder().setId("outdoors23"))
29
)
30
.setOutputConfig(
31
OutputConfig.newBuilder()
32
.setClosedEnvironment(true)
33
)
34
)
35
)
36
.build()
37
);
38
39
if (postModelsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
40
throw new RuntimeException("Post models failed, status: " + postModelsResponse.getStatus());
41
}
Copied!
1
// Insert here the initialization code as outlined on this page:
2
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
stub.PostModels(
5
{
6
models: [
7
{
8
id: "detection-test-1591638385",
9
model_type_id: "visual-detector",
10
train_info: {
11
params: {
12
num_epoch: 2,
13
template: "Clarifai-InceptionV2"
14
}
15
},
16
output_info: {
17
data: {
18
concepts: [
19
{id: "ferrari23"},
20
{id: "outdoors23"}
21
]
22
},
23
output_config: {
24
closed_environment: true
25
}
26
}
27
}
28
]
29
},
30
metadata,
31
(err, response) => {
32
if (err) {
33
throw new Error(err);
34
}
35
36
if (response.status.code !== 10000) {
37
throw new Error("Received status: " + response.status.description + "\n" + response.status.details);
38
}
39
}
40
);
Copied!
1
from google.protobuf.struct_pb2 import Struct
2
3
# Insert here the initialization code as outlined on this page:
4
# https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
5
6
train_params = Struct()
7
train_params.update(
8
{
9
"template": "Clarifai-InceptionV2",
10
"num_epochs": 2
11
}
12
)
13
14
post_models_response = stub.PostModels(
15
service_pb2.PostModelsRequest(
16
models=[
17
resources_pb2.Model(
18
id="detection-test-1591638385",
19
model_type_id="visual-detector",
20
train_info=resources_pb2.TrainInfo(params=train_params),
21
output_info=resources_pb2.OutputInfo(
22
data=resources_pb2.Data(
23
concepts=[
24
resources_pb2.Concept(id="ferrari23"),
25
resources_pb2.Concept(id="outdoors23")
26
]
27
),
28
output_config=resources_pb2.OutputConfig(closed_environment=True)
29
)
30
)
31
]
32
),
33
metadata=metadata
34
)
35
36
if post_models_response.status.code != status_code_pb2.SUCCESS:
37
print("There was an error with your request!")
38
print("\tCode: {}".format(post_models_response.outputs[0].status.code))
39
print("\tDescription: {}".format(post_models_response.outputs[0].status.description))
40
print("\tDetails: {}".format(post_models_response.outputs[0].status.details))
41
raise Exception("Post models failed, status: " + post_models_response.status.description)
Copied!
1
curl -X POST 'https://api.clarifai.com/v2/models' \
2
-H 'Authorization: Key YOUR_API_KEY' \
3
-H 'Content-Type: application/json' \
4
--data-raw '{
5
"model": {
6
"id": "detection-test-1591638385",
7
"model_type_id": "visual-detector",
8
"train_info": {
9
"params": {
10
"template": "Clarifai-InceptionV2",
11
"num_epochs": 2
12
}
13
},
14
"output_info": {
15
"data": {
16
"concepts": [
17
{"id":"ferrari23"},
18
{"id":"outdoors23"}
19
]
20
},
21
"output_config": {
22
"closed_environment" : true
23
}
24
}
25
}
26
}'
Copied!

Create a Visual Embedder

Create a visual embedding model to transform images and videos frames into "high level" vector representation understood by our AI models. These embeddings enable visual search and can be used as base models to train other models.
Java
NodeJS
Python
cURL
1
import com.clarifai.grpc.api.*;
2
import com.clarifai.grpc.api.status.*;
3
4
// Insert here the initialization code as outlined on this page:
5
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
6
7
Struct.Builder trainInfoParams = Struct.newBuilder()
8
.putFields(
9
"num_epochs", Value.newBuilder().setNumberValue(2).build()
10
11
)
12
.putFields(
13
"template", Value.newBuilder().setStringValue("classification_basemodel_v1_embed").build()
14
);
15
16
SingleModelResponse postModelsResponse = stub.postModels(
17
PostModelsRequest.newBuilder()
18
.addModels(
19
Model.newBuilder()
20
.setId("embed-test-1591638385")
21
.setModelTypeId("visual-embedder")
22
.setTrainInfo(TrainInfo.newBuilder().setParams(trainInfoParams))
23
.setOutputInfo(
24
OutputInfo.newBuilder()
25
.setData(
26
Data.newBuilder()
27
.addConcepts(Concept.newBuilder().setId("ferrari23"))
28
.addConcepts(Concept.newBuilder().setId("outdoors23"))
29
)
30
.setOutputConfig(
31
OutputConfig.newBuilder()
32
.setClosedEnvironment(true)
33
)
34
)
35
)
36
.build()
37
);
38
39
if (postModelsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
40
throw new RuntimeException("Post models failed, status: " + postModelsResponse.getStatus());
41
}
Copied!
1
// Insert here the initialization code as outlined on this page:
2
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
stub.PostModels(
5
{
6
models: [
7
{
8
id: "embed-test-1591638385",
9
model_type_id: "visual-embedder",
10
train_info: {
11
params: {
12
num_epoch: 2,
13
template: "classification_basemodel_v1_embed"
14
}
15
},
16
output_info: {
17
data: {
18
concepts: [
19
{id: "ferrari23"},
20
{id: "outdoors23"}
21
]
22
},
23
output_config: {
24
closed_environment: true
25
}
26
}
27
}
28
]
29
},
30
metadata,
31
(err, response) => {
32
if (err) {
33
throw new Error(err);
34
}
35
36
if (response.status.code !== 10000) {
37
throw new Error("Received status: " + response.status.description + "\n" + response.status.details);
38
}
39
}
40
);
Copied!
1
# Insert here the initialization code as outlined on this page:
2
# https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
from google.protobuf.struct_pb2 import Struct
5
6
train_params = Struct()
7
train_params.update(
8
{
9
"template": "classification_basemodel_v1_embed",
10
"num_epochs": 2
11
}
12
)
13
14
post_models_response = stub.PostModels(
15
service_pb2.PostModelsRequest(
16
models=[
17
resources_pb2.Model(
18
id="embed-test-1591638385",
19
model_type_id="visual-embedder",
20
train_info=resources_pb2.TrainInfo(params=train_params),
21
output_info=resources_pb2.OutputInfo(
22
data=resources_pb2.Data(
23
concepts=[
24
resources_pb2.Concept(id="ferrari23"),
25
resources_pb2.Concept(id="outdoors23")
26
]
27
),
28
output_config=resources_pb2.OutputConfig(closed_environment=True)
29
)
30
)
31
]
32
),
33
metadata=metadata
34
)
35
36
if post_models_response.status.code != status_code_pb2.SUCCESS:
37
print("There was an error with your request!")
38
print("\tCode: {}".format(post_models_response.outputs[0].status.code))
39
print("\tDescription: {}".format(post_models_response.outputs[0].status.description))
40
print("\tDetails: {}".format(post_models_response.outputs[0].status.details))
41
raise Exception("Post models failed, status: " + post_models_response.status.description)
Copied!
1
curl -X POST 'https://api.clarifai.com/v2/models' \
2
-H 'Authorization: Key YOUR_API_KEY' \
3
-H 'Content-Type: application/json' \
4
--data-raw '{
5
"model": {
6
"id": "embed-test-1591638385",
7
"model_type_id": "visual-embedder",
8
"train_info": {
9
"params": {
10
"template": "classification_basemodel_v1_embed",
11
"num_epochs": 2
12
}
13
},
14
"output_info": {
15
"data": {
16
"concepts": [
17
{"id":"ferrari23"},
18
{"id":"outdoors23"}
19
]
20
},
21
"output_config": {
22
"closed_environment" : true
23
}
24
}
25
}
26
}'
Copied!

Create a Workflow with a Deep Trained Model

Put your new deep-trained model to work by adding it to a workflow.
Java
gRPC NodeJS
Python
cURL
1
import com.clarifai.grpc.api.*;
2
import com.clarifai.grpc.api.status.*;
3
4
// Insert here the initialization code as outlined on this page:
5
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
6
7
MultiWorkflowResponse postWorkflowsResponse = stub.postWorkflows(
8
PostWorkflowsRequest.newBuilder()
9
.addWorkflows(
10
Workflow.newBuilder()
11
.setId("my-new-workflow-id")
12
.addNodes(
13
WorkflowNode.newBuilder()
14
.setId("embed")
15
.setModel(
16
Model.newBuilder()
17
.setId("{YOUR_EMBED_MODEL_ID}")
18
.setModelVersion(
19
ModelVersion.newBuilder()
20
.setId("{YOUR_EMBED_MODEL_VERSION_ID}")
21
)
22
)
23
)
24
.addNodes(
25
WorkflowNode.newBuilder()
26
.setId("my-custom-model")
27
.setModel(
28
Model.newBuilder()
29
.setId("{YOUR_CUSTOM_MODEL_ID}")
30
.setModelVersion(
31
ModelVersion.newBuilder()
32
.setId("{YOUR_CUSTOM_MODEL_MODEL_VERSION_ID}")
33
)
34
)
35
.addNodeInputs(NodeInput.newBuilder().setNodeId("embed"))
36
)
37
)
38
.build()
39
);
40
41
if (postWorkflowsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
42
throw new RuntimeException("Post workflows failed, status: " + postWorkflowsResponse.getStatus());
43
}
Copied!
1
// Insert here the initialization code as outlined on this page:
2
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
stub.PostWorkflows(
5
{
6
workflows: [
7
{
8
id: "my-new-workflow-id",
9
nodes: [
10
{
11
id: "embed",
12
model: {
13
id: "{YOUR_EMBED_MODEL_ID}",
14
model_version: {
15
id: "{YOUR_EMBED_MODEL_VERSION_ID}"
16
}
17
}
18
},
19
{
20
id: "my-custom-model",
21
model: {
22
id: "{YOUR_CUSTOM_MODEL_ID}",
23
model_version: {
24
id: "{YOUR_CUSTOM_MODEL_VERSION_ID}"
25
}
26
},
27
node_inputs: [
28
{node_id: "embed"}
29
]
30
}
31
]
32
}
33
]
34
},
35
metadata,
36
(err, response) => {
37
if (err) {
38
throw new Error(err);
39
}
40
41
if (response.status.code !== 10000) {
42
console.log(response.status);
43
throw new Error("Post workflows failed, status: " + response.status.description);
44
}
45
}
46
);
Copied!
1
# Insert here the initialization code as outlined on this page:
2
# https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
post_workflows_response = stub.PostWorkflows(
5
service_pb2.PostWorkflowsRequest(
6
workflows=[
7
resources_pb2.Workflow(
8
id="my-new-workflow-id",
9
nodes=[
10
resources_pb2.WorkflowNode(
11
id="embed",
12
model=resources_pb2.Model(
13
id="{YOUR_EMBED_MODEL_ID}",
14
model_version=resources_pb2.ModelVersion(
15
id="{YOUR_EMBED_MODEL_VERSION_ID}"
16
)
17
)
18
),
19
resources_pb2.WorkflowNode(
20
id="my-custom-model",
21
model=resources_pb2.Model(
22
id="{YOUR_CUSTOM_MODEL_ID}",
23
model_version=resources_pb2.ModelVersion(
24
id="{YOUR_CUSTOM_MODEL_VERSION_ID}"
25
)
26
),
27
node_inputs=[
28
resources_pb2.NodeInput(node_id="embed")
29
]
30
),
31
]
32
)
33
]
34
),
35
metadata=metadata
36
)
37
38
if post_workflows_response.status.