37,720
社区成员
发帖
与我相关
我的任务
分享
import numpy as np
import matplotlib.pyplot as plt
#读取训练集中的数据
train_data = np.loadtxt('ccpp_train.txt',delimiter=',')
print('训练集中的数据:',train_data)
#获取训练集数据的总条数
Sum = np.shape(train_data)[0]
print('训练集的总条数:',Sum)
#获取训练集中的X部分
normalX = train_data[:,0:4]
print('X部分:',normalX)
#获取训练集中Y的部分
normalY = train_data[:,4].reshape(Sum,1)
print('Y部分',normalY)
#获取训练集中X部分的平均值
mu = np.mean(normalX,0)
print('X部分的平均值:',mu)
#获取训练集中X部分的标准差
sigma = np.std(normalX,0,ddof=1)
print('X部分的标准差:',sigma)
#标准化
normalX -= np.tile(mu,[Sum,1])
normalX /= np.tile(sigma,[Sum,1])
#实现代价函数
def cost_function(x,y,theta):
num = np.shape(y)[0]
J = np.sum(x.dot(theta)-y)**2/(2*num)
return J
#实现梯度下降
def genaral_function(x,y,theta,alpha,iter_num):
#定义一个可接受的误差范围
canOk = 0.0001
m = x.shape[0]
for iter_index in range(iter_num):
J = cost_function(x,y,theta)
delta = x.T.dot(x.dot(theta)-y)
theta -= (alpha/m)*delta
if J <= canOk:
break
return theta
# 测试集的使用
data = np.loadtxt('ccpp_test.txt',delimiter=',')
X = data[:,0:4]
mm = data.shape[0]
Y = data[:,4].reshape(mm,1)
theta = np.zeros((4,1))
goodth = genaral_function(X,Y,theta,0.05,1000)
# 画图
# X 测试值 Y真实值
x = normalY
y = goodth.dot(X)
plt.plot(x,y,r'x')
plt.show()
D:\Python36\python.exe C:/Users/ASUS/PycharmProjects/Mechaing_test/weekTest01/lineReg.py
训练集中的数据: [[ 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]
...,
[ 19.31 43.56 1013.65 41.54 463.35]
[ 21.4 74.93 1014.58 80.85 434.09]
[ 29.33 52.84 1006.04 44.3 438.25]]
训练集的总条数: 6687
X部分: [[ 8.34 40.77 1010.84 90.01]
[ 23.64 58.49 1011.4 74.2 ]
[ 29.74 56.9 1007.15 41.91]
...,
[ 19.31 43.56 1013.65 41.54]
[ 21.4 74.93 1014.58 80.85]
[ 29.33 52.84 1006.04 44.3 ]]
Y部分 [[ 480.48]
[ 445.75]
[ 438.76]
...,
[ 463.35]
[ 434.09]
[ 438.25]]
X部分的平均值: [ 19.71185135 54.35718857 1013.1687214 73.20855242]
X部分的标准差: [ 7.42148416 12.76360801 5.9547403 14.65785661]
C:/Users/ASUS/PycharmProjects/Mechaing_test/weekTest01/lineReg.py:33: RuntimeWarning: overflow encountered in double_scalars
J = np.sum(x.dot(theta)-y)**2/(2*num)
C:/Users/ASUS/PycharmProjects/Mechaing_test/weekTest01/lineReg.py:47: RuntimeWarning: invalid value encountered in subtract
theta -= (alpha/m)*delta
Traceback (most recent call last):
File "C:/Users/ASUS/PycharmProjects/Mechaing_test/weekTest01/lineReg.py", line 67, in <module>
y = goodth.dot(X)
ValueError: shapes (4,1) and (2881,4) not aligned: 1 (dim 1) != 2881 (dim 0)
Process finished with exit code 1