简单线性回归(单变量)

简单线性回归(单变量)

自动生成数据

使用make_regression生成回归模型数据。几个关键参数有n_samples(生成样本数), n_features(样本特征数),noise(样本随机噪音)和coef(是否返回回归系数)。

import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
from sklearn.datasets.samples_generator import make_regression
# X为样本特征,y为样本输出, coef为回归系数,共10个样本,每个样本1个特征
X, y, coef =make_regression(n_samples=10, n_features=1,noise=10, coef=True)
# 画图
plt.scatter(X, y,  color='black')
plt.plot(X, X*coef, color='blue',
         linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()

在这里插入图片描述

算术法求解

线性回归数学分析:https://zhuanlan.zhihu.com/p/41821254

Python环境下的8种简单线性回归算法具体参考:https://blog.csdn.net/tkkzc3e6s4ou4/article/details/78955619

1.最小二乘
最小二乘法是一种数学优化技术,它通过最小化误差的平方和寻找数据的最佳函数匹配。

import numpy as np
def fitslr(x,y):
    n=len(x)
    dinominator=0
    numerator=0
    for i in range (0,n):
        numerator +=(x[i]-np.mean(x))*(y[i]-np.mean(y))
        dinominator+= (x[i]-np.mean(x))**2
    print("numerator",numerator)
    print("dinominator",dinominator)
    b1=numerator/float(dinominator)
    b0=np.mean(y)/float(np.mean(x))
    print(b1)
    print(b0)
    return b0,b1
def predict(x,b0,b1):
    return b0+x*b1

x=[1,3,2,1,3]
y=[14,24,18,17,27]
b0,b1=fitslr(x,y)

x_text=6
y_text=predict(6,b0,b1)
print("x_text",y_text)

results:

dinominator 4.0
5.0
10.0
x_text 40.0

2.梯度下降
什么是梯度下降? 梯度下降是一种求最优化解的方式,就好比是一小人站在山顶上想要最快速度下山,下山有很多的方向,但那个是最快的方向?下山最快的方向垂直于山的等高线切线的反方向,然后往下走一了一段以后,然后在看看自己是不是在最佳下山方向(即垂直于山的等高线的切线方向),然后往下走一段。这么一直往下走,直到山底。(参考https://www.jianshu.com/p/887ca091b02b)

import numpy as np
import random


def gradient_descent(alpha, x, y, ep=0.0001, max_iter=10000):
    converged = False
    iter = 0
    m = x.shape[0]  # 数据的行数

    # 初始化参数(theta)
    t0 = np.random.random(x.shape[1])
    t1 = np.random.random(x.shape[1])

    # 代价函数, J(theta)
    J = sum([(t0 + t1 * x[i] - y[i]) ** 2 for i in range(m)])

    # 进行迭代
    while not converged:
        # 计算训练集中每一行数据的梯度 (d/d_theta j(theta))
        grad0 = 1.0 / m * sum([(t0 + t1 * x[i] - y[i]) for i in range(m)])
        grad1 = 1.0 / m * sum([(t0 + t1 * x[i] - y[i]) * x[i] for i in range(m)])

        # 更新参数 theta
        # 此处注意,参数要同时进行更新,所以要建立临时变量来传值
        temp0 = t0 - alpha * grad0
        temp1 = t1 - alpha * grad1
        t0 = temp0
        t1 = temp1

        # 均方误差 (MSE)
        e = sum([(t0 + t1 * x[i] - y[i]) ** 2 for i in range(m)])

        if abs(J - e) <= ep:
            print('Converged, iterations: ', iter, '!!!')
            converged = True

        J = e  # 更新误差值
        iter += 1  # 更新迭代次数

        if iter == max_iter:
            print('Max interactions exceeded!')
            converged = True

    return t0, t1

向量法求解

1.最小二乘

from sklearn.linear_model import LinearRegression
import numpy as np
x = np.array([1,3,2,1,3])
y = np.array([14,24,18,17,27])
# 定义线性回归模型
model = LinearRegression()
model.fit(x.reshape(len(x),1), y) # 训练, reshape 操作把数据处理成 fit 能接受的形状
print(model.coef_)
print(model.intercept_)

2.梯度下降

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt


dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,0].values
Y = dataset.iloc[:,-1].values

#将数据分成训练集和测试集,训练集用于训练模型,测试集用于测试训练的模型的效果
X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size = 0.3,random_state = 0)
X_train = X_train.reshape(-1,1)
Y_train = Y_train.reshape(-1,1)

regresor = LinearRegression()
regresor.fit(X_train,Y_train)
#根据模型得出的对应训练集的预测Y值
predict = regresor.predict(X_train.reshape(-1,1))

plt.figure(figsize=(10,12)) #设置画布大小
figure = plt.subplot(211)  #将画布分成2行1列,当前位于第一块子画板

plt.scatter(X_train, Y_train,color = 'red')  #描出训练集对应点
plt.plot(X_train,predict,color='black')  #画出预测的模型图
plt.xlabel('YearsExperience')
plt.ylabel('Salary')
plt.title('Train set')

#将模型应用于测试集,检验拟合结果
plt.subplot(212)
plt.scatter(X_test, Y_test,color = 'red')
plt.plot(X_train,predict,color='black')
plt.xlabel('YearsExperience')
plt.ylabel('Salary')
plt.title('Test set')

算术法、 向量法性能比较

Sklearn 是基于Python的机器学习工具模块。里面主要包含了6大模块:分类、回归、聚类、降维、模型选择、预处理。根据Sklearn 官方文档资料,下面将各个模块中常用的模型函数总结出来。
回归及分类(监督学习)
1.1 广义线性模型 (fromsklearn import linear_model)
最小二乘法:拟合一个线性模型, 使得数据集实际观测数据和预测数据(估计值)之间残差平方和最小。
clf=linear_model.LinearRegression(), clf.fit(X,y)
岭回归:改良的最小二乘,解决共线问题。
clf=linear_model.Ridge(alpha=0.5),clf.fit(X,y)
逻辑回归:
clf=linear_model.LogisticRegression()
1.2 朴素贝叶斯
高斯模型: from sklearn.naive_bayes import GassianNB
Gnb=GassianNB(),gnb.fit(data, target).predict(data)
多项式模型:MultinomialNB
伯努利模型:会把输入数据二元化BernoulliNB
1.3 决策树 from sklearn import tree
决策树分类器:clf=tree.DecisionTreeClassifier()
回归分类器(y 值为float非int):
clf=tree. DecisionTreeRegressor()
1.4 支持向量机
from sklearn import svm
clf=svm.SVC()2. 聚类
K-means:
from sklearn.cluster import KMeans
kmeans= KMeans(n_clusters=2, random_state=0).fit(X)
降维
PCA:
From sklearn.decomposition import PCA
pca = PCA(n_components=2)
method:
fit(X[y])
get_covariance()
get_params([deep])
get_precision()
score(X[y])
特征选择
树特征:
From sklearn.ensemble import ExtraTreesClassifier5 .数据预处理
From sklearn import preprocessing
标准化:preprocessing.scale(x)
规范化:preprocessing.normalize()
二值化: preprocessing.Binarizer()
处理缺失值:fromsklearn.preprocessing import Imputer
imp=Imputer(missing_values=‘NaN’,strategy=‘mean’,axis=0)


(本文主要参考:https://blog.csdn.net/qq_40594554/article/details/88079241)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值