【自用】吴恩达机器学习编程题

*代码参考及数据来自
https://github.com/fengdu78/Coursera-ML-AndrewNg-Notes
https://www.kesci.com/home/workspace/project?tab=public
*
Linear Regression with One Variable
据城市人口数量,预测开小吃店的利润 数据在ex1data1.txt里,第一列是城市人口数量,第二列是该城市小吃店利润。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


path = "D:\\machinelearning\\Coursera-ML-AndrewNg-Notes\\cod" \
       "e\\ex1-linear regression\\ex1data1.txt"
# 以数据框形式呈现
data = pd.read_csv(path, header=None, names=['Population','Profit'])

# 调整参数θ(0) θ(1) h(x) = θ(0)+θ(1)*x
# 计算代价函数J(θ) 用梯度减少得到一个最小J(θ)
def computeCost(X, y , theta):
    # 矩阵X*theta的逆置
    inner = np.power(((X*theta.T)-y), 2)
    return np.sum(inner) / (2*len(X))

# 加入一列x 用于更新θ(0) 将θ初始化为0
data.insert(0, 'Ones', 1)
# 初始化X,y
# cols为data的列数
cols = data.shape[1]
# X是data里的除最后列(即为Ones和Population)
X = data.iloc[:,:-1]
# y为data的最后一列(Profit) X为训练集 y为目标变量
y = data.iloc[:, cols-1:cols]

# 代价函数是应该是numpy矩阵,所以我们需要转换X和Y,才能使用它们
X = np.matrix(X.values)
y = np.matrix(y.values)
# 初始化θ为[0,0]
theta = np.matrix(np.array([0, 0]))

# 计算代价函数J(θ) 此时θ为初始值0
computeCost(X, y, theta)

# 梯度下降 J(θ)的变量是θ,梯度下降的过程是使J(θ)不断减小并最终趋于稳定
# 趋于稳定后得到的θ用于预测小吃店在35000及70000人城市规模的利润
def gradientDescent(X, y, theta, alpha, iters):
    # 把temp初始化为和theta一样行列并全为0的数组  temp用于存储theta
    temp = np.matrix(np.zeros(theta.shape))
    # theta的列数(2)
    parameters = int(theta.ravel().shape[1])
    # cost为一行 iters列(默认为浮点数)
    cost = np.zeros(iters)
    for i in range(iters):
        # h(x)与y的误差
        error = (X*theta.T)-y
        for j in range(parameters):
            term = np.multiply(error, X[:, j])
            temp[0, j] = theta[0,j]-((alpha/len(X)) * np.sum(term))
        # 更新theta J(theta)
        theta = temp
        cost[i] = computeCost(X, y, theta)

    return theta,cost

# 初始化学习效率和迭代次数
alpha = 0.01
iters = 1500

g, cost = gradientDescent(X, y, theta, alpha, iters)
print(g)
#预测35000和70000城市规模的小吃摊利润
predict1 = [1, 3.5]*g.T
predict2 = [1, 7]*g.T
print('predict1=', predict1)
print('predict2=', predict2)
# 两个变量
path = "D:\\machinelearning\\Coursera-ML-AndrewN" \
       "g-Notes\\code\\ex1-linear regression\\ex1data2.txt"
data2 = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
print(data2.head())
# size变量是bedrooms变量的1000倍大小,统一量级会让梯度下降收敛的更快
# 做法就是,将每类特征减去他的平均值后除以标准差
data2 = (data2 - data2.mean()) / data2.std()
print(data2.head())

# 梯度下降
# 加一列常数
data2.insert(0, 'Ones', 1)
# 初始化X和y
cols = data2.shape[1]
X2 = data2.iloc[:, :-1]
y2 = data2.iloc[:, cols-1:cols]
X2 = np.matrix(X2.values)
y2 = np.matrix(y2.values)
theta2 = np.matrix(np.array([0,0,0]))
g2, cost2 = gradientDescent(X2, y2, theta2, alpha, iters)
print(g2)

利用正规方程解出向量 利用正规方程解出向量

在python 3.5以后,@是一个操作符,表示矩阵-向量乘法

A@x 就是矩阵-向量乘法A*x: np.dot(A, x)

# 正规方程
def normalEqn(X, y):
    theta = np.linalg.inv(X.T@X)@X.T@y
    return theta

final_theta = normalEqn(X,y)
print(final_theta)

这次,我们不自己写代码实现梯度下降,我们会调用一个已有的库。这就是说,我们不用自己定义迭代次数和步长,功能会直接告诉我们最优解

scipy.optimize.fmin_tnc 函数
最常使用的参数:

func:优化的目标函数

x0:初值

fprime:提供优化函数func的梯度函数,不然优化函数func必须返回函数值和梯度,或者设置approx_grad=True

approx_grad :如果设置为True,会给出近似梯度

args:元组,是传递给优化函数的参数

drop函数的使用:删除行、删除列 drop函数默认删除行,列需要加axis = 1

正则化优化logistic回归过拟合

正则化(Regularized)是解决过拟合问题的一种方法,它将保留所有的特征变量,但是会减小特征变量的数量级(参数数值的大小θ(j)),当我们有很多特征变量时,其中每一个变量都能对预测产生一点影响,每一个变量都是有用的,因此我们不希望把它们删掉,但是我们可以通过正则化方式增加它们的成本cost,来减小我们的函数中的一些项的权重,其意义在于平滑函数曲线,使得预测函数相对简单一些,避免过度复杂函数的过拟合问题。
在这里插入图片描述

`import numpy as np
import pandas as pd
import scipy.optimize as opt
import matplotlib.pyplot as plt

path = "D:\\machinelearning\\Coursera-ML-AndrewNg-Notes\\code\\ex2-logistic regression\\ex2data1.txt"
data = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])


def sigmoid(z):
    return 1 / (1 + np.exp(-z))


def cost(theta, X, y):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
    second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
    return np.sum(first - second) / len(X)


data.insert(0, 'Ones', 1)
print(data.head())

cols = data.shape[1]

X = data.iloc[:, 0:cols - 1]
y = data.iloc[:, cols - 1:cols]
z = data.iloc[:, cols - 1]
theta = np.zeros(3)

X = np.array(X.values)
y = np.array(y.values)

cost(theta, X, y)


# 梯度计算
def gradient(theta, X, y):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)

    parameters = int(theta.ravel().shape[1])
    grad = np.zeros(parameters)

    error = sigmoid(X * theta.T) - y

    for i in range(parameters):
        term = np.multiply(error, X[:, i])
        grad[i] = np.sum(term) / len(X)

    return grad


result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, y))
print(result)
# 用θ的计算结果代回代价函数计算
print(cost(result[0], X, y))


# 实现hθ
def hfunc1(theta, X):
    return sigmoid(np.dot(theta.T, X))


# 如果一个学生exam1得分45,exam2得分85,他录取的概率
print(hfunc1(result[0], [1, 45, 85]))


# 定义预测函数
def predict(theta, X):
    probability = sigmoid(X * theta.T)
    return [1 if x >= 0.5 else 0 for x in probability]


# 统计预测正确率
theta_min = np.matrix(result[0])
predictions = predict(theta_min, X)
# correct是一个list
correct = [1 if (a == 1 and b == 1) or (a == 0 and b == 0) else 0 for (a, b) in zip(predictions, y)]
accuracy = (sum(map(int, correct)) % len(correct))
print(accuracy)
print('accuracy = {0}%'.format(accuracy))

# 在训练的第二部分,我们将实现加入正则项提升逻辑回归算法。
# 设想你是工厂的生产主管,你有一些芯片在两次测试中的测试结果,测试结果决定是否芯片要被接受或抛弃。你有一些历史数据,帮助你构建一个逻辑回归模型。
path = "D:\\machinelearning\\Coursera-ML-AndrewNg-Notes\\code\\ex2-logistic regression\\ex2data2.txt"
data_int = pd.read_csv(path, header=None, names=['Test 1', 'Test 2', 'Accepted'])
print(data_int.head())

degree = 6
data2 = data_int
x1 = data2['Test 1']
x2 = data2['Test 2']

data2.insert(3, 'Ones', 1)

for i in range(1, degree+1):
    for j in range(0, i+1):
        data2['F' + str(i - j) + str(j)] = np.power(x1, i - j) * np.power(x2, j)
data2.drop('Test 1', axis=1, inplace=True)
data2.drop('Test 2', axis=1, inplace=True)
print(data2.head())

# 实现正则化的代价函数 θ0不需要正则化 从θ1开始
def costReg(theta, X, y, learningRate):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
    second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
    reg = (learningRate / (2 * len(X))) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2))
    return np.sum(first - second) / len(X) + reg

# 实现正则化的梯度函数
def gradientReg(theta, X, y, learingRate):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    parameters = int(theta.ravel().shape[1])
    grad = np.zeros(parameters)

    error = sigmoid(X*theta.T) - y

    for i in range(parameters):
        term = np.multiply(error, X[:,i])

        if (i == 0):
            grad[i] = np.sum(term) / len(X)
        else:
            grad[i] = (np.sum(term) / len(X)) + ((learningRate / len(X)) * theta[:, i])

        return grad

cols = data2.shape[1]
X2 = data2.iloc[:,1:cols]
y2 = data2.iloc[:,0:1]
theta2 = np.zeros(cols-1)

# 进行类型转换
X2 = np.array(X2.values)
y2 = np.array(y2.values)

# λ设为1
learningRate = 1

# 计算初始代价
a = costReg(theta2, X2, y2, learningRate)
print(a)

# 用工具库求解参数
result2 = opt.fmin_tnc(func=costReg, x0=theta2, fprime=gradientReg,args=(X2, y2, learningRate))
# 使用预测函数


theta_min = np.matrix(result2[0])
predictions = predict(theta_min, X2)
correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y2)]
accuracy = (sum(map(int, correct)) % len(correct))
print('accuracy = {0}%'.format(accuracy))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值