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
| import tensorflow as tf from tensorflow.keras import models,layers,optimizers,losses,metrics
@tf.function def printbar(): ts = tf.timestamp() today_ts = ts%(24*60*60)
hour = tf.cast(today_ts//3600+8,tf.int32)%tf.constant(24) minite = tf.cast((today_ts%3600)//60,tf.int32) second = tf.cast(tf.floor(today_ts%60),tf.int32)
def timeformat(m): if tf.strings.length(tf.strings.format("{}",m))==1: return(tf.strings.format("0{}",m)) else: return(tf.strings.format("{}",m))
timestring = tf.strings.join([timeformat(hour),timeformat(minite), timeformat(second)],separator = ":") tf.print("=========="*8,end = "") tf.print(timestring)
n = 800
X = tf.random.uniform([n,2],minval=-10,maxval=10) w0 = tf.constant([[2.0],[-1.0]]) b0 = tf.constant(3.0)
Y = X@w0 + b0 + tf.random.normal([n,1],mean = 0.0,stddev= 2.0)
ds_train = tf.data.Dataset.from_tensor_slices((X[0:n*3//4,:],Y[0:n*3//4,:])) \ .shuffle(buffer_size = 1000).batch(20) \ .prefetch(tf.data.experimental.AUTOTUNE) \ .cache()
ds_valid = tf.data.Dataset.from_tensor_slices((X[n*3//4:,:],Y[n*3//4:,:])) \ .shuffle(buffer_size = 1000).batch(20) \ .prefetch(tf.data.experimental.AUTOTUNE) \ .cache() tf.keras.backend.clear_session()
class MyModel(models.Model): def __init__(self): super(MyModel, self).__init__()
def build(self,input_shape): self.dense1 = layers.Dense(1) super(MyModel,self).build(input_shape)
def call(self, x): y = self.dense1(x) return(y)
model = MyModel() model.build(input_shape =(None,2)) model.summary()
optimizer = optimizers.Adam() loss_func = losses.MeanSquaredError()
train_loss = tf.keras.metrics.Mean(name='train_loss') train_metric = tf.keras.metrics.MeanAbsoluteError(name='train_mae')
valid_loss = tf.keras.metrics.Mean(name='valid_loss') valid_metric = tf.keras.metrics.MeanAbsoluteError(name='valid_mae')
@tf.function def train_step(model, features, labels): with tf.GradientTape() as tape: predictions = model(features) loss = loss_func(labels, predictions) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss.update_state(loss) train_metric.update_state(labels, predictions)
@tf.function def valid_step(model, features, labels): predictions = model(features) batch_loss = loss_func(labels, predictions) valid_loss.update_state(batch_loss) valid_metric.update_state(labels, predictions)
@tf.function def train_model(model,ds_train,ds_valid,epochs): for epoch in tf.range(1,epochs+1): for features, labels in ds_train: train_step(model,features,labels)
for features, labels in ds_valid: valid_step(model,features,labels)
logs = 'Epoch={},Loss:{},MAE:{},Valid Loss:{},Valid MAE:{}'
if epoch%100 ==0: printbar() tf.print(tf.strings.format(logs, (epoch,train_loss.result(),train_metric.result(),valid_loss.result(),valid_metric.result()))) tf.print("w=",model.layers[0].kernel) tf.print("b=",model.layers[0].bias) tf.print("")
train_loss.reset_states() valid_loss.reset_states() train_metric.reset_states() valid_metric.reset_states()
train_model(model,ds_train,ds_valid,400)
Model: "my_model" _________________________________________________________________ Layer (type) Output Shape Param ================================================================= dense (Dense) multiple 3 ================================================================= Total params: 3 Trainable params: 3 Non-trainable params: 0 _________________________________________________________________ ================================================================================18:17:08 Epoch=100,Loss:67.9662247,MAE:6.36445856,Valid Loss:65.3885117,Valid MAE:6.17629 w= [[1.65662384] [-1.01629746]] b= [1.92026019]
================================================================================18:17:16 Epoch=200,Loss:36.144165,MAE:4.0302186,Valid Loss:35.4477425,Valid MAE:4.01481533 w= [[1.99435031] [-1.00531375]] b= [3.02523756]
================================================================================18:17:25 Epoch=300,Loss:25.3425236,MAE:3.20795441,Valid Loss:25.308445,Valid MAE:3.25203133 w= [[1.99592912] [-1.00504756]] b= [3.08958364]
================================================================================18:17:34 Epoch=400,Loss:19.9554043,MAE:2.79780984,Valid Loss:20.2524834,Valid MAE:2.87172508 w= [[1.99595356] [-1.00504148]] b= [3.08971953]
|