import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 导入并处理数据
path = "E:\\study_data\\data_sets\\ex2data2.txt"
data_init = pd.read_csv(path, header=None, names=['Test 1', 'Test 2', 'Accepted'])
# 可视化训练集
positive2 = data_init[data_init['Accepted'].isin([1])]
negative2 = data_init[data_init['Accepted'].isin([0])]
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(positive2['Test 1'], positive2['Test 2'], s=50, c='b', marker='o', label='Accepted')
ax.scatter(negative2['Test 1'], negative2['Test 2'], s=50, c='r', marker='x', label='Not Accepted')
ax.legend()
ax.set_xlabel('Test 1 Score')
ax.set_ylabel('Test 2 Score')
plt.show()
degree = 6
data2 = data_init
x1 = data2['Test 1']
x2 = data2['Test 2']
data2.insert(3, 'Ones', 1)
# 在第三列插入新数据值为1
for i in range(1, degree + 1):
# 上面这一层for循环表示多项式的次数,当多项式为一次,两次,三次...的时候下面这个for循环列出所有能组合成这个次数的情况。
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)
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 实现正则化代价函数
def costReg(theta, X, y, LearningRate):
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
# first 和second使用的是theta代入整体的样本,来计算差值
first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
# reg是计算当前采用的theta的平方,用来惩罚模型
reg = (LearningRate / (2 * len(X))) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2))
# theta[:, 1:theta.shape[1]]表示取除了第一列的所有列,因为第一列是截距列不参与不参与模型的训练
return np.sum(first - second) / len(X) + reg
# 实现正则化的梯度下降函数,利用优化函数(所以不用更新theta,由优化函数来进行更新)
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)) + ((learingRate / 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进行匹配
# 将两个数据转化为numpy数组以便进行矩阵运算
X2 = np.array(X2.values)
y2 = np.array(y2.values)
learningRate = 1
print(costReg(theta2, X2, y2, learningRate))
# 用工具库函数进行求解参数
import scipy.optimize as opt
result = opt.fmin_tnc(func=costReg, x0=theta2, fprime=gradientReg, args=(X2, y2, learningRate))
print(result)
print(np.shape(X2))
print(np.shape(y2))
print(np.shape(theta2))
# 定义预测函数
def predict(theta, X):
probability = sigmoid(X * theta.T)
# 因为传入的X可能是个多维矩阵,所以probability有很多结果
return [1 if x >= 0.5 else 0 for x in probability]
# 统计预测的正确率
theta_min = np.matrix(result[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)]
# zip将实际值和预测值放一起,如果实际值与预测值相同返回1,否则返回0
accuracy = (sum(map(int, correct)) / len(correct))
# map函数是用来将correct数组中每个元素都转化为整型,求和后是正确的样本数
print(f"{accuracy:.2f}")
# 生成一个函数,该函数就是h(x),也就是预测函数
def hfunc(theta, x1, x2):
temp = theta[0][0]
place = 0
for i in range(1, degree + 1):
for j in range(0, i + 1):
temp += np.power(x1, i - j) * np.power(x2, j) * theta[0][place + 1]
# temp是一个函数,theta[0][place+1]表示的是多项式的系数
place += 1
return temp
# 边界曲线(决策界限),绘制决策边界就是让sigmoid函数取值为0.5
# 也就是让theta.T*X的结果是0,也就是预测函数h(x)的值为0
def find_decision_boundray(theta):
t1 = np.linspace(-1, 1.5, 1000)
# 生成cong-1到1.5的1000个等差数列
t2 = np.linspace(-1, 1.5, 1000)
cordinates = [(x, y) for x in t1 for y in t2]
# 使用列表推导式,生成一个包含所有x,y的元组的列表,可用于图像绘制和数值计算
x_cord, y_cord = zip(*cordinates)
# 将元组的两个元素分开单独生成两个元组
h_val = pd.DataFrame({'x1': x_cord, 'x2': y_cord})
# 生成一个Dateframe对象,包含两个列x1,x2,dateframe对象可以用来存储和处理数据,
# 在本次使用中是用来绘制一个二维图像,x1,x2对应两个自变量
h_val['hval'] = hfunc(theta, h_val['x1'], h_val['x2'])
# 生成一个新列'hval',存储的是二维函数的高度,h(x)的值,决策曲线是让h(x)等于0,这里采用近似的思想
decision = h_val[np.abs(h_val['hval']) < 2 * 10 ** -3]
# np.abs是用来计算绝对值,筛选出符合条件的行,决策去曲线包含的点
return decision.x1, decision.x2
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(positive2['Test 1'], positive2['Test 2'], s=50, c='b', marker='o', label='Accepted')
ax.scatter(negative2['Test 1'], negative2['Test 2'], s=50, c='r', marker='x', label='Accepted')
ax.set_xlabel('Test 1 Score')
ax.set_ylabel('Test 2 Score')
x, y = find_decision_boundray(result)
plt.scatter(x, y, c='y', s=10, label='Prediction')
ax.legend()
plt.show()
边界曲线:h(x) = sigmoid(theta.T*X) = 1/2
也就是 theta.T*X = 0