分类: R语言

  • torch的模块

    library(torch)
    # 线性层,输入特征5,输出特征16,常用于神经网络的第一层
    l <- nn_linear(in_features = 5, out_features = 16)
    l
    l$weight
    l$bias
    # 生成一个尺寸为 [50, 5] 的随机张量 x,
    # 其中包含50个样本,每个样本有5个特征。
    # 数据服从标准正态分布。
    x <- torch_randn(50, 5)
    # x 传递给线性层 l,得到输出 output
    output <- l(x)
    # 获取并返回输出张量的尺寸,即 [50, 16]
    output$size()
    # 用于跟踪生成 output 张量的计算图中的梯度函数。
    output$grad_fn
    
    # 定义损失函数为output的均值
    loss <- output$mean()
    # loss的反向传播
    loss$backward()
    # 获取线性层 l 的权重参数的梯度。
    # 这些梯度用于更新权重,
    # 以最小化损失函数。
    l$weight$grad
    
    # 多层感知机,模型是通过 nn_sequential 组合多个神经网络模块构建
    mlp <- nn_sequential(
      nn_linear(10, 32),
      nn_relu(),
      nn_linear(32, 64),
      nn_relu(),
      nn_linear(64, 1)
    )
    
    # 调用该模块
    mlp(torch_randn(5, 10))
    
  • 利用自动微分来计算梯度并优化函数

    # 加载torch包
    library(torch)
    
    # 设置常量a和b
    a <- 1
    b <- 5
    
    # rosenbrock函数
    rosenbrock <- function(x) {
      x1 <- x[1]
      x2 <- x[2]
      (a - x1)^2 + b * (x2 - x1^2)^2
    }
    
    # 迭代数2
    num_iterations <- 2
    
    # x被初始化为一个值为-1和1的张量k
    # 并且requires_grad = TRUE表示需要为该张量计算梯度。
    x <- torch_tensor(c(-1, 1), requires_grad = TRUE)
    
    # optimizer使用optim_lbfgs设置
    # 这是L-BFGS优化算法的实现
    # line_search_fn参数设置为"strong_wolfe",这是一种线搜索方法
    optimizer <- optim_lbfgs(x, line_search_fn = "strong_wolfe")
    
    # calc_loss函数用于清零现有的梯度,计算Rosenbrock函数的值
    # 显示该值,然后调用backward()来计算梯度。
    calc_loss <- function() {
      optimizer$zero_grad()
    
      value <- rosenbrock(x)
      cat("Value is: ", as.numeric(value), "\n")
    
      value$backward()
      value
    }
    
    # 循环运行指定的迭代次数(num_iterations)
    # 在每次迭代中,打印迭代次数并调用optimizer$step(calc_loss)
    # 这会使用L-BFGS算法执行一次优化步骤。
    for (i in 1:num_iterations) {
      cat("\nIteration: ", i, "\n")
      optimizer$step(calc_loss)
    }
    
    
  • 梯度下降法优化 Rosenbrock 函数

    a <- 1
    b <- 5
    
    rosenbrock <- function(x) {
      x1 <- x[1]
      x2 <- x[2]
      (a - x1)^2 + b * (x2 - x1^2)^2
    }
    
    num_iterations <- 1000   # 迭代次数为1000
    
    lr <- 0.01   # 学习率(步长)0.01
    
    # 初始化一个张量,初始值为 (-1, 1),并允许计算梯度。
    x <- torch_tensor(c(-1, 1), requires_grad = TRUE)
    
    for (i in 1:num_iterations) {
      # 每100次迭代,输出当前的迭代次数。
      if (i %% 100 == 0) cat("Iteration: ", i, "\n")
    
      value <- rosenbrock(x)   # 计算当前 x 处的 Rosenbrock 函数值,并在每100次迭代时输出该值。
      if (i %% 100 == 0) {
        cat("Value is: ", as.numeric(value), "\n")
      }
      # 计算函数关于 x 的梯度。
      value$backward()
      if (i %% 100 == 0) {
        cat("Gradient is: ", as.matrix(x$grad), "\n")
      }
      # 使用 with_no_grad 块更新 x 的值:x$sub_(lr * x$grad),即沿梯度的反方向更新 x。
      with_no_grad({
        x$sub_(lr * x$grad)
        x$grad$zero_()   # x清零,用于下次迭代
      })
    }
    x
    
    
    展开/折叠结果
    Iteration:  100 
    Value is:  3.176291e-05
    Gradient is:  -0.002168588 -0.004486442
    Iteration:  200 
    Value is:  1.453024e-05
    Gradient is:  -0.001461957 -0.003031492 
    Iteration:  300 
    Value is:  6.658438e-06
    Gradient is:  -0.0009882869 -0.0020504
    Iteration:  400 
    Value is:  3.055203e-06
    Gradient is:  -0.0006686524 -0.001388192
    Iteration:  500 
    Value is:  1.40284e-06
    Gradient is:  -0.0004510169 -0.0009411573
    Iteration:  600 
    Value is:  6.444936e-07
    Gradient is:  -0.0003067786 -0.0006371737
    Iteration:  700 
    Value is:  2.964038e-07
    Gradient is:  -0.000207768 -0.0004321337
    Iteration:  800 
    Value is:  1.363231e-07
    Gradient is:  -0.0001404032 -0.0002932549
    Iteration:  900 
    Value is:  6.276184e-08
    Gradient is:  -9.749157e-05 -0.0001978874
    Iteration:  1000 
    Value is:  2.8892e-08
    Gradient is:  -6.644445e-05 -0.0001341105
    > x
    torch_tensor
     0.9998
     0.9997
    [ CPUFloatType{2} ][ requires_grad = TRUE ]
    
  • 单因素方差分析与多因素方差分析

    # 创建数据框  
    data <- data.frame(  
      score = c(85, 88, 90, 78, 82, 85, 92, 95, 89),  
      method = factor(c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'))  
    )  
    
    # 执行单因素方差分析  
    result <- aov(score ~ method, data = data)  
    
    # 查看结果  
    summary(result)
    
    # 创建数据框  
    data <- data.frame(  
      score = c(85, 88, 90, 78, 82, 85, 92, 95, 89, 80, 83, 87),  
      method = factor(c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'A', 'B', 'C')),  
      time = factor(c('short', 'short', 'short', 'short', 'short', 'short', 'long', 'long', 'long', 'long', 'long', 'long'))  
    )  
    
    # 执行多因素方差分析  
    result <- aov(score ~ method * time, data = data)  
    
    # 查看结果  
    summary(result)
    

    在这两个示例中,单因素方差分析用于比较单一因素的影响,而多因素方差分析用于研究多个因素及其交互作用对因变量的影响。

  • 检查R语言的torch是否支持GPU

    library(torch)  
    if (cuda_is_available()) {  
      cat("CUDA is available\n")  
    } else {  
      cat("CUDA is not available\n")  
    }  
    

    或者

    torch::cuda_is_available()
    

  • 损失函数

    损失函数是一个用于衡量模型预测结果与实际目标之间差异的函数。在神经网络中,损失函数的作用是指导模型的训练过程,通过最小化损失函数的值来优化模型的参数。

    在回归任务中,常用的损失函数是均方误差(Mean Squared Error, MSE),它计算预测值与真实值之间差异的平方平均值。选择合适的损失函数取决于具体的任务需求。例如,除了均方误差外,有时也可能使用平均绝对误差(Mean Absolute Error)。

    y <- torch_randn(5)  
    y_pred <- y + 0.01  
    loss <- (y_pred - y)$pow(2)$mean()
    

    这个代码片段计算了预测值y_pred与真实值y之间的均方误差,并将其存储在loss变量中。损失函数的值越小,表示模型的预测越接近真实值。通过不断调整模型的参数以最小化损失函数的值,模型的性能可以得到提升。

  • R语言的单因素方差分析

    # This code installs and loads the "multcomp" package in R.
    #? install.packages("multcomp")
    # Load the "multcomp" package in R.
    library(multcomp)
    # Attach the "cholesterol" dataset to the R environment.
    attach(cholesterol)
    # Create a table of the cholesterol levels by treatment group.
    table(trt)
    # Create a table of the mean cholesterol levels by treatment group.
    aggregate(response,list(trt),FUN=mean)
    # Create a table of the standard deviation of cholesterol levels by treatment group.
    aggregate(response, by=list(trt), FUN=sd)
    # Create a one-way ANOVA model of the cholesterol levels by treatment group.
    fit <- aov(response ~ trt)
    # Print the summary of the ANOVA model.
    summary(fit)
    # Load the "gplots" package in R.
    library(gplots)
    # Create a boxplot of the cholesterol levels by treatment group.
    plotmeans(response ~ trt, xlab="Treatment", ylab="Response", main="Mean plot\nwith 95% CI")
    # detach the "cholesterol" dataset from the R environment.
    detach(cholesterol)
    
        展开/折叠结果     
    > # This code installs and loads the "multcomp" package in R.
    > #? install.packages("multcomp")
    > # Load the "multcomp" package in R.
    > library(multcomp)
    载入需要的程序包:mvtnorm
    载入需要的程序包:survival
    载入需要的程序包:TH.data
    载入需要的程序包:MASS
    
    载入程序包:'TH.data'
    
    The following object is masked from 'package:MASS':
    
        geyser
    
    > # Attach the "cholesterol" dataset to the R environment.
    > attach(cholesterol)
    > # Create a table of the cholesterol levels by treatment group.
    > table(trt)
    trt
     1time 2times 4times  drugD  drugE
        10     10     10     10     10
    > # Create a table of the mean cholesterol levels by treatment group.
    > aggregate(response,list(trt),FUN=mean)
      Group.1        x
    1   1time  5.78197
    2  2times  9.22497
    3  4times 12.37478
    4   drugD 15.36117
    5   drugE 20.94752
    > # Create a table of the standard deviation of cholesterol levels by treatmen$
    > aggregate(response, by=list(trt), FUN=sd)
      Group.1        x
    1   1time 2.878113
    2  2times 3.483054
    3  4times 2.923119
    4   drugD 3.454636
    5   drugE 3.345003
    > # Create a one-way ANOVA model of the cholesterol levels by treatment group.
    > fit <- aov(response ~ trt)
    > # Print the summary of the ANOVA model.
    > summary(fit)
                Df Sum Sq Mean Sq F value   Pr(>F)
    trt          4 1351.4   337.8   32.43 9.82e-13 ***
    Residuals   45  468.8    10.4
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    > # Load the "gplots" package in R.
    > library(gplots)
    
    载入程序包:'gplots'
    
    The following object is masked from 'package:stats':
    
        lowess
    
    > # Create a boxplot of the cholesterol levels by treatment group.
    > plotmeans(response ~ trt, xlab="Treatment", ylab="Response", main="Mean plot$
    > # detach the "cholesterol" dataset from the R environment.
    > detach(cholesterol)
    

  • R语言lm()的多项式回归

    fit2 <- lm(weight ~ hight + I(height^2), data = women)
    summary(fit2)
    
    展开/折叠结果
    Call:
    lm(formula = weight ~ height + I(height^2), data = women)
    
    Residuals:
         Min       1Q   Median       3Q      Max 
    -0.50941 -0.29611 -0.00941  0.28615  0.59706 
    
    Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
    (Intercept) 261.87818   25.19677  10.393 2.36e-07 ***
    height       -7.34832    0.77769  -9.449 6.58e-07 ***
    I(height^2)   0.08306    0.00598  13.891 9.32e-09 ***
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    
    Residual standard error: 0.3841 on 12 degrees of freedom
    Multiple R-squared:  0.9995,	Adjusted R-squared:  0.9994 
    F-statistic: 1.139e+04 on 2 and 12 DF,  p-value: < 2.2e-16
    

    $\hat{Weight}=261.88-7.35 \times Height+0.083\times Height^2$

    模型的方差解释了99.95%的方差。所有项均小于0.001,达到极显著水平。I()的作用是把一个表达式当作一个独立的项。

  • R语言的lm()函数

    lm()是R语言中线性建模的函数。lm()函数适合线性模型并用于执行回归分析。

    fit <- lm(weight~height,data=women)
    fit
    
        展开/折叠结果     
    Call:
    lm(formula = weight ~ height, data = women)
    Coefficients:
    (Intercept) height -87.52 3.45
    summary(fit)
    
        展开/折叠结果     
    Call:
    lm(formula = weight ~ height, data = women)
    
    Residuals:
        Min      1Q  Median      3Q     Max 
    -1.7333 -1.1333 -0.3833  0.7417  3.1167 
    
    Coefficients:
                 Estimate Std. Error t value Pr(>|t|)    
    (Intercept) -87.51667    5.93694  -14.74 1.71e-09 ***
    height        3.45000    0.09114   37.85 1.09e-14 ***
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    
    Residual standard error: 1.525 on 13 degrees of freedom
    Multiple R-squared:  0.991,     Adjusted R-squared:  0.9903 
    F-statistic:  1433 on 1 and 13 DF,  p-value: 1.091e-14

    $\hat{Weight}=-87.52+3.45\times Height$

    该模型解释了99.1%的方差,残差标准误1.525可理解为身高预测体重的模型的平均误差是1.525。

  • 用R语言实现文字转拼音

    需要安装一个pinyin包。

    # 安装并加载pinyin包  
    if (!requireNamespace("pinyin", quietly = TRUE)) {  
      install.packages("pinyin")  
    }  
    library(pinyin)  
    
    # 示例中文文本  
    chinese_text <- c("赵云","马超")  
    
    # 转换为拼音  
    pinyin_result <- py(chinese_text,sep = " ")  
    
    # 打印结果  
    print(pinyin_result)
    
    展开/折叠结果 > print(pinyin_result)
    赵云 马超
    "zhào yún" "mǎ chāo"