更新时间:2024-08-15 GMT+08:00

使用TensorFlow进行线性回归

首先在FunctionGraph页面将tensorflow添加为公共依赖

图1 tensorflow添加为公共依赖

在代码中导入tensorflow并使用

import json
import random
# 导入 TensorFlow 依赖库
import tensorflow as tf
def handler (event, context):
 
    TRUE_W = random.randint(0,9)
    TRUE_b = random.randint(0,9)
    
    NUM_SAMPLES = 100
 
    X = tf.random.normal(shape=[NUM_SAMPLES, 1]).numpy()
    noise = tf.random.normal(shape=[NUM_SAMPLES, 1]).numpy()
    y = X * TRUE_W + TRUE_b + noise  
    model = tf.keras.layers.Dense(units=1)  
 
    EPOCHS = 20
    LEARNING_RATE = 0.002
    print("start training")
    for epoch in range(EPOCHS):  
        with tf.GradientTape() as tape: 
            y_ = model(X)
            loss = tf.reduce_sum(tf.keras.losses.mean_squared_error(y, y_))  
 
        grads = tape.gradient(loss, model.variables)  
        optimizer = tf.keras.optimizers.SGD(LEARNING_RATE)  
        optimizer.apply_gradients(zip(grads, model.variables))  
 
        print('Epoch [{}/{}], loss [{:.3f}]'.format(epoch, EPOCHS, loss))
    print("finished")
    print(TRUE_W,TRUE_b)
    print(model.variables)
    return {
        "statusCode": 200,
        "isBase64Encoded": False,
        "body": json.dumps(event),
        "headers": {
            "Content-Type": "application/json"
        }
    }
 
class Model(object):
    def __init__(self):
        self.W = tf.Variable(tf.random.uniform([1]))  
        self.b = tf.Variable(tf.random.uniform([1]))
    def __call__(self, x):
        return self.W * x + self.b