#菜鸟机器学习的逆袭之路#Day4

isin()接受一个列表,判断该列中元素是否在列表中。

fig,ax = plt.subplots(figsize = (12,8))
#fig代表绘图窗口(Figure);ax代表这个绘图窗口上的坐标系(axis),一般会继续对ax进行操作。
legend()的主要作用就是用于在图上标明一个图例,用于说明每条曲线的文字显示。 你也可以把图例控制在左边,右边,底下等等。
实际使用中,legend()有一个loc参数,用于控制图例的位置。 比如 plot.legend(loc=2) , 这个位置就是4象项中的第二象项,也就是左上角。 loc可以为1,2,3,4 这四个数字。
原文连接:
http://30daydo.com/article/215
转载请注明出处

fmin_tnc函数:
参数:
func:优化的目标函数
x0:初值
fprime:提供优化函数func的梯度函数,不然优化函数func必须返回函数值和梯度,或者设置approx_grad=True
approx_grad :如果设置为True,会给出近似梯度
args:元组,是传递给优化函数的参数
返回:
x : 数组,返回的优化问题目标值
nfeval : 整数,function evaluations的数目
在进行优化的时候,每当目标优化函数被调用一次,就算一个function evaluation。在一次迭代过程中会有多次function evaluation。这个参数不等同于迭代次数,而往往大于迭代次数。
rc : int,Return code, see below

#np中linspace函数:第一个参数开始值、第二个参数结束值(不包括)、第三个参数步长(每个元素间的间隔)

引入数据:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

path = ‘d:/ex2data1.txt’
data = pd.read_csv(path,header = None,names = [‘Exam 1’,‘Exam 2’,‘Admitted’])
data.head()

#数据分组
positive = data[data[‘Admitted’].isin([1])]
negative = data[data[‘Admitted’].isin([0])]
fig,ax = plt.subplots(figsize = (12,8))
ax.scatter(positive[‘Exam 1’],positive[‘Exam 2’],s = 50,c=‘b’,marler = ‘o’,label = ‘Admitted’)
ax.scatter(negative[‘Exam 1’],negative[‘Exam 2’],s = 50,c=‘r’,marker = ‘x’,label = ‘Not Admitted’)
ax.legend()
ax.set_xlabel(‘Exam 1 Score’)
ax.set_ylabel(‘Exam 2 Score’)
plt.show()

#编辑sigmoid函数:
def sigmoid(z)
return 1/(1+np.exp(-z))

#编辑代价函数J(theta)
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),log(1 - sigmoid(X * theta.T)))
return np.sum(first - second)/(len(X))

#初始化X,y,theta
data.insert(0,‘Ones’,1)
cols = data.shape[1]
X = data.iloc[:,:-1]
y = data.iloc[:,cols-1:cols]
theta = np.zeros(3)

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

#检查矩阵维度
X.shape,y.shape,theta.shape
cost(theta,X,y)

#实现梯度计算函数,并且无theta的更新
def gradient(theta,X,y):
theta = np.matrix(theta)
X = np.matrix(X.values)
y = np. matrix(y.values)
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

#之后调用python库中可以自动找到迭代次数和步长的函数,该函数会自动解出最优解。

import scipy.optimize as opt
result = opt.fmin_tnc(func = cost,x0 = theta,fprime = gradient,args = (X,y))
result
#查看结果
cost(result[0],X,y)

plotting_x1 = np.linspace(30,100,100)
plotting_h1 = (-result[0,0] - result[0] [1] * plotting_x1) / result[0][2]
fig,ax = plt.subplots(figsize = (12,8))
ax.plot(plotting_x1,plotting_h1,‘y’,label = ‘Prediction’)
ax.scatter(positive[‘Exam 1’],positive[‘Exam 2’],s =50,c=‘b’,marker = ‘o’,label = ‘Admitted’)
ax.scatter(negative[‘Exam 1’],negative[‘Exam 2’],s =50,c = ‘r’,marker = ‘x’,label = ‘Not Admitted’)
ax.legend()
ax.set_xlabel(‘Exam 1 Score’)
ax.set_ylabel(‘Exam 2 Score’)
plt.show()

def hfunc1(theta,X):
return sigmoid(np.dot(theta.T,X))
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 = [1 if ((a1 and b1) or (a==0) and (b == 0)) else 0 for (a,b) in zip(predictions,y)]
accuracy = (sum(map(int,correct)) % len(correct)))
preint(‘accuracy = {0}%’.format(accuracy))

发布了31 篇原创文章 · 获赞 0 · 访问量 699

猜你喜欢

转载自blog.csdn.net/ballzy/article/details/104362486