Open asifrpa opened 4 years ago
Have you defined or imported the function anywhere in your code?
def train_predict(clf, X_train, y_train, X_test, y_test):
Defined like this....later in the code
Not imported anywhere else in the code
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_predict
X_train_cv, X_test_cv, y_train_cv, y_test_cv = train_test_split(X_train, y_train, test_size = 0.3, random_state=100)
neighbors = []
accuracy = []
for n in range(3,10):
knn = KNeighborsClassifier(n_neighbors=n)
print("Number of neighbors is: {}".format(n))
train_predict(knn, X_train_cv, y_train_cv, X_test_cv, y_testcv)
clf = knn.fit(X_train, y_train)
ypred = clf.predict(X_test)
neighbors.append(n)
accuracy.append( str(("%.2f" %(accuracy_score(y_test,y_pred)* 100) )))
accuracy.sort()
neighbors.sort()
plt.bar( list(range(3, 10)), accuracy, tick_label=neighbors, width=0.8, color="rgbymc")
plt.title("Optimizing Neighbours for KNN")
plt.xlabel("Neighbours")
plt.ylabel("accuracy")
plt.ylim(0)
plt.show()
ImportError Traceback (most recent call last)
def train_clf(clf, X_train, y_train):
return clf.fit(X_train, y_train)
def pred_clf(clf, features, target):
y_pred = clf.predict(features)
return f1_score(target.values, y_pred, pos_label = 1)
def train_predict(clf, X_train, y_train, X_test, y_test):
train_clf(clf, X_train, y_train)
print("F1 score for training set is: {:.4f}".format(pred_clf(clf, X_train, y_train)))
print("F1 score for testing set is: {:.4f}\n".format(pred_clf(clf, X_test, y_test)))
If your methods are so short, consider just putting them inside your main function that you want to optimise.
Additionally, no such function train_predict
exists inside sklearn.model_selection
. Also consider formatting your code so it's easier to read. Place the code between a pair of ```
from sklearn.neighbors import KNeighborsClassifier X_train_cv, X_test_cv, y_train_cv, y_test_cv = train_test_split(X_train, y_train, test_size = 0.3, random_state=100) neighbors = [] accuracy = [] for n in range(3,10):
knn = KNeighborsClassifier(n_neighbors=n) print("Number of neighbors is: {}".format(n)) train_predict(knn, X_train_cv, y_train_cv, X_test_cv, y_testcv) clf = knn.fit(X_train, y_train) ypred = clf.predict(X_test) neighbors.append(n) accuracy.append( str(("%.2f" %(accuracy_score(y_test,y_pred)* 100) ))) accuracy.sort() neighbors.sort() plt.bar( list(range(3, 10)), accuracy, tick_label=neighbors, width=0.8, color="rgbymc") plt.title("Optimizing Neighbours for KNN") plt.xlabel("Neighbours") plt.ylabel("accuracy") plt.ylim(0) plt.show()
ERROR NameError Traceback (most recent call last)