机器学习---线性回归(一)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

x = np.array([4,3,3,4,2,2,0,1,2,5,1,2,5,1,3])
y = np.array([8,6,6,7,4,4,2,4,5,9,3,4,8,3,6])
m = len(x)
x = np.c_[np.ones([m,1]),x] #增加一列1
y = np.c_[y]
print(x.shape)#(15, 2)
print(y.shape)#(15, 1)
theta = np.zeros([2,1])
#theta  初始化
alpha = 0.01  #初始化学习率alpha
m_iter = 100 #定义最大迭代次数
cost = np.zeros([m_iter]) #记录代价值
for i in range(m_iter):
    y_hat = x.dot(theta)
    error = y_hat - y
    cost_value = 1/2*m * error.T.dot(error)
    cost[i] = cost_value
    delt_theta = 1/m *x.T.dot(error)
    theta = theta - alpha*delt_theta
print(theta)  #梯度下降求得最优参数值
	array([[ 0.80067129],
	       [ 1.66911044]])
#进行绘图显示
plt.scatter(x[:,1],y,c ='r')
plt.plot(x[:,1],y_hat,'r-')
plt.show()
plt.plot(cost)
plt.show()

x:
array([[ 1., 4.],
[ 1., 3.],
[ 1., 3.],
[ 1., 4.],
[ 1., 2.],
[ 1., 2.],
[ 1., 0.],
[ 1., 1.],
[ 1., 2.],
[ 1., 5.],
[ 1., 1.],
[ 1., 2.],
[ 1., 5.],
[ 1., 1.],
[ 1., 3.]])
y:
array([[8],
[6],
[6],
[7],
[4],
[4],
[2],
[4],
[5],
[9],
[3],
[4],
[8],
[3],
[6]])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值