python - 如何根据回归模型的预测值计算标签?

标签 python machine-learning classification linear-regression

我正在开展一个机器学习项目。我需要创建两个 python 脚本:

1) 分类器
2) 使用该分类器生成标签文本文件。

我只是将模型保存在第一个脚本中。然后,在第二个脚本中,我将该模型应用到包含文本的不同数据集以生成预测标签(火腿或垃圾邮件),并将这些预测标签保存在文本文件中。

基本上我有一个带有标签、火腿或垃圾邮件的文本列表。

我使用线性回归模型创建了一个分类器。我有两个不同的训练数据文件(texts_traininglabels_training),因此我将训练数据加载到称为文本和标签的变量中。然后,我研究了分类器。这就是我的分类器:

#classifier.py 
def features (words):
     fe = np.ndarrary ((len(tweets), 56) 
          for t, text in enumerate (words):
               if "money" in text:
                   money = 1
               else:
                   money = 0

               ...(55 more features)

               fe = [i:] = [money, ...]
         return fe
fe = features (words)

feat.shape
>>>(1000, 56)

import sklearn
X = fe
label = preprocessing.LabelEncoder()
label.fit(labels)
label = lab.transform(labels)
y.shape
>>>(1000,)


from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split (X,y, random_state = 4)

from sklearn.preprocessing import StandardScaler
scaler = preprocessing.StandardScaler().fit(X_train)


#Model
from sklearn.linear_model import LinearRegression
clf = LinearRegression()
clf = lreg.fit(X, y) 

import pickle
f = open ("clf.pkl", "w")
pickle.dump ((clf, f)
f.close ()

现在,我将其加载到不同的脚本中,但两个脚本都保存在同一文件夹中。该脚本基本上必须使用该分类器来保存 txt 中生成的标签。

system.py

    def features (words):
     fe = np.ndarrary ((len(tweets), 56) 
          for t, text in enumerate (words):
               if "money" in text:
                   money = 1
               else:
                   money = 0

               ...(55 more features)

               feat = [t, :] = [money, ...]
         return fe
fe = features (words)

X = feat
from sklearn import preprocessing
label = preprocessing.LabelEncoder()
label.fit(labels)
label = label.transform(labels) 
y = label
from sklearn.preprocessing import StandardScaler
scaler = preprocessing.StandardScaler().fit(X)



import pickle
#class_output = pickle.load (open('clf.pkl', 'r'))
loaded_model = pickle.load (open('clf.pkl', 'r'))

class_output = loaded_model.predict (X)

**print class_output
>>>array([ 0.06140778,  0.053107  ,  0.14343903, ...,  0.05701325,
    0.18738435, -0.08788421])**

f = open ("labels_produced.txt", "w")
for output in class_output:
    if output ==0:
        f.write ("ham\n")
    else:
        f.write("spam\n")
f.close()

但是,由于 class_output 中的值都不等于 0,因此如何计算新数据集的垃圾邮件或火腿邮件。我的特征设置为 0 或 1。

我是一名初学者,今天我一整天都在为此苦苦挣扎。我不明白为什么会出现此错误以及如何修复它。如果有人提供帮助,我将非常感激。

最佳答案

您正在尝试迭代一个对象。这就是错误的含义:

'LinearRegression' object is not iterable'

这可以通过执行以下操作来看到:

type(clf) = sklearn.linear_model.base.LinearRegression

clf是一个 LinearRegression 对象,具有自己的一系列属性。您无法像尝试在以下行中那样迭代它:

for output in class_output:
    if output == 0:
        # etc

您需要从 LinearRegression 对象中提取所需的属性 clf ,在将它们保存到 Pickle 之前或在尝试迭代它们之前。

LinearRegression 对象中包含多个属性。 例如,以下将为您提供线性回归拟合的五个系数:

Coefficients = clf.coef_

如果您决定实际要迭代 clf 的哪个属性,则可以按照上面所示的方式提取它。

编辑:LinearRegression 对象中的属性列表可在此处找到:

http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html

coef_ : array, shape (n_features, ) or (n_targets, n_features)

Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features.

residues_ : array, shape (n_targets,) or (1,) or empty

Sum of residuals. Squared Euclidean 2-norm for each target passed during the fit. If the linear regression problem is under-determined (the number of linearly independent rows of the training matrix is less than its number of linearly independent columns), this is an empty array. If the target vector passed during the fit is 1-dimensional, this is a (1,) shape array. New in version 0.18.

intercept_ : array

Independent term in the linear model.

编辑:这里有很好的例子:

http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html

进一步问题:

在你的函数中features ,看起来您传入了 (texts)然后保存某个特征是否为01在列表中feat 。但在函数结束时,您返回 re而不是返回 feat 。如果您返回feat您可能会得到您想要的信息。此外,您还可以使用变量 t,text 进行迭代。但随后在 (feat = [i:] = [money, ...])您在 feat 中分配值使用变量 i 的数组。应该i替换为t

关于python - 如何根据回归模型的预测值计算标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41035578/

相关文章:

python - "Connection aborted"和 "Cannot connect to proxy"

javascript - 带有 python 脚本的 Node.js 应用程序

python - TensorFlow 对象检测 API 评估训练性能

Tensorflow:LSTM 中变量范围的值错误

database - 用于测试图像分类的标准图像数据库

python - 我可以使用 python 检索半径内的多个邮政编码吗

python - 如何在 Python 中将单例数组转换为标量值?

machine-learning - 如何获取OpenNLP模型的训练数据集?

machine-learning - 无法处理多类和连续的混合

java - ARFF 文件中的类属性