正则化逻辑回归
题目:
你是工厂主管,你有一些芯片在两次测试的结果,你需要决定它们是否合格,你手里有之前的结果,现在需要构建一个逻辑回归模型进行预测
代码:
1. 读取数据
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
path = 'ex2data2.txt'
df = pd.read_csv(path, header=None, names=['Test1', 'Test2', 'Accepted'])
df.head()

df.describe()

2. 绘制样本图像
positive = df[df['Accepted'].isin([1])]
negative = df[df['Accepted'].isin([0])]
fig, ax = plt.subplots(figsize=(12, 8))
ax.scatter(positive['Test1'], positive['Test2'], s=50, c='b', marker='o', label='Accepted')
ax.scatter(negative['Test1'], negative['Test2'], s=50, c='r', marker='x', label='Rejected')
ax.legend()
ax.set_xlabel('Test1 Score')
ax.set_ylabel('Test2 Score')
plt.show()

3. 运用特征映射
特征映射是卷积神经网络CNN里的知识,我暂时跳过了
简单了解就是:
特征映射的目的是从原始输入数据中提取出有用的信息,并将其转化为一种适合后续处理(如分类、回归等)的形式
def feature_mapping(x, y, power, as_ndarray=False):
data = {'f{0}{1}'.format(i-p, p): np.power(x, i-p) * np.power(y, p)
for i in range(0, power+1)
for p in range(0, i+1)
}
if as_ndarray:
return pd.DataFrame(data).values
else:
return pd.DataFrame(data)
x1 = df.Test1.values
x2 = df.Test2.values
Y = df.Accepted
data = feature_mapping(x1, x2, power=6)
# data = data.sort_index(axis=1, ascending=True)
data.head()
data.describe()

4. 使用代价函数

与上图即上次作业不同的是多了一个正则项
就是对于θ平方求和再乘了一个λ权重

4.1 调用特征映射
theta = np.zeros(data.shape[1])
X = feature_mapping(x1, x2, power=6, as_ndarray=True)
X.shape, Y.shape, theta.shape
((118, 28), (118,), (28,))
4.2 调用sigmoid函数,将模型的输出转换为概率值


1270

被折叠的 条评论
为什么被折叠?



