如何使用预测变量和响应变量进行逻辑回归?

时间:2019-02-13 21:16:08

标签: r optimization logistic-regression

运行我的逻辑回归,我要绘制我创建的数据,然后绘制由模型系数描述的线。

library("dplyr")  # filter and reformat data frames
library("tidyr")  # make data tidy

# Create an empty vector will 200 variables
df_vector <- c(1:200)

# For the first 100 variables, 
for (i in 1: 100) {
    # Set the normal distribution with mean -5 and sd 5
    v1 <- rnorm(100, -5,5)

# For the second 100
for (i in 101:200) 
    # Set the normal distribution with mean 4 and sd 8
    v2 <- rnorm(100,4,8)
}

# Input the vales of v1 and v2 into a data frame 
df_vector <- data.frame(v1,v2)

# Combine the 2 columns of data into one single vector with a length of 200
Uni_dataframe <- data.frame(d = unlist(df_vector, use.names = FALSE))


# Create another vector with first half of the values = 0 and second half = 1
resp_vector <- c(1:200)

# For the first 100 variables
for (i in 1:100) {

    # Set the first 100 variables = 0
    resp1 <-(rep(0, times = 100 ))

# For the second 100 variables   
for (i in 101:200)
    # Set the second 100 variables = 1
    resp2 <- (rep(1, times = 100 ))
}

# Input both resp1 and resp 2 into a data frame
resp_vector <- data.frame(resp1, resp2)

# Combine the 2 columns of data into a single vector with length 100
Uni_resp_vector <- data.frame (d = unlist(resp_vector))

我在上面创建的2个向量是Uni_dataframe和Uni_resp_vector。 然后,我受命根据以下代码和功能运行逻辑回归。

log.likelihood(params, x, y)

logistic.fit(xtrain, ytrain)

logistic.predict(xtest, fit)

log.likelihood = function(params, x, y) {

    x = cbind(rep(1, nrow(x)), x)       
    Bx.sum = params %*% t(x) 
    t1 = sum((1-y)*Bx.sum)
    t2 = sum(log(1+sapply(-Bx.sum, exp, simplify=T))) 

    likelihood = -(t1+t2)
    return(-likelihood) 
}



model <- optim(params = Uni_dataframe, fn = Uni_resp_vector, log.likelihood, data, method='BFGS')

但是,我不确定要在optim()中放入什么参数,并且我从optim中得到了错误:无法将类型'closure'强制转换为类型'double'的向量。 “数据”参数有问题吗?

任何帮助我们开发出逻辑回归模型的人,将不胜感激。关于应如何绘制的任何建议?谢谢!

0 个答案:

没有答案