非线性回归(逻辑回归)
一.理论
1.概率
1)定义:对一件事发生的可能性的衡量;
2)范围:0<=P<=1
3)计算方法:
a.根据个人置信
b.根据历史数据
c.根据模拟数据
4)条件概率
定1
2.逻辑回归(Logistic Regression)
1)在特定的场景中,线性回归不能正确的分类数据
2)基本模型
定2
定3
3.Cost函数(代价最小化)
线性回归:
定4
定5
定6
4.梯度下降(gradient decent)求解方程
二.实践
1)代码
# -*- coding: utf-8 -*-
import numpy as np
import random
#定义梯度下降算法
'''
x:数据集
y:结果集
theta:学习的参数(即类似于线性回归中因变量的参数)
alpha:学习率
m:实例个数
numIterations:更新的次数
'''
def gradientDescent(x,y,theta,alpha,m,numIterations):
#对X矩阵进行转置
xTrans = x.transpose()
for i in range(0,numIterations):
#向量表示
hypothesis = np.dot(x,theta)
#预测偏差
loss = hypothesis-y
cost = np.sum(loss**2)/(2*m)
print("Iteration %d |Cost:%f"%(i,cost))
#更新值
gradient = np.dot(xTrans,loss)/m
theta = theta-alpha*gradient
return theta
#产生数据
'''
numPoints:实例的个数,决定有多少行
bias:偏好值
variance:方差
'''
def getData(numPoints,bias,variance):
#行数为numPoints,列数为2
x = np.zeros(shape=(numPoints,2))
#归类的标签
y = np.zeros(shape=(numPoints))
#range函数取值为0-numPoints-1
for i in range(0,numPoints):
x[i][0] = 1
x[i][1] = i
#uniform函数产生0-1的随机数
y[i] = (i+bias)+random.uniform(0,1)*variance
return x,y
#测试数据生成
x,y = getData(100,25,10)
#print("x")
#print(x)
#print("y")
#print(y)
m,n = np.shape(x)
y1 = np.shape(y)
#print(m,n)
#print(y1)
numIterations = 100000
alpha = 0.0005
#因变量个数为n
theta = np.ones(n)
theta = gradientDescent(x,y,theta,alpha,m,numIterations)
print(theta)
2)实验结果(数据太多,仅显示部分结果)
Iteration 99979 |Cost:4.096864
Iteration 99980 |Cost:4.096864
Iteration 99981 |Cost:4.096864
Iteration 99982 |Cost:4.096864
Iteration 99983 |Cost:4.096864
Iteration 99984 |Cost:4.096864
Iteration 99985 |Cost:4.096864
Iteration 99986 |Cost:4.096864
Iteration 99987 |Cost:4.096864
Iteration 99988 |Cost:4.096864
Iteration 99989 |Cost:4.096864
Iteration 99990 |Cost:4.096864
Iteration 99991 |Cost:4.096864
Iteration 99992 |Cost:4.096864
Iteration 99993 |Cost:4.096864
Iteration 99994 |Cost:4.096864
Iteration 99995 |Cost:4.096864
Iteration 99996 |Cost:4.096864
Iteration 99997 |Cost:4.096864
Iteration 99998 |Cost:4.096864
Iteration 99999 |Cost:4.096864
[ 30.67578723 0.98134199]