机器学习

第一章:机器学习基础 第二章:线性回归 第三章:逻辑回归 第四章:BP 神经网络 第五章:卷积神经网络 第六章:循环神经网络 第七章:决策树与随机森林 第八章:支持向量机 第九章:隐马尔科夫 第十章:聚类等算法 ...

单变量线性回归原理与python实现

github地址


前言

机器学习是从人工智能中产生的一个重要学科分支,是实现智能化的关键

一、基础概念

回归分析(Regression Analysis)是确定两种或两种以上变量间相互依赖的定量关系的一种统计分析方法 ,是一种预测性的建模技术
在这里插入图片描述

1.1 线性回归

线性回归,简单而言,就是将输入项分别乘以一些常量,再将结果加起来得到输出。线性回归包括一元线性回归和多元线性回归。
在这里插入图片描述

1.1.1 单变量线性回归

线型回归分析中,如果仅有一个自变量与一个因变量,且其关系大致上可用一条直线表示,则称之为简单回归分析。
如果发现因变量Y和自变量X之间存在高度的正相关,可以确定一条直线的方程,使得所有的数据点尽可能接近这条拟合的直线。简单回归分析的模型可以用以下方程表示:
Y=a+bx
其中:Y为因变量,a为截距,b为相关系数,x为自变量。

二、单变量线性回归练习

2.1 吴恩达单变量线性回归作业

# 开发时间 ;2021/5/12 0012 15:04

#导入库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

#导入数据集
#note:ex1data1.txt包含我们的线性回归问题的数据集。
# 第一列是一个城市的人口第二列是该城市一辆快餐车的利润。
# 利润为负数表示亏损。
data=pd.read_csv('F:\\ML\\线性回归\\数据文件\\ex1data1.txt',header=None,names=['population','profit'])
# print(data.head(5))

#画出预先散点图
data.plot(x='population',y='profit',kind='scatter',figsize=(16,9))
plt.show()

#代价函数
def cost_fun(X,y,theta):
     inner=(np.dot(X,theta)-y)**2
     m=len(X)
     return np.sum(inner)/2*m
#令x0=1
data.insert(0,'Ones',1)
# print(data)
X=data.iloc[:,:-1].values
print(X)
y=data.iloc[:,-1].values
#初始化theta
theta=np.zeros(X.shape[1])


#梯度下降
def gradient(X,y,alpha,theta):
    m = len(X)
    for i in range(1000):
        theta=theta-(alpha/m)*np.dot(X.T,(np.dot(X,theta)-y))
    return theta

theta=gradient(X,y,0.01,theta)
print(theta)
fig = plt.figure()
ax= plt.axes(projection='3d')
# fig,ax=plt.subplots(figsize=(16,9))
x=np.linspace(data.population.min(),data.population.max(),100)
y=theta[0]+theta[1]*x
ax.plot(x,y,'r',label='Prediction')
ax.scatter(data.population,data.profit,label='Traning Data')#画点
ax.legend(loc=2)##点和线的图例,2表示在左上角。不写这句的话图例出现不了
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('single_linear_regression')
plt.show()

可视化数据
在这里插入图片描述
拟合效果
在这里插入图片描述

2.2 房价预测

# 开发时间 ;2021/5/4 0004 21:38
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import datasets,linear_model

def data(file_name):
    data=pd.read_csv(file_name)
    X=[]
    Y=[]
    for single_square_feet,single_price_value in zip(data['square_feet'],data['price']):
        #遍历数据
        X.append([float(single_square_feet)])
        Y.append(float(single_price_value))
    return X,Y

#将数据拟合到线性模型
def linear_model_main(X,Y,predict_value):
    '''
    :param X_parameters:平方英尺
    :param Y_parameters:一平方英尺单价
    :param predict_value:预测值
    :return:
    '''
    #创建线性回归对象
    regression=linear_model.LinearRegression()#建立线性回归模型
    regression.fit(X,Y)#训练模型
    predict_outcome=regression.predict(predict_value)#预测结果
    predictions={}
    predictions['intercept']=regression.intercept_#相当于y=ax+b中的b,截距
    predictions['coefficient'] = regression.coef_#相当于y=ax+b中的a,系数
    predictions['predicted_value']=predict_outcome
    return predictions

X,Y=data('input_data.csv')
predictvalue=[[700]]
result=linear_model_main(X,Y,predictvalue)
print("Intercept value",result['intercept'])
print("coefficient",result['coefficient'])
print("predicted value",result['predicted_value'])
print('此模型为:','Y =',result['coefficient'],'* X +',result['intercept'])

#可视化
def show_linear_line(X,Y):
        regression=linear_model.LinearRegression()
        regression.fit(X,Y)
        plt.scatter(X,Y,color='blue')
        plt.plot(X,regression.predict(X),color='red',linewidth=4)
        plt.xticks(())
        plt.yticks(())
        plt.show()
show_linear_line(X,Y)

三、总结

重新发一个,之前的有问题。欢迎大家交流。