Exercise 2:Logistic Regression---实现一个逻辑回归
问题描述:用逻辑回归根据学生的考试成绩来判断该学生是否可以入学。
这里的训练数据(training instance)是学生的两次考试成绩,以及TA是否能够入学的决定(y=0表示成绩不合格,不予录取;y=1表示录取)
因此,需要根据trainging set 训练出一个classification model。然后,拿着这个classification model 来评估新学生能否入学。
训练数据的成绩样例如下:第一列表示第一次考试成绩,第二列表示第二次考试成绩,第三列表示入学结果(0--不能入学,1--可以入学)
代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt path = 'ex2data1.txt' data = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted']) # 设置特征名称 data.head() positive = data[data['Admitted'].isin([1])] #选取admitted中为1 的 negative = data[data['Admitted'].isin([0])] #选取admitted中为0 的 fig, ax = plt.subplots() # 画图 ax.scatter(positive['Exam 1'], positive['Exam 2'], c='b', marker='o', label='Admitted') #marker就是标记的形状 ax.scatter(negative['Exam 1'], negative['Exam 2'], c='r', marker='x', label='Not Admitted') ax.legend() #显示色彩标签 ax.set_xlabel('Exam 1 Score') ax.set_ylabel('Exam 2 Score') plt.show() #s型函数(sigmoid) 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)) #设置 偏置单元x0 data.insert(0, 'Ones', 1) # 初始化变量 cols = data.shape[1] X = data.iloc[:,0:cols-1] y = data.iloc[:,cols-1:cols] #转化成矩阵类型 X = np.array(X.values) y = np.array(y.values) theta = np.zeros(3) # 注意 !!! print(cost(theta,X,y)) #梯度下降公式,只下降了 一次c ,准备被直接调用 def gradient(theta, X, y): theta = np.matrix(theta) X = np.matrix(X) y = np.matrix(y) parameters = int(theta.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 print(gradient(theta,X,y)) #调用scipy中的 optimizezu直接求出最佳 最优参数 import scipy.optimize as opt result = opt.fmin_tnc(func=cost, x0=theta, fprime=gradient, args=(X, y)) # 一步直接求出 print(result) print(cost(result[0], X, y)) #通过sigmod直接预测结果 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) #python3和python2不同,需要加上list() print(list(zip(predictions,y))) # zip(predictions,y) 就是 形成 ((a,b),(c,d) ......)这种类型的数组 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 = {0}%'.format(accuracy))