【发布时间】:2017-04-23 11:10:56
【问题描述】:
我正在从事一个机器学习项目。我需要创建两个 python 脚本:
1) 分类器
2) 使用该分类器生成标签的文本文件。
我只是将模型保存在第一个脚本中。然后,在第二个脚本中,我将该模型应用于包含文本的不同数据集以生成预测标签(火腿或垃圾邮件)并将这些预测标签保存在文本文件中。
基本上我有一个带有标签、火腿或垃圾邮件的文本列表。
我使用线性回归模型创建了一个分类器。我有两个不同的训练数据文件(texts_training 和 labels_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。
我是初学者,今天我一直在为此苦苦挣扎。我不明白为什么我会收到此错误以及如何修复它。如果有人提供帮助,我将不胜感激。
【问题讨论】:
-
clf的type是什么,在你写clf = lreg.fit(X, y)之后? -
;我如何找到类型?文本和标签变量在 numpy.ndarray -
1.请避免函数调用和括号之间有空格。 2. pickle.dump((clf,f) 产生语法错误 3. 那行也保存了拟合的模型,但没有保存数据!你需要再次预测。为什么这么早创建文件对象 f?labels_produced 背后的逻辑。 txt 我不清楚。顺便说一句。线性回归通常不是(!)分类器。
-
@Quickbeam2k1 我只是将模型保存在第一个脚本中。然后我将该模型应用于包含文本的不同数据集以生成预测标签(火腿或垃圾邮件)并将这些预测标签保存在文本文件中。
-
您正在保存模型。该模型不包含任何输出值。但是,如果您对输入进行迭代,则可以将模型应用于该输入并获得输出,
ham或spam。我想你想存储这些输出。但目前,你没有这样做
标签: python machine-learning classification linear-regression