我一直在使用 ipython (Jupyter) notebook 来完成我的 R 和 Python 任务。最近,我探索了 R Notebook,发现了我希望在 R Notebook 中实现的 Jupyter Notebook 中的功能。所以,我想切换到 R Notebook。然而,当在 R Notebook 中使用 Python 时,我无法缓存 python 结果并在另一个 block 中使用一个 block 的输出。此外,我无法生成内联的 python 图。它在新窗口中给我绘图,而不是在笔记本本身中。为了仅提供一些可重现的代码,如果将下面的代码放在一个 block 中,则它可以正常工作并提供输出,但如果将其分成几个 block ,则无法在另一个 block 中调用一个 block 的输出。该图也会在新窗口中弹出。
```{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()
```
请您参考如下方法:
我无法缓存 python 结果并在另一个 block 中使用一个 block 的输出
- 如果语言引擎不是 R,这似乎是不可能的
- 参见 knitr - Python engine cache option not working
我无法缓存 python 结果并在另一个 block 中使用一个 block 的输出,而且我无法生成内联 python 图
- 您可以试用 knitron 并分享它是否有效吗?
- knitron:knitr + IPython + matplotlib:https://github.com/fhirschmann/knitron
