Tensorflow tutorial (first one) — linear regression

Time:2020-11-7

Univariate linear regression cost function

The sum of the squares of the error between the predicted value and the real value is calculated and minimized

Tensorflow tutorial (first one) -- linear regression

One variable linear regression gradient descent method

Initialize θ 0 and θ 1, and constantly change θ 0 and θ 1 until J (θ 0, θ 1) reaches a global or local minimum

Tensorflow tutorial (first one) -- linear regression

αFor learning rate

Univariate linear regression – Implementation

Univariate linear regression equation

Tensorflow tutorial (first one) -- linear regression

from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt

data = np.genfromtxt("../data/csv/data.csv", delimiter=",")
x_data = data[:, 0, np.newaxis]
y_data = data[:, 1, np.newaxis]
model = LinearRegression()
model.fit(x_data, y_data)
#Drawing
plt.plot(x_data, y_data, 'b.')
plt.plot(x_data, model.predict(x_data), 'r')
plt.show()

Tensorflow tutorial (first one) -- linear regression

Multiple linear regression cost function

Tensorflow tutorial (first one) -- linear regression

Multiple linear regression gradient descent method

X0 = 1. For the convenience of description, let the subscript of X correspond to the subscript of θ one by one

Tensorflow tutorial (first one) -- linear regression

Multiple linear regression – Implementation

Multiple linear regression equation

Tensorflow tutorial (first one) -- linear regression

import numpy as np
from numpy import genfromtxt
from sklearn import linear_model
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#Import data
data = genfromtxt(r'E:/project/python/data/csv/Delivery.csv', delimiter=',')
#Data segmentation
x_data = data[:, :-1]
y_data = data[:, -1]
#Modeling
model = linear_model.LinearRegression()
model.fit(x_data, y_data)
print(Coefficient:, model.coef_)
print(Intercept:, model.intercept_)
#Drawing
ax = plt.figure().add_subplot(111, projection='3d')
ax.scatter(x_data[:, 0], x_data[:, 1], y_data, c='r', marker='o', s=100)
x0 = x_data[:, 0]
x1 = x_data[:, 1]
x0, x1 = np.meshgrid(x0, x1)
z = model.intercept_ + x0 * model.coef_[0] + x1 * model.coef_[1]
ax.plot_surface(x0, x1, z)
ax.set_xlabel('Miles')
ax.set_ylabel('Num of Deliveries')
ax.set_zlabel('Time')
plt.show()

Tensorflow tutorial (first one) -- linear regression

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint