# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pylab as plt
from multiprocessing import Process
def plotData(X, y):
plt.scatter(X, y, color='r', s=10, marker='x')
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.show()
def computerCost(X, y, theta):
m = len(y)
h = np.dot(X, theta) #X和theta是array类型,用点乘
square = np.square(h - y)
J = 1/(2*m)*sum(square)
return J
def gradientDescent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = np.zeros((num_iters,1))
for i in range(num_iters):
theta = theta - alpha/m*(np.dot(X.T,(np.dot(X,theta))-y))
J_history = computerCost(X, y, theta)
return theta, J_history
if __name__ == '__main__':
#X为txt里第一列
X = np.loadtxt(fname='E:\python\ex1_multi\data\ex1data1.txt',dtype=float,delimiter=",",usecols=(0,))
#y为txt里第二列
y = np.loadtxt(fname='E:\python\ex1_multi\data\ex1data1.txt',dtype=float,delimiter=",",usecols=(1,))
m = len(X)
#读取的数据为1*m,转换为m*1
X = X.reshape(m, 1)
y = y.reshape(m, 1)
#绘图
plotData(X, y)
X = np.column_stack((np.ones((m,1),dtype=int), X)) #Add a column of ones to x
theta = np.zeros((2,1))
iterations = 1500
alpha = 0.01
J = computerCost(X, y, theta) #Expected cost value (approx) 32.07
print(J)
J = computerCost(X, y, [[-1],[2]]) #Expected cost value (approx) 54.24
print(J)
theta = gradientDescent(X, y, theta, alpha, iterations)[0]
print(theta)
Andrew Ng的machine learning课程week2编程题python实现
最新推荐文章于 2022-02-03 15:49:21 发布
