机器学习之癌症预测

相关代码:

来源:代码来源

#宗旨,先前项传播,然后进行梯度下降算法,然后反向传播,通过反向传播用来更新参数
import numpy as np
from sklearn.datasets import load_breast_cancer


def feature_scalling(X):
    mean = X.mean(axis=0)
    std = X.std(axis=0)
    return (X - mean) / std


def load_data(shuffled=False):
    data_cancer = load_breast_cancer()
    x = data_cancer.data
    y = data_cancer.target
    x = feature_scalling(x)
    y = np.reshape(y, (len(y), 1))
    if shuffled:
        shuffled_index = np.random.permutation(y.shape[0])
        x = x[shuffled_index]
        y = y[shuffled_index]
    return x, y


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


def gradDescent(X, y, W, b, alpha, maxIt):
    cost_history = []
    maxIteration = maxIt
    m, n = X.shape
    for i in range(maxIteration):#每迭代一次参数更新一次
        z = np.dot(X, W) + b
        error = sigmoid(z) - y
        print (error.shape)
        W = W - (1 / m) * alpha * np.dot(X.T, error)
        b = b - (1.0 / m) * alpha * np.sum(error)
        cost_history.append(cost_function(X, y, W, b))#每迭代一次计算当前代价并添加到cost_history中
    return W, b, cost_history


def accuracy(X, y, W, b):
    m, n = np.shape(X)
    z = np.dot(X, W) + b
    y_hat = sigmoid(z)
    predictioin = np.ones((m, 1), dtype=float)
    for i in range(m):
        if y_hat[i, 0] < 0.5:
            predictioin[i] = 0.0
    return 1 - np.sum(np.abs(y - predictioin)) / m


def cost_function(X, y, W, b):
    m, n = X.shape
    z = np.dot(X, W) + b
    y_hat = sigmoid(z)
    J = (-1 / m) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))
    return J

if __name__ == '__main__':#程序从这里开始运行
    X, y = load_data()
    m, n = X.shape
    print(X.shape)#569*30
    alpha = 0.1
    W = np.random.randn(n, 1)
    b = 0.1
    maxIt = 200
    W, b, cost_history = gradDescent(X, y, W, b, alpha, maxIt)
    print("******************")
    print("W is :             ")
    print(W)
    print("accuracy is :         " + str(accuracy(X, y, W, b)))
    print("******************")

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值