Python编程实现线性回归和批量梯度下降法代码实例
作者:Key_Ky 发布时间:2021-10-13 07:33:27
标签:线性回归,梯度下降,python
通过学习斯坦福公开课的线性规划和梯度下降,参考他人代码自己做了测试,写了个类以后有时间再去扩展,代码注释以后再加,作业好多:
import numpy as np
import matplotlib.pyplot as plt
import random
class dataMinning:
datasets = []
labelsets = []
addressD = '' #Data folder
addressL = '' #Label folder
npDatasets = np.zeros(1)
npLabelsets = np.zeros(1)
cost = []
numIterations = 0
alpha = 0
theta = np.ones(2)
#pCols = 0
#dRows = 0
def __init__(self,addressD,addressL,theta,numIterations,alpha,datasets=None):
if datasets is None:
self.datasets = []
else:
self.datasets = datasets
self.addressD = addressD
self.addressL = addressL
self.theta = theta
self.numIterations = numIterations
self.alpha = alpha
def readFrom(self):
fd = open(self.addressD,'r')
for line in fd:
tmp = line[:-1].split()
self.datasets.append([int(i) for i in tmp])
fd.close()
self.npDatasets = np.array(self.datasets)
fl = open(self.addressL,'r')
for line in fl:
tmp = line[:-1].split()
self.labelsets.append([int(i) for i in tmp])
fl.close()
tm = []
for item in self.labelsets:
tm = tm + item
self.npLabelsets = np.array(tm)
def genData(self,numPoints,bias,variance):
self.genx = np.zeros(shape = (numPoints,2))
self.geny = np.zeros(shape = numPoints)
for i in range(0,numPoints):
self.genx[i][0] = 1
self.genx[i][1] = i
self.geny[i] = (i + bias) + random.uniform(0,1) * variance
def gradientDescent(self):
xTrans = self.genx.transpose() #
i = 0
while i < self.numIterations:
hypothesis = np.dot(self.genx,self.theta)
loss = hypothesis - self.geny
#record the cost
self.cost.append(np.sum(loss ** 2))
#calculate the gradient
gradient = np.dot(xTrans,loss)
#updata, gradientDescent
self.theta = self.theta - self.alpha * gradient
i = i + 1
def show(self):
print 'yes'
if __name__ == "__main__":
c = dataMinning('c:\\city.txt','c:\\st.txt',np.ones(2),100000,0.000005)
c.genData(100,25,10)
c.gradientDescent()
cx = range(len(c.cost))
plt.figure(1)
plt.plot(cx,c.cost)
plt.ylim(0,25000)
plt.figure(2)
plt.plot(c.genx[:,1],c.geny,'b.')
x = np.arange(0,100,0.1)
y = x * c.theta[1] + c.theta[0]
plt.plot(x,y)
plt.margins(0.2)
plt.show()
图1. 迭代过程中的误差cost
图2. 数据散点图和解直线
总结
Python算法输出1-9数组形成的结果为100的所有运算式
python中实现k-means聚类算法详解
Python编程实现粒子群算法(PSO)详解
如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
来源:https://www.cnblogs.com/Key-Ky/archive/2013/12/10/3468290.html


猜你喜欢
- PyCharm 是我用过的python编辑器中,比较顺手的一个。而且可以跨平台,在macos和windows下面都可以用,这点比较好。是py
- 个人类型和海外类型的小程序不支持 web-view 标签 也就是说个人申请的小程序,就别想跳转了!!!!1.开发的时候,我们难免
- model.py:#!/usr/bin/python# -*- coding: utf-8 -*-import torchfrom torc
- 做图像识别的时候需要在图片中画出特定大小和角度的矩形框,自己写了一个函数,给定的输入是图片名称,矩形框的位置坐标,长宽和角度,直接输出画好矩
- 一个等号 =:表示赋值 ;两个等号 ==:先转换类型再比较 ;三个等号 ===:先判断类型,如果不是同一类型直接false。
- 关于最近要在python下做可视化界面的设计,想到之前用QtDesigner来画界面很是方便,当时画完之后都要手动在终端输入 pyuic5
- 工作中遇到的,在一个.c文件中有很多函数,这个.c是自动生成的,需要将所有的函数通过extern放到.h中,每个函数都是UINT32 O_开
- 一、列表切片(Slicing)由于列表是元素的集合,我们应该能够获得这些元素的任何子集。 例如,如果想从列表中获得前三个元素,我们应该能够轻
- 设置自动的参数注释标识如何使用pycharm自动添加引用注释描述功能使用场景多行注释,且需要对传入的参数以及返回值进行详尽的阐述时,如下图设
- 写文的原因学习 Python 的过程中,经常会使用 pip 命令去安装第三方模块,但细细琢磨下来,我真的掌握这款工具了吗?本文为你全面揭示一
- 项目场景:Python项目需要画两组数据的双柱状图,以下以一周七天两位小朋友吃糖颗数为例进行演示,用matplotlib库实现代码:impo
- 一、字符串(str)字符串转换为列表使用list()方法str_1 = "1235"str_2 = 'zhang
- Python中 join() 函数的使用函数:string.join()Python中有join()和os.path.join()两个函数,
- SQL Server数据库查询速度慢的原因有很多,常见的有以下几种:1、没有索引或者没有用到索引(这是查询慢最常见的问题,是程序设计的缺陷)
- 此文章主要向大家讲述的是SQL Server数据库的分布式数据库系统的实际目标,通俗的讲就是研制分布式数据库系统的目的、动机,其中主要包括的
- 当鼠标移动上去后,字慢慢的变大的 效果应该 如果实现啊<!DOCTYPE html PUBLIC "-//W3C//DTD
- sql="select * from admin where users='"&users&&q
- 这篇文章主要介绍了Python hashlib常见摘要算法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,
- 本文实例讲述了php计算两个整数的最大公约数常用算法。分享给大家供大家参考。具体如下:<?php//计时,返回秒function&nb
- 在网页中,我们经常需要引用大量的javascript和css文件,在加上许多javascript库都包含debug版和经过压缩的releas