简体   繁体   English

Jupyter 笔记本 python 名称错误

[英]Jupyter notebook python nameerror

I have the following NameError and I'm not sure why.我有以下NameError ,我不知道为什么。 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) .我不断收到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) .尝试KMeans().fit(X_scaled)而不是kmeans.fit(X_scaled) In scikit-learn you have to instantiate a model first before you can fit to it.在 scikit-learn 中,你必须先实例化一个模型,然后才能适应它。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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