3

我一直在使用 ipython (Jupyter) notebook 来完成我的 R 和 Python 任务。最近,我探索了 R Notebook,发现了我希望它们在 Jupyter Notebook 中实现的那种功能。所以,我想切换到 R Notebook。但是,当在 R Notebook 中使用 Python 时,我无法缓存 Python 结果并在另一个块中使用一个块的输出。此外,我无法内联生成 python 图。它让我在一个新窗口中绘制图表,而不是在笔记本本身中。为了提供一些可重现的代码,下面的代码可以正常工作,如果你把它放在一个块中,它会给出一个输出,但是如果你把它分成几个块,你不能从另一个块中调用一个块的输出。该图还会在新窗口中弹出。

```{python}
 # Import necessary modules
 from sklearn import datasets
 import matplotlib.pyplot as plt
 from sklearn.model_selection import train_test_split
 from sklearn.neighbors import KNeighborsClassifier
 import numpy as np

 # Load the digits dataset: digits
 digits = datasets.load_digits()


 # Create feature and target arrays
 X = digits.data
 y = digits.target

# Split into training and test set
 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2,    random_state = 42, stratify = y)

# Setup arrays to store train and test accuracies
 neighbors = np.arange(1, 9)
 train_accuracy = np.empty(len(neighbors))
 test_accuracy = np.empty(len(neighbors))

  # Loop over different values of k
 for i, k in enumerate(neighbors):
  # Setup a k-NN Classifier with k neighbors: knn
    knn = KNeighborsClassifier(n_neighbors = k)

    # Fit the classifier to the training data
    knn.fit(X_train,y_train)

    #Compute accuracy on the training set
    train_accuracy[i] = knn.score(X_train, y_train)

    #Compute accuracy on the testing set
     test_accuracy[i] = knn.score(X_test, y_test)

  # Generate plot
 plt.title('k-NN: Varying Number of Neighbors')
 plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')
 plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')
 plt.legend()
 plt.xlabel('Number of Neighbors')
 plt.ylabel('Accuracy')
 plt.show()
 ```

下图显示在新窗口中。不在笔记本中内联。 在此处输入图像描述

4

3 回答 3

1
  • 我无法缓存 python 结果并在另一块中使用一个块的输出

  • 我无法缓存 python 结果并在另一块中使用一个块的输出,我无法内联生成 python 图

于 2017-03-27T10:41:41.430 回答
0

我认为处理这个问题的正确方法是使用 rPython。使用这个库,您可以执行 python 代码并将结果作为 R 变量获取。检查此链接以查看示例:

https://github.com/rajshah4/tensorflow_shiny/blob/master/server.R

于 2017-03-29T22:12:46.080 回答
0

可能值得一看 pweave python 包。

于 2017-04-04T10:39:29.533 回答