一元线性回归模型原理参考之前写的博客链接:https://blog.csdn.net/zzx2016zzx/article/details/80589050
import pandas as pdimport tensorflow as tfimport numpy as npfrom matplotlib import pyplot as pltplt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签plt.rcParams['axes.unicode_minus']=False #解决负号“-”显示为方块的问题data=pd.read_csv('D:/code/python/pythonProject/tensorflow51自学/tensorflow入门与实战-基础部分数据集/Income1.csv')x=data.Educationy=data.Incomemodel=tf.keras.Sequential()#定义模型, 使用一层全连接, 输出为一维,输入为一维model.add(tf.keras.layers.Dense(1,input_shape=(1,)))#编译模型, 使用adam(梯度下降)作为优化函数, 使用mse(均方差)作为损失函数model.compile(optimizer='adam',loss='mse')#mes均方差# 开始训练history=model.fit(x,y,epochs=50000)#训练次数# Y=model.predict(pd.Series([20]))#使用训练后的模型进行预测Y=model.predict(x)plt.plot(x,Y,'r-s',label="训练模型预测")plt.scatter(data.Education ,data.Income,color='b',label='原始数据')#一元线性b=np.sum((x-np.mean(x))*(y-np.mean(y)))/np.sum((x-np.mean(x))**2)a=np.mean(y)-b*np.mean(x)x1=np.arange(10,22)y2=b*x1+aplt.plot(x1,y2,'m-p',label='一元线性预测')plt.legend()plt.show()
Income1.csv数据,其中Education为受到教育年限、Income为收入,想预测受到教育的年限和收入之间的关系
EducationIncome1026.6588410.4013427.3064410.8428122.1324111.2441521.1698411.6454815.1926312.0869626.3989512.4882917.435���,���3112.8896325.5078913.2909736.8845913.7324439.6661114.1337834.3962814.5351241.4979914.9765944.9815715.3779347.039615.7792648.2525816.2207457.0342516.6220751.4909217.0234161.3366217.4648857.5819917.8662268.5537118.2675664.3109318.7090368.9590119.1103774.6146419.5117171.867219.9130476.0981420.3545275.7752220.7558572.4860621.1571977.3550221.5986672.118792280.26057训练500次训练5000次训练30000次训练50000次总结:随着模型训练次数的增加,训练的一元线性回归越来越接近标准的线性回归模型,从中可以看出,只要训练次数足够大,训练模型就可以无线逼近直到完成和标准的模型重合
2、多元线性回归预测