【问题标题】:ValueError: shapes (831,18) and (1629,2) not aligned: 18 (dim 1) != 1629 (dim 0)ValueError:形状(831,18)和(1629,2)未对齐:18(dim 1)!= 1629(dim 0)
【发布时间】:2019-04-01 19:18:24
【问题描述】:

所以我一直在尝试根据歌曲的歌词和其他参数(如速度等)对歌曲的流行度进行分类。现在这是我试图通过 tkinter 运行的代码的 sn-p。

import pandas as pd
from sklearn_pandas import DataFrameMapper
from sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer,CountVectorizer

df = pd.read_csv(r'Dataset(Advanced)(processed lyrics).csv') 

df['Lyrics'] = df['Lyrics'].astype(str)   

mapper = DataFrameMapper([('Lyrics', CountVectorizer()),
  ('Tempo', None),
  ('Energy', None),
   ('Loudness', None),
  ('Danceability', None),
  ('Speechiness', None),
  ('Acousticness', None),
 ('Artist Hit', None)
 ])

features = mapper.fit_transform(df[['Lyrics', 'Tempo', 'Energy', 'Loudness', 'Danceability', 'Speechiness'
                                , 'Acousticness', 'Artist Hit']])
y = df['Hit']

from sklearn.naive_bayes import MultinomialNB
model = MultinomialNB()

model.fit(features, y)

现在,这是我单击按钮时调用的函数。在这里,我获取歌曲的所有值,例如歌词、节奏等,并将其转换为数据框属性以适合 DataFrameMapper。虽然这一切看起来都不错,

def predict():
user_Lyrics = lyricsTextBox2.get(1.0, "end-1c")
user_Lyrics = user_Lyrics.values.astype(str)
print(user_Lyrics.head())
print(type(user_Lyrics))

# Everything in lowercase
user_Lyrics = user_Lyrics.apply(lambda x: " ".join(x.lower() for x in str(x).split()))

# Removing punctuation that does not add meaning to the song
user_Lyrics = user_Lyrics.str.replace('[^\w\s]', '')

# Removing of stop words
from nltk.corpus import stopwords

stop = stopwords.words('english')
user_Lyrics = user_Lyrics.apply(lambda x: " ".join(x for x in str(x).split() if x not in stop))

# Correction of Spelling mistakes
from textblob import TextBlob
user_Lyrics = user_Lyrics.apply(lambda x: str(TextBlob(x).correct()))

# Lemmatization is basically converting a word into its root word. It is preferred over Stemming.
from textblob import Word
user_Lyrics = user_Lyrics.apply(lambda x: " ".join([Word(word).lemmatize() for word in x.split()]))



df['AP'] = float(ArtistPopularityEntry.get())
df['SE'] = float(EnergyEntry.get())
df['SL'] = float(LoudnessEntry.get())
df['SA'] = float(AcousticnessEntry.get())
df['ST'] = float(TempoEntry.get())
df['SD'] = float(DanceabilityEntry.get())
df['SS'] = float(SpeechinessEntry.get())

mapper2 = DataFrameMapper([
    ('Lyrics_User', CountVectorizer()),
    ('ST', None),
    ('SE', None),
    ('SL', None),
    ('SD', None),
    ('SS', None),
    ('SA', None),
    ('AP', None)
])
features2 = mapper2.fit_transform(df[['Lyrics_User', 'ST', 'SE', 'SL', 'SD', 'SS', 'SA', 'AP']])

print(type(features2))
print(len(features2))
print(features2.shape)

print(type(features))
print(len(features))
print(features.shape)

user_prediction = model.predict(features2)
print(user_prediction)
if (user_prediction[0] == 1):
    resultLabel2.config(text='Song is Hit')
else:
    resultLabel2.config(text='Song is not Hit')

输出:

<class 'numpy.ndarray'>
831
(831, 18)
<class 'numpy.ndarray'>
831
(831, 1629)

Error: 

Exception in Tkinter callback Traceback (most recent call last):   File "C:\Users\moksh\Anaconda3\lib\tkinter\__init__.py", line 1702, in
    __call__
        return self.func(*args)   File "<ipython-input-4-f6ddab248363>", 
line 69, in predict
        user_prediction = model.predict(features2)   File 
"C:\Users\moksh\Anaconda3\lib\site-packages\sklearn\naive_bayes.py", line 
66, in predict
        jll = self._joint_log_likelihood(X)   File 
"C:\Users\moksh\Anaconda3\lib\site-packages\sklearn\naive_bayes.py", line 
725, in _joint_log_likelihood
        return (safe_sparse_dot(X, self.feature_log_prob_.T) +   File 
"C:\Users\moksh\Anaconda3\lib\site-packages\sklearn\utils\extmath.py", 
line 140, in safe_sparse_dot
        return np.dot(a, b) ValueError: shapes (831,18) and (1629,2) not 
aligned: 18 (dim 1) != 1629 (dim 0)

编辑

 df['AP'] = float(ArtistPopularityEntry.get())
 df['SE'] = float(EnergyEntry.get())
 df['ST'] = float(TempoEntry.get())


 features2 = mapper.transform(df[['Lyrics_User', 'ST', 'SE', 'AP']])

这给出了另一个错误:

Tkinter 回调 Traceback 中的异常(最近一次调用最后一次):
文件 "C:\Users\moksh\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", 第 3063 行,在 get_loc 中 返回 self._engine.get_loc(key) 文件“pandas_libs\index.pyx”,第 140 行,在 pandas._libs.index.IndexEngine.get_loc 文件中 “pandas_libs\index.pyx”,第 162 行,在 pandas._libs.index.IndexEngine.get_loc 文件 “pandas_libs\hashtable_class_helper.pxi”,第 1492 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 文件 “pandas_libs\hashtable_class_helper.pxi”,第 1500 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'Lyrics'

在处理上述异常的过程中,又发生了一个异常:

Traceback(最近一次调用最后一次):文件 “C:\Users\moksh\Anaconda3\lib\tkinter__init__.py”,第 1702 行,在 致电 return self.func(*args) File "", line 53, in predict features2 = mapper.transform(df[['Lyrics_User', 'ST', 'SE', 'AP']]) 文件 "C:\Users\moksh\Anaconda3\lib\site-packages\sklearn_pandas\dataframe_mapper.py", 第 289 行,在变换中 Xt = self._get_col_subset(X, columns, input_df) 文件 "C:\Users\moksh\Anaconda3\lib\site-packages\sklearn_pandas\dataframe_mapper.py", 第 182 行,在 _get_col_subset t = X[cols[0]] 文件“C:\Users\moksh\Anaconda3\lib\site-packages\pandas\core\frame.py”, 第 2685 行,在 getitem 中 返回 self._getitem_column(key) 文件 "C:\Users\moksh\Anaconda3\lib\site-packages\pandas\core\frame.py", 第 2692 行,在 _getitem_column 中 返回 self._get_item_cache(key) 文件 "C:\Users\moksh\Anaconda3\lib\site-packages\pandas\core\generic.py", 第 2486 行,在 _get_item_cache 中 值 = self._data.get(item) 文件“C:\Users\moksh\Anaconda3\lib\site-packages\pandas\core\internals.py”, 第 4115 行,在获取 loc = self.items.get_loc(item) 文件 "C:\Users\moksh\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", 第 3065 行,在 get_loc 中 return self._engine.get_loc(self._maybe_cast_indexer(key)) 文件“pandas_libs\index.pyx”,第 140 行,在 pandas._libs.index.IndexEngine.get_loc 文件 “pandas_libs\index.pyx”,第 162 行,在 pandas._libs.index.IndexEngine.get_loc 文件 “pandas_libs\hashtable_class_helper.pxi”,第 1492 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 文件 “pandas_libs\hashtable_class_helper.pxi”,第 1500 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'Lyrics'

【问题讨论】:

  • 显然,您正试图将两个没有正确维度的矩阵相乘。你做了什么检查坏尺寸来自哪里?
  • 很明显,是的。但我就是无法找到错误尺寸的来源。
  • 你试过输出形状吗?例如,您在原始模型中拥有什么,以及您在新数据中使用什么。
  • 我编辑了问题,将输出包含在“features2”下方的打印语句中。我似乎无法纠正这个问题。显然,存在尺寸不匹配。骗我。有可行的解决方案吗?
  • 这看起来和tkinter无关。

标签: python dataframe machine-learning scikit-learn


【解决方案1】:

您正在拟合两个不同的 CountVectorizer 对象(1 个用于训练,另一个用于预测),它们学习了两个不同的词汇集。

在训练过程中,由于数据量很大并且由多个样本组成,它产生了 1629 个单词的词汇表。但是在预测的时候,因为你只是用它来预测单个样本,所以词汇量是18。

这是错误的来源。

现在告诉我你为什么在预测时使用相同的 model 对象,而不是新的对象?那是因为新的model 不会学到任何东西。同样,mapper 中的原始CountVectorizer 对象已经了解了一些关于您的数据的信息,这些信息需要在预测时使用。

您需要使用旧的mapper(已经安装),而不是声明一个新对象mapper2并调用fit_transform()(它将了解从头开始传递的数据),并调用transform () 就可以了。

而不是:

mapper2 = DataFrameMapper([
    ('Lyrics_User', CountVectorizer()),
    ('ST', None),
    ('SE', None),
    ('SL', None),
    ('SD', None),
    ('SS', None),
    ('SA', None),
    ('AP', None)
])
features2 = mapper2.fit_transform(df[['Lyrics_User', 'ST', 'SE', 'SL', 'SD', 'SS', 'SA', 'AP']])

这样做:

features2 = mapper.transform(df[['Lyrics', 'ST', 'SE', 'SL', 'SD', 'SS', 'SA', 'AP']])

【讨论】:

  • 感谢您如此详细的回复,非常感谢!我试过这样做,它给了我另一个错误。 (编辑)
  • @MokshVerma 您需要与原始映射器中的列名相同。我很抱歉我错过了。您需要将Lyrics_User 更改为Lyrics
猜你喜欢
  • 2019-03-21
  • 2019-05-28
  • 2021-04-25
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 2019-04-25
相关资源
最近更新 更多