简体   繁体   中英

Jupyter notebook python nameerror

I have the following NameError and I'm not sure why. I've only changed the input file path and the column names from a tutorial which worked for me.

import json
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

file = 'cuisine_ingredients.json'
with open(file) as train_file:
   json = json.load(train_file)

train = pd.concat(map(pd.DataFrame,json))
train.reset_index(level=0, inplace=True)

unique_cuisines = train['cuisine'].nunique()

labelEncoder_cuisine = LabelEncoder()
labelEncoder_cuisine.fit(train['cuisine'])
train['cuisine'] = labelEncoder_cuisine.transform(train['cuisine'])

labelEncoder_ingredients = LabelEncoder()
labelEncoder_ingredients.fit(train['ingredients'])
train['ingredients'] = 
labelEncoder_ingredients.transform(train['ingredients'])

X = np.array(train.drop(['id'], 1).astype(float))

scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)

kmeans.fit(X_scaled)

KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=600,
n_clusters=unique_cuisines, n_init=10, n_jobs=1, precompute_distances='auto',
random_state=None, tol=0.0001, verbose=0)

I keep getting NameError: name 'kmeans' is not defined for kmeans.fit(X_scaled) .

Cheers :)

我只是简要地查看了您的代码,但您似乎没有像在kmeans.fit()编写的那样定义kmeans (小写 k 和 m kmeans.fit()

Try KMeans().fit(X_scaled) instead of kmeans.fit(X_scaled) . In scikit-learn you have to instantiate a model first before you can fit to it.

I don't know what the author of the notebook intended but usually you want to save your model to a variable, so you could also write it the following way:

kmeans = KMeans()
kmeans.fit(X_scaled)

Swap these 2 lines of code.

kmeans.fit(X_scaled)

KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=600,
n_clusters=unique_cuisines, n_init=10, n_jobs=1, precompute_distances='auto',
random_state=None, tol=0.0001, verbose=0)

After which, you will probably want the results:

X_transformed = kmeans.transform(X_scaled)

Initialize your model based on your parameters first.

kmeans = KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=600,n_clusters=unique_cuisines, n_init=10, n_jobs=1, precompute_distances='auto',random_state=None, tol=0.0001, verbose=0)

Once the model is initialized then you can try to fit the data.

kmeans.fit(X_scaled)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM