【发布时间】:2018-05-30 12:39:25
【问题描述】:
我正在尝试使用 R 中用于“iris”数据集的“neuralnet”包来实现一个简单的多层前馈神经网络。
我使用的代码如下-
library(neuralnet)
data(iris)
D <- data.frame(iris, stringsAsFactors=TRUE)
# create formula-
f <- as.formula(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width)
# convert qualitative variables to dummy (binary) variables-
m <- model.matrix(f, data = D)
# create neural network-
iris_nn <- neuralnet(f, data = m, hidden = 4, learningrate = 0.3)
我现在有两个问题-
1.) 如何使用“隐藏”参数?根据手册页,它的说法-
hidden:一个整数向量,指定每层中隐藏神经元(顶点)的数量
我应该如何提供整数向量?假设我想在每层有 1 个隐藏层,每层有 4 个神经元/感知器,或者如果我想在每层有 3 个隐藏层,每层有 5 个神经元。
2.) 最后一行代码给了我错误-
eval 中的错误(predvars、data、env):找不到对象“物种”
如果我删除“隐藏”参数,这个错误仍然存在。
我在这里做错了什么?
编辑:添加行后-
m <- model.matrix(f, data = D)
矩阵“m”不再包含我试图预测的“物种”变量/属性。
输出
str(D)
str(D) 'data.frame': 150 obs。 5 个变量:$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... $ 萼片宽度: num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ... $ 花瓣长度: num 1.4 1.4 1.3 1.5 1.4 1.4 1.4 .1.5 1.4 1.4 ..5 1 . $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 . ..
我已经成功地用“nnet”对此进行了编码。发布我的代码以供参考-
data(iris)
library(nnet)
# create formula-
f <- as.formula(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width)
# create a NN with hidden layer having 4 neurons/node and
# maximum number of iterations = 3
iris_nn <- nnet(f, data = iris, size = 4, maxit = 3)
# create a test data-
new_obs <- data.frame(Sepal.Length = 5.5, Sepal.Width = 3.1, Petal.Length = 1.4, Petal.Width = 0.4)
# make prediction-
predict(iris_nn, new_obs) # gives percentage of which class it may belong
predict(iris_nn, new_obs, type = "class") # gives the class instead of percentages of which 'class' this data type may belong to
# create a 'confusion matrix' to measure accuracy of model-
# rows are actual values and columns are predicted values-
# table(iris$Species, predict(iris_nn, iris[, 1:4], type = "class"))
cat("\n\nConfusion Matrix for # of iters = 3\n")
print(table(iris$Species, predict(iris_nn, iris[, 1:4], type = "class")))
cat("\n\n")
rm(iris_nn)
# setting 'maxit' to 1000, makes the model coverge-
iris_nn <- nnet(f, data = iris, size = 4, maxit = 1000)
# create a new confusion matrix to check model accuracy again-
cat("\n\nConfusion Matrix for # of iters = 1000\n")
print(table(iris$Species, predict(iris_nn, iris[, 1:4], type = "class")))
# table(iris$Species, predict(iris_nn, iris[, 1:4], type = "class"))
# to plot 'iris_nn' trained NN-
# library("NeuralNetTools")
# plotnet(iris_nn)
谢谢!!
【问题讨论】:
-
@SamFlynn 我已经编辑了我的帖子以包含矩阵“m”。但是现在我试图预测“物种”的变量已经消失了!因此,最后一行代码给出了找不到“物种”的错误!有什么想法吗?
-
我也试过了,一直搞错。在问题中添加
str(d)的输出。我所做的是将所有阶乘列手动更改为虚拟变量并且它起作用了。 -
属性规范化会有帮助吗?
标签: r neural-network