本篇博客讲解下Weka中数据的属性Attribute。
- 什么是Attribute?
attribute指的是Weka中数据的属性,一般就是表明数据集信息,数据每一列的性质等。之前讲过的Weka数据格式ARFF其实头信息包含的就是数据的Attribute信息。之前讲的Weka的数据存储方式Instances也有Attribute属性。
Attribute属性主要分以下几类,上一篇博客也有具体分析,这节再温习一下:
numeric: This type of attribute represents a floating-point number.
就是代表连续的,浮点数变量,如气温。
nominal: This type of attribute represents a fixed set of nominal values.
指的是离散的,刻意被划分为几类的变量,如户口类型。
string: This type of attribute represents a dynamically expanding set of nominal values. Usually used in text classification.
指的该列内容是文本,一般用于文本挖掘。
date: This type of attribute represents a date, internally represented as floating-point number storing the milliseconds since January 1, 1970, 00:00:00 GMT. The string representation of the date must be ISO-8601 compliant, the default is yyyy-MM-dd'T'HH:mm:ss.
指的该列数据代表日期,要按照规范格式写。
relational: This type of attribute can contain other attributes and is, e.g., used for representing Multi-Instance data. (Multi-Instance data consists of a nominal attribute containing the bag-id, then a relational attribute with all the attributes of the bag, and finally the class attribute.)
用来实现其他类型的数据。
- Attribute用法
Attribute既然是数据的属性,那它只有和数据绑定才有意义。一般来讲,如果读入的文件来自标准格式,如ARFF/CSV,文件头就包含了特征属性名等信息,如果读入txt/libSVM,则Weka要么提示你缺少属性名,要么就会直接把第一条数据当成属性。这样会导致错误。所以加载数据前务必手动添加属性名,无法添加的话就必须手动指定或者修改属性。
下面是官方给的Examlpe:
// Create numeric attributes "length" and "weight"
Attribute length = new Attribute("length");
Attribute weight = new Attribute("weight");
// Create list to hold nominal values "first", "second", "third"
List my_nominal_values = new ArrayList(3);
my_nominal_values.add("first");
my_nominal_values.add("second");
my_nominal_values.add("third");
// Create nominal attribute "position"
Attribute position = new Attribute("position", my_nominal_values);
上面的例子告诉了你如何创建一个Numeric和Nominal属性。一般来说,除非是做文本挖掘项目,一般这两个属性就够了。所以掌握这两个属性的创建方法在使用中已经足够。
另外,当Instances被创建时,你也可以随时使用Attribute方法获取属性信息。如下面的简单打印。
for(int j=0;j<data.numAttributes();j++) {
Attribute attribute = data.attribute(j);
System.out.println(attribute);
}
Attribute和Instance/Instances
这里需要注意的一点是,当你创建一个Instance时,必须要为之指定Attribute,如何创建instance之前的一篇博客有讲过,在此不在赘述。
如果想创建一个新的Instances又不想输入属性,可以直接从已有的数据直接获取Attribute信息,方法是
DataSource source = new DataSource("/some/where/data.arff");
Instances A = source.getDataSet();
Instances blank = new Instances(A,0)