r - R 中的手动感知器示例 - 结果可以接受吗?

标签 r machine-learning

我正在尝试获得一种用于分类的感知器算法,但我认为缺少了一些东西。这是通过逻辑回归实现的决策边界:

enter image description here

在测试 1 和 2 中表现更好后,红点进入了大学。

This is the data ,这是 R 中逻辑回归的代码:

dat = read.csv("perceptron.txt", header=F)
colnames(dat) = c("test1","test2","y")
plot(test2 ~ test1, col = as.factor(y), pch = 20, data=dat)
fit = glm(y ~ test1 + test2, family = "binomial", data = dat)
coefs = coef(fit)
(x = c(min(dat[,1])-2,  max(dat[,1])+2))
(y = c((-1/coefs[3]) * (coefs[2] * x + coefs[1])))
lines(x, y)

感知器“手动”实现的代码如下:

# DATA PRE-PROCESSING:
dat = read.csv("perceptron.txt", header=F)
dat[,1:2] = apply(dat[,1:2], MARGIN = 2, FUN = function(x) scale(x)) # scaling the data
data = data.frame(rep(1,nrow(dat)), dat) # introducing the "bias" column
colnames(data) = c("bias","test1","test2","y")
data$y[data$y==0] = -1 # Turning 0/1 dependent variable into -1/1.
data = as.matrix(data) # Turning data.frame into matrix to avoid mmult problems.

# PERCEPTRON:
set.seed(62416)
no.iter = 1000                           # Number of loops
theta = rnorm(ncol(data) - 1)            # Starting a random vector of coefficients.
theta = theta/sqrt(sum(theta^2))         # Normalizing the vector.
h = theta %*% t(data[,1:3])              # Performing the first f(theta^T X)

for (i in 1:no.iter){                    # We will recalculate 1,000 times
  for (j in 1:nrow(data)){               # Each time we go through each example.
      if(h[j] * data[j, 4] < 0){         # If the hypothesis disagrees with the sign of y,
      theta = theta + (sign(data[j,4]) * data[j, 1:3]) # We + or - the example from theta.
      }
      else
      theta = theta                      # Else we let it be.
  }
  h = theta %*% t(data[,1:3])            # Calculating h() after iteration.
}
theta                                    # Final coefficients
mean(sign(h) == data[,4])                # Accuracy

这样,我得到以下系数:

     bias     test1     test2 
 9.131054 19.095881 20.736352 

准确度为 88%,与使用 glm() 逻辑回归函数计算的结果一致:mean(sign(predict(fit))= =data[,4]) of 89% - 从逻辑上讲,无法对所有点进行线性分类,从上图中可以明显看出。事实上,仅迭代 10 次并绘制准确率,仅 1 迭代后即可达到 ~90%:

enter image description here

与逻辑回归的训练分类性能相符,代码很可能在概念上没有错误。

问题:获得与逻辑回归如此不同的系数是否可以:

(Intercept)       test1       test2 
   1.718449    4.012903    3.743903 

最佳答案

这实际上更像是一个 CrossValidated 问题,而不是 StackOverflow 问题,但我会继续回答。

是的,得到非常不同的系数是正常的,因为您无法直接比较这两种技术之间的系数大小。

对于 logit(逻辑)模型,您使用的是二项式分布和基于 sigmoid 成本函数的 logit-link。这些系数仅在这种情况下才有意义。 Logit 中还有一个截距项。

对于感知器模型来说,这一切都不成立。因此,系数的解释完全不同。

现在,这并没有说明哪种模型更好。您的问题中没有可比的性能指标可以让我们确定这一点。要确定您应该进行交叉验证或至少使用保留样本。

关于r - R 中的手动感知器示例 - 结果可以接受吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38023678/

相关文章:

r - R中按组划分的spearman相关性

r - 将ggplot2颜色条刻度线更改为黑色

r - 查找多个组的最后一行

python - TextBlob 如何计算情感极性?如何使用机器学习分类器计算情绪值?

python-3.x - 教师力量训练 PyTorch

r - 分配损失时如何解释 rpart(方法 ="class")的 xerror

machine-learning - 正确解释余弦角距离相似度和欧氏距离相似度

r - 按变量对轴文本进行颜色显示

python - 机器学习中回归的局限性?

r - 获取一行中的第一个非 NA 元素