我一直在使用 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()
```