-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
model.go
304 lines (260 loc) · 9.32 KB
/
model.go
1
2
3
4
5
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bigquery
import (
"context"
"fmt"
"strings"
"time"
"cloud.google.com/go/internal/optional"
"cloud.google.com/go/internal/trace"
bq "google.golang.org/api/bigquery/v2"
)
// Model represent a reference to a BigQuery ML model.
// Within the API, models are used largely for communicating
// statistical information about a given model, as creation of models is only
// supported via BigQuery queries (e.g. CREATE MODEL .. AS ..).
//
// For more info, see documentation for Bigquery ML,
// see: https://cloud.google.com/bigquery/docs/bigqueryml
type Model struct {
ProjectID string
DatasetID string
// ModelID must contain only letters (a-z, A-Z), numbers (0-9), or underscores (_).
// The maximum length is 1,024 characters.
ModelID string
c *Client
}
// Identifier returns the ID of the model in the requested format.
//
// For Standard SQL format, the identifier will be quoted if the
// ProjectID contains dash (-) characters.
func (m *Model) Identifier(f IdentifierFormat) (string, error) {
switch f {
case LegacySQLID:
return fmt.Sprintf("%s:%s.%s", m.ProjectID, m.DatasetID, m.ModelID), nil
case StandardSQLID:
// Per https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-create#model_name
// we quote the entire identifier.
out := fmt.Sprintf("%s.%s.%s", m.ProjectID, m.DatasetID, m.ModelID)
if strings.Contains(out, "-") {
out = fmt.Sprintf("`%s`", out)
}
return out, nil
default:
return "", ErrUnknownIdentifierFormat
}
}
// FullyQualifiedName returns the ID of the model in projectID:datasetID.modelid format.
func (m *Model) FullyQualifiedName() string {
s, _ := m.Identifier(LegacySQLID)
return s
}
func (m *Model) toBQ() *bq.ModelReference {
return &bq.ModelReference{
ProjectId: m.ProjectID,
DatasetId: m.DatasetID,
ModelId: m.ModelID,
}
}
// Metadata fetches the metadata for a model, which includes ML training statistics.
func (m *Model) Metadata(ctx context.Context) (mm *ModelMetadata, err error) {
ctx = trace.StartSpan(ctx, "cloud.google.com/go/bigquery.Model.Metadata")
defer func() { trace.EndSpan(ctx, err) }()
req := m.c.bqs.Models.Get(m.ProjectID, m.DatasetID, m.ModelID).Context(ctx)
setClientHeader(req.Header())
var model *bq.Model
err = runWithRetry(ctx, func() (err error) {
ctx = trace.StartSpan(ctx, "bigquery.models.get")
model, err = req.Do()
trace.EndSpan(ctx, err)
return err
})
if err != nil {
return nil, err
}
return bqToModelMetadata(model)
}
// Update updates mutable fields in an ML model.
func (m *Model) Update(ctx context.Context, mm ModelMetadataToUpdate, etag string) (md *ModelMetadata, err error) {
ctx = trace.StartSpan(ctx, "cloud.google.com/go/bigquery.Model.Update")
defer func() { trace.EndSpan(ctx, err) }()
bqm, err := mm.toBQ()
if err != nil {
return nil, err
}
call := m.c.bqs.Models.Patch(m.ProjectID, m.DatasetID, m.ModelID, bqm).Context(ctx)
setClientHeader(call.Header())
if etag != "" {
call.Header().Set("If-Match", etag)
}
var res *bq.Model
if err := runWithRetry(ctx, func() (err error) {
ctx = trace.StartSpan(ctx, "bigquery.models.patch")
res, err = call.Do()
trace.EndSpan(ctx, err)
return err
}); err != nil {
return nil, err
}
return bqToModelMetadata(res)
}
// Delete deletes an ML model.
func (m *Model) Delete(ctx context.Context) (err error) {
ctx = trace.StartSpan(ctx, "cloud.google.com/go/bigquery.Model.Delete")
defer func() { trace.EndSpan(ctx, err) }()
req := m.c.bqs.Models.Delete(m.ProjectID, m.DatasetID, m.ModelID).Context(ctx)
setClientHeader(req.Header())
return req.Do()
}
// ModelMetadata represents information about a BigQuery ML model.
type ModelMetadata struct {
// The user-friendly description of the model.
Description string
// The user-friendly name of the model.
Name string
// The type of the model. Possible values include:
// "LINEAR_REGRESSION" - a linear regression model
// "LOGISTIC_REGRESSION" - a logistic regression model
// "KMEANS" - a k-means clustering model
Type string
// The creation time of the model.
CreationTime time.Time
// The last modified time of the model.
LastModifiedTime time.Time
// The expiration time of the model.
ExpirationTime time.Time
// The geographic location where the model resides. This value is
// inherited from the encapsulating dataset.
Location string
// Custom encryption configuration (e.g., Cloud KMS keys).
EncryptionConfig *EncryptionConfig
// The input feature columns used to train the model.
featureColumns []*bq.StandardSqlField
// The label columns used to train the model. Output
// from the model will have a "predicted_" prefix for these columns.
labelColumns []*bq.StandardSqlField
// Information for all training runs, ordered by increasing start times.
trainingRuns []*bq.TrainingRun
Labels map[string]string
// ETag is the ETag obtained when reading metadata. Pass it to Model.Update
// to ensure that the metadata hasn't changed since it was read.
ETag string
}
// TrainingRun represents information about a single training run for a BigQuery ML model.
// Experimental: This information may be modified or removed in future versions of this package.
type TrainingRun bq.TrainingRun
// RawTrainingRuns exposes the underlying training run stats for a model using types from
// "google.golang.org/api/bigquery/v2", which are subject to change without warning.
// It is EXPERIMENTAL and subject to change or removal without notice.
func (mm *ModelMetadata) RawTrainingRuns() []*TrainingRun {
if mm.trainingRuns == nil {
return nil
}
var runs []*TrainingRun
for _, v := range mm.trainingRuns {
r := TrainingRun(*v)
runs = append(runs, &r)
}
return runs
}
// RawLabelColumns exposes the underlying label columns used to train an ML model and uses types from
// "google.golang.org/api/bigquery/v2", which are subject to change without warning.
// It is EXPERIMENTAL and subject to change or removal without notice.
func (mm *ModelMetadata) RawLabelColumns() ([]*StandardSQLField, error) {
return bqToModelCols(mm.labelColumns)
}
// RawFeatureColumns exposes the underlying feature columns used to train an ML model and uses types from
// "google.golang.org/api/bigquery/v2", which are subject to change without warning.
// It is EXPERIMENTAL and subject to change or removal without notice.
func (mm *ModelMetadata) RawFeatureColumns() ([]*StandardSQLField, error) {
return bqToModelCols(mm.featureColumns)
}
func bqToModelCols(s []*bq.StandardSqlField) ([]*StandardSQLField, error) {
if s == nil {
return nil, nil
}
var cols []*StandardSQLField
for _, v := range s {
c, err := bqToStandardSQLField(v)
if err != nil {
return nil, err
}
cols = append(cols, c)
}
return cols, nil
}
func bqToModelMetadata(m *bq.Model) (*ModelMetadata, error) {
md := &ModelMetadata{
Description: m.Description,
Name: m.FriendlyName,
Type: m.ModelType,
Location: m.Location,
Labels: m.Labels,
ExpirationTime: unixMillisToTime(m.ExpirationTime),
CreationTime: unixMillisToTime(m.CreationTime),
LastModifiedTime: unixMillisToTime(m.LastModifiedTime),
EncryptionConfig: bqToEncryptionConfig(m.EncryptionConfiguration),
featureColumns: m.FeatureColumns,
labelColumns: m.LabelColumns,
trainingRuns: m.TrainingRuns,
ETag: m.Etag,
}
return md, nil
}
// ModelMetadataToUpdate is used when updating an ML model's metadata.
// Only non-nil fields will be updated.
type ModelMetadataToUpdate struct {
// The user-friendly description of this model.
Description optional.String
// The user-friendly name of this model.
Name optional.String
// The time when this model expires. To remove a model's expiration,
// set ExpirationTime to NeverExpire. The zero value is ignored.
ExpirationTime time.Time
// The model's encryption configuration.
EncryptionConfig *EncryptionConfig
labelUpdater
}
func (mm *ModelMetadataToUpdate) toBQ() (*bq.Model, error) {
m := &bq.Model{}
forceSend := func(field string) {
m.ForceSendFields = append(m.ForceSendFields, field)
}
if mm.Description != nil {
m.Description = optional.ToString(mm.Description)
forceSend("Description")
}
if mm.Name != nil {
m.FriendlyName = optional.ToString(mm.Name)
forceSend("FriendlyName")
}
if mm.EncryptionConfig != nil {
m.EncryptionConfiguration = mm.EncryptionConfig.toBQ()
}
if !validExpiration(mm.ExpirationTime) {
return nil, invalidTimeError(mm.ExpirationTime)
}
if mm.ExpirationTime == NeverExpire {
m.NullFields = append(m.NullFields, "ExpirationTime")
} else if !mm.ExpirationTime.IsZero() {
m.ExpirationTime = mm.ExpirationTime.UnixNano() / 1e6
forceSend("ExpirationTime")
}
labels, forces, nulls := mm.update()
m.Labels = labels
m.ForceSendFields = append(m.ForceSendFields, forces...)
m.NullFields = append(m.NullFields, nulls...)
return m, nil
}