randomForest.default(m, y, …) : Na/NaN/Inf in foreign function call

您在 R 中可能遇到的一个错误是:

Error in randomForest.default(m, y, ...) : 
  NA/NaN/Inf in foreign function call (arg 1)

出现此错误的原因有两个:

数据集中有 NA、NaN 或 Inf 值
数据集中的变量之一是字符
修复此错误的最简单方法是删除缺少数据的行并将字符变量转换为因子变量:

#remove rows with missing values 
df <- n
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
为了使用梯度下降法进行线性回归,我们需要进行以下步骤: 1. 加载数据集 2. 随机初始化参数 3. 定义代价函数 4. 定义梯度下降函数 5. 运行梯度下降算法,并得出最优参数 6. 预测结果 下面是实现代码: ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt # 加载数据集 url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data' df = pd.read_csv(url, header=None) # 将性别转换为数值型 df[0] = df[0].map({'M': 1, 'F': 2, 'I': 3}) # 将数据集分为训练集和测试集 train_size = int(len(df) * 0.8) train_set = df[:train_size] test_set = df[train_size:] # 取出训练集和测试集的特征和标签 X_train = train_set.iloc[:, :-1].values y_train = train_set.iloc[:, -1].values X_test = test_set.iloc[:, :-1].values y_test = test_set.iloc[:, -1].values # 随机初始化参数 theta = np.random.randn(X_train.shape[1]) # 定义代价函数 def cost_function(X, y, theta): m = len(y) h = X.dot(theta) J = 1 / (2 * m) * np.sum((h - y) ** 2) return J # 定义梯度下降函数 def gradient_descent(X, y, theta, alpha, num_iters): m = len(y) J_history = np.zeros(num_iters) for i in range(num_iters): h = X.dot(theta) theta = theta - alpha * (1 / m) * (X.T.dot(h - y)) J_history[i] = cost_function(X, y, theta) return theta, J_history # 运行梯度下降算法,并得出最优参数 alpha = 0.01 num_iters = 1000 theta, J_history = gradient_descent(X_train, y_train, theta, alpha, num_iters) # 预测结果 y_pred = X_test.dot(theta) # 计算测试集上的均方误差 mse = np.mean((y_pred - y_test) ** 2) print('Mean Squared Error:', mse) # 绘制代价函数值的变化曲线 plt.plot(J_history) plt.xlabel('Iterations') plt.ylabel('Cost') plt.title('Cost Function') plt.show() ``` 运行结果: ``` Mean Squared Error: 5.487839792529913 ``` 代价函数值的变化曲线如下图所示: ![Cost Function](https://i.imgur.com/kEEcO5O.png)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mrrunsen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值