题目要求
1.按要求完成下面的各项需求。
利用python编写如下程序,
现有一个循环发电场样本数据集,其中包括训练集(ccpp_train.txt文件)和测试集(ccpp_test.txt文件)。数据集格式如下:
AT(温度) V(压力) AP(湿度) RH(压强) PE(输出电力)
8.34 40.77 1010.84 90.01 480.48
23.64 58.49 1011.4 74.2 445.75
29.74 56.9 1007.15 41.91 438.76
请通过Python实现线性回归模型,并用此模型预测输出电力,具体要求如下:
完成数据集的读取
实现代价函数
实现梯度下降函数
要求输出迭代过程中的代价函数值
完成测试集的数据预测,并计算在测试集上的代价函数值
以横轴为真实值,纵轴为预测值,画出散点图
代码实现
import numpy as np
from matplotlib import pyplot as plt
# 读取数据
data_train = np.loadtxt(r'ccpp_train.txt',delimiter=',')
data_test = np.loadtxt(r'ccpp_train.txt',delimiter=',')
# 定义数据处理函数
def preprocess(data):
# 数据提取
X = data[:,:-1]
y = data[:,-1]
# 特征缩放
X -= np.mean(X,axis=0)
X /= np.std(X,axis=0,ddof=1)
# 数据初始化
X = np.c_[np.ones(len(X)),X]
y = np.c_[y]
# 数据处理完毕 返回
return X,y
# 调用数据处理函数获得处理好的数据
X_train,y_train = preprocess(data_train)
X_test,y_test = preprocess(data_test)
# 定义模型
def model(X,theta):
h = np.dot(X,theta)
return h
# 定义代价函数
def costFunction(h,y):
m = len(h)
J = (1.0/(2 * m)) * np.sum(np.square(h -y))
return J
# 定义梯度下降
def gradeDesc(X,y,alpha=0.01,iter_num=2000):
# 数据准备
# 获取维度
m,n = X.shape
# 初始化theta
theta = np.zeros((n,1))
# 初始化代表值
J_history = np.zeros(iter_num)
# 执行梯度下降
for i in range(iter_num):
# 调用模型获得数据的预