Regressão linear

Introdução ao TensorFlow em Python

Isaiah Hull

Visiting Associate Professor of Finance, BI Norwegian Business School

O que é regressão linear?

Esta imagem mostra um diagrama de dispersão do logaritmo natural do tamanho da casa em pés quadrados versus o logaritmo natural do preço da casa em dólares.

Introdução ao TensorFlow em Python

O que é regressão linear?

Esta imagem mostra uma linha de regressão ajustada a um diagrama de dispersão do logaritmo natural do tamanho da casa em pés quadrados versus o logaritmo natural do preço da casa em dólares.

Introdução ao TensorFlow em Python

O modelo de regressão linear

  • Um modelo de regressão linear assume relação linear:
    • $price = intercept + size*slope + error$
  • Este é um exemplo de regressão univariada.
    • Há apenas uma feature, size.
  • Modelos de regressão múltipla têm mais de uma feature.
    • Ex.: size e location
Introdução ao TensorFlow em Python

Regressão linear no TensorFlow

# Define the targets and features
price = np.array(housing['price'], np.float32)
size = np.array(housing['sqft_living'], np.float32)

# Define the intercept and slope
intercept = tf.Variable(0.1, np.float32)
slope = tf.Variable(0.1, np.float32)
# Define a linear regression model
def linear_regression(intercept, slope, features = size):
    return intercept + features*slope
# Compute the predicted values and loss
def loss_function(intercept, slope, targets = price, features = size):
    predictions = linear_regression(intercept, slope)
    return tf.keras.losses.mse(targets, predictions)
Introdução ao TensorFlow em Python

Regressão linear no TensorFlow

# Define an optimization operation
opt = tf.keras.optimizers.Adam()
# Minimize the loss function and print the loss
for j in range(1000):
    opt.minimize(lambda: loss_function(intercept, slope),\
    var_list=[intercept, slope])
    print(loss_function(intercept, slope))
tf.Tensor(10.909373, shape=(), dtype=float32)
...
tf.Tensor(0.15479447, shape=(), dtype=float32)
# Print the trained parameters
print(intercept.numpy(), slope.numpy())
Introdução ao TensorFlow em Python

Vamos praticar!

Introdução ao TensorFlow em Python

Preparing Video For Download...