当前位置:网站首页>Multiple linear regression (gradient descent method)
Multiple linear regression (gradient descent method)
2022-07-05 08:50:00 【Python code doctor】
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Reading data
data = np.loadtxt('Delivery.csv',delimiter=',')
print(data)
# Structural features x, The goal is y
# features
x_data = data[:,0:-1]
y_data = data[:,-1]
# Initialize learning rate ( step )
learning_rate = 0.0001
# initialization intercept
theta0 = 0
# initialization coefficient
theta1 = 0
theta2 = 0
# Maximum number of initialization iterations
n_iterables = 100
def compute_mse(theta0,theta1,theta2,x_data,y_data):
''' Computational cost function '''
total_error = 0
for i in range(len(x_data)):
# Calculate the loss ( True value - Predictive value )**2
total_error += (y_data[i]-(theta0 + theta1*x_data[i,0]+theta2*x_data[i,1]))**2
mse_ = total_error/len(x_data)/2
return mse_
def gradient_descent(x_data,y_data,theta0,theta1,theta2,learning_rate,n_iterables):
''' Gradient descent method '''
m = len(x_data)
# loop
for i in range(n_iterables):
# initialization theta0,theta1,theta2 Partial derivative
theta0_grad = 0
theta1_grad = 0
theta2_grad = 0
# Calculate the sum of partial derivatives and then average
# Traverse m Time
for j in range(m):
theta0_grad += (1/m)*((theta1*x_data[j,0]+theta2*x_data[j,1]+theta0)-y_data[j])
theta1_grad += (1/m)*((theta1*x_data[j,0]+theta2*x_data[j,1]+theta0)-y_data[j])*x_data[j,0]
theta2_grad += (1/m)*((theta1*x_data[j,0]+theta2*x_data[j,1]+theta0)-y_data[j])*x_data[j,1]
# to update theta
theta0 = theta0 - (learning_rate*theta0_grad)
theta1 = theta1 - (learning_rate*theta1_grad)
theta2 = theta2 - (learning_rate*theta2_grad)
return theta0,theta1,theta2
# Visual distribution
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x_data[:,0],x_data[:,1],y_data)
plt.show()
print(f" Start : intercept theta0={
theta0},theta1={
theta1},theta2={
theta2}, Loss ={
compute_mse(theta0,theta1,theta2,x_data,y_data)}")
print(" Start running ~")
theta0,theta1,theta2 = gradient_descent(x_data,y_data,theta0,theta1,theta2,learning_rate,n_iterables)
print(f" iteration {
n_iterables} Next time : intercept theta0={
theta0},theta1={
theta1},theta2={
theta2}, Loss ={
compute_mse(theta0,theta1,theta2,x_data,y_data)}")
# Draw the desired plane
x_0 = x_data[:,0]
x_1 = x_data[:,1]
# Generate grid matrix
x_0,x_1 = np.meshgrid(x_0,x_1)
# y
y_hat = theta0 + theta1*x_0 +theta2*x_1
ax.plot_surface(x_0,x_1,y_hat)
# Set the label
ax.set_xlabel('Miles')
ax.set_ylabel('nums')
ax.set_zlabel('Time')
plt.show()
边栏推荐
- [daiy4] copy of JZ35 complex linked list
- Business modeling of software model | vision
- Old Wang's esp8266 and old Wu's ws2818 light strip
- 287. Looking for repeats - fast and slow pointer
- 12. Dynamic link library, DLL
- Guess riddles (7)
- File server migration scheme of a company
- Some pitfalls of win10 network sharing
- Array, date, string object method
- 某公司文件服务器迁移方案
猜你喜欢

Use and programming method of ros-8 parameters

My university

EA introduction notes

Ros-11 common visualization tools

Guess riddles (10)

Old Wang's esp8266 and old Wu's ws2818 light strip

Install the CPU version of tensorflow+cuda+cudnn (ultra detailed)

猜谜语啦(7)

Typescript hands-on tutorial, easy to understand

Halcon color recognition_ fuses. hdev:classify fuses by color
随机推荐
OpenFeign
ROS learning 1- create workspaces and function packs
Speech recognition learning summary
Hello everyone, welcome to my CSDN blog!
Install the CPU version of tensorflow+cuda+cudnn (ultra detailed)
How can fresh students write resumes to attract HR and interviewers
Numpy pit: after the addition of dimension (n, 1) and dimension (n,) array, the dimension becomes (n, n)
One dimensional vector transpose point multiplication np dot
[daily training -- Tencent selected 50] 557 Reverse word III in string
Halcon blob analysis (ball.hdev)
猜谜语啦(142)
多元线性回归(梯度下降法)
Basic number theory - fast power
资源变现小程序添加折扣充值和折扣影票插件
【日常训练】1200. 最小绝对差
Explore the authentication mechanism of StarUML
Halcon: check of blob analysis_ Blister capsule detection
Arrangement of some library files
GEO数据库中搜索数据
Dynamic dimensions required for input: input, but no shapes were provided. Automatically overriding