当前位置: 首页>>代码示例>>Python>>正文


Python Table.from_list方法代码示例

本文整理汇总了Python中Orange.data.Table.from_list方法的典型用法代码示例。如果您正苦于以下问题:Python Table.from_list方法的具体用法?Python Table.from_list怎么用?Python Table.from_list使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Orange.data.Table的用法示例。


在下文中一共展示了Table.from_list方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: setUp

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
    def setUp(self):
        self.cont_data = Table.from_list(
            self.cont_domain,
            [[1, 3, 2],
             [-1, 5, 0],
             [1, 1, 1],
             [7, 2, 3]])

        self.cont_data2 = Table.from_list(
            self.cont_domain,
            [[2, 1, 3],
             [1, 2, 2]]
        )

        self.disc_data = Table.from_list(
            self.disc_domain,
            [[0, 0, 0],
             [0, 1, 1],
             [1, 3, 1]]
        )

        self.disc_data4 = Table.from_list(
            self.disc_domain,
            [[0, 0, 0],
             [0, 1, 1],
             [0, 1, 1],
             [1, 3, 1]]
        )

        self.mixed_data = self.data = Table.from_numpy(
            self.domain, np.hstack((self.cont_data.X[:3], self.disc_data.X)))
开发者ID:ales-erjavec,项目名称:orange3,代码行数:33,代码来源:test_distance.py

示例2: test_zero_instances

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
    def test_zero_instances(self):
        "Test all zero instances"
        domain = Domain([ContinuousVariable(c) for c in "abc"])
        dense_data = Table.from_list(
            domain, [[0, 0, 0], [0, 0, 0], [0, 0, 1]])
        sparse_data = Table(domain, csr_matrix(dense_data.X))
        dist_dense = self.Distance(dense_data)
        dist_sparse = self.Distance(sparse_data)

        self.assertEqual(dist_dense[0][1], 0)
        self.assertEqual(dist_sparse[0][1], 0)
        self.assertEqual(dist_dense[0][2], 1)
        self.assertEqual(dist_sparse[0][2], 1)
开发者ID:PrimozGodec,项目名称:orange3,代码行数:15,代码来源:test_distance.py

示例3: test_different_number_of_attributes

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
 def test_different_number_of_attributes(self, canvas_rectangle):
     domain = Domain([DiscreteVariable(c, values="01") for c in "abcd"])
     data = Table.from_list(
         domain,
         [list("{:04b}".format(i)[-4:]) for i in range(16)])
     self.send_signal(self.widget.Inputs.data, data)
     widget = self.widget
     widget.variable2 = widget.variable3 = widget.variable4 = None
     for i, attr in enumerate(data.domain[:4], start=1):
         canvas_rectangle.reset_mock()
         setattr(self.widget, "variable" + str(i), attr)
         self.widget.update_graph()
         self.assertEqual(canvas_rectangle.call_count, 7 + 2 ** (i + 1))
开发者ID:PrimozGodec,项目名称:orange3,代码行数:15,代码来源:test_owmosaic.py

示例4: test_sparse

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
    def test_sparse(self):
        """Test sparse support in distances."""
        domain = Domain([ContinuousVariable(c) for c in "abc"])
        dense_data = Table.from_list(
            domain, [[1, 0, 2], [-1, 5, 0], [0, 1, 1], [7, 0, 0]])
        sparse_data = Table(domain, csr_matrix(dense_data.X))

        if not self.Distance.supports_sparse:
            self.assertRaises(TypeError, self.Distance, sparse_data)
        else:
            # check the result is the same for sparse and dense
            dist_dense = self.Distance(dense_data)
            dist_sparse = self.Distance(sparse_data)
            np.testing.assert_allclose(dist_sparse, dist_dense)
开发者ID:ales-erjavec,项目名称:orange3,代码行数:16,代码来源:test_distance.py

示例5: from_url

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
def from_url(url):
    name = urllib.parse.urlparse(url)[2].replace('/', '_')

    def suggested_filename(content_disposition):
        # See https://tools.ietf.org/html/rfc6266#section-4.1
        matches = re.findall(r"filename\*?=(?:\"|.{0,10}?'[^']*')([^\"]+)",
                             content_disposition or '')
        return urllib.parse.unquote(matches[-1]) if matches else ''

    def get_encoding(content_disposition):
        matches = re.findall(r"filename\*=(.{0,10}?)'[^']*'",
                             content_disposition or '')
        return matches[0].lower() if matches else 'utf-8'

    with urllib.request.urlopen(url, timeout=10) as response:
        name = suggested_filename(response.headers['content-disposition']) or name

        encoding = get_encoding(response.headers['content-disposition'])
        text = [row.decode(encoding) for row in response]
        csv_reader = csv.reader(text, delimiter='\t')
        header = next(csv_reader)
        data = np.array(list(csv_reader))

        attrs = []
        metas = []
        attrs_cols = []
        metas_cols = []
        for col in range(data.shape[1]):
            values = [val for val in data[:, col] if val not in ('', '?', 'nan')]
            try: floats = [float(i) for i in values]
            except ValueError:
                # Not numbers
                values = set(values)
                if len(values) < 12:
                    attrs.append(DiscreteVariable(header[col], values=sorted(values)))
                    attrs_cols.append(col)
                else:
                    metas.append(StringVariable(header[col]))
                    metas_cols.append(col)
            else:
                attrs.append(ContinuousVariable(header[col]))
                attrs_cols.append(col)

        domain = Domain(attrs, metas=metas)
        data = np.hstack((data[:, attrs_cols], data[:, metas_cols]))
        table = Table.from_list(domain, data.tolist())

    table.name = os.path.splitext(name)[0]
    return table
开发者ID:r0b1n1983liu,项目名称:o3env,代码行数:51,代码来源:owgooglesheets.py

示例6: _grid_indices_to_image_list

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
    def _grid_indices_to_image_list(self, images):
        """
        Return the image grid as a Table of images, ordered by rows. 
        If a grid cell does not contain an image, put None in its place.

        Parameters
        ----------
        images: Orange.data.Table
            The images to order.

        Returns
        -------
        Orange.data.Table
            A Table of images in the grid, ordered by rows.
        """
        image_list = [Instance(images.domain, image)
                      for image in self.order_to_grid(images)]
        image_list = Table.from_list(images.domain, image_list)
        return image_list
开发者ID:biolab,项目名称:orange3-imageanalytics,代码行数:21,代码来源:image_grid.py

示例7: read_distance_file

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
 def read_distance_file(self, fn):
     fle = open(fn)
     line = fle.readline().split()
     n = int(line[0])
     labelled = len(line) > 1
     matrix = np.zeros((n, n))
     items = [] if labelled else None
     for i in range(n):
         line = fle.readline().split("\t")
         if labelled:
             items.append(line[0])
         del line[0]
         for j, e in enumerate(line):
             matrix[i, j] = matrix[j, i] = float(e)
     if labelled:
         items = Table.from_list(
             Domain([], metas=[StringVariable("label")]),
             [[item] for item in items])
     return DistMatrix(matrix, items, items)
开发者ID:ales-erjavec,项目名称:orange3-prototypes,代码行数:21,代码来源:owdistancefile.py

示例8: __call__

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
    def __call__(self, data, ret=Value):
        def fix_dim(x):
            return x[0] if one_d else x

        if not 0 <= ret <= 2:
            raise ValueError("invalid value of argument 'ret'")
        if ret > 0 and any(v.is_continuous for v in self.domain.class_vars):
            raise ValueError("cannot predict continuous distributions")

        # Call the predictor
        one_d = False
        if isinstance(data, np.ndarray):
            one_d = data.ndim == 1
            prediction = self.predict(np.atleast_2d(data))
        elif isinstance(data, scipy.sparse.csr.csr_matrix):
            prediction = self.predict(data)
        elif isinstance(data, (Table, Instance)):
            if isinstance(data, Instance):
                data = Table(data.domain, [data])
                one_d = True
            if data.domain != self.domain:
                if self.original_domain.attributes != data.domain.attributes \
                        and data.X.size \
                        and not np.isnan(data.X).all():
                    data = data.transform(self.original_domain)
                    if np.isnan(data.X).all():
                        raise DomainTransformationError(
                            "domain transformation produced no defined values")
                data = data.transform(self.domain)
            prediction = self.predict_storage(data)
        elif isinstance(data, (list, tuple)):
            if not isinstance(data[0], (list, tuple)):
                data = [data]
                one_d = True
            data = Table.from_list(self.original_domain, data)
            data = data.transform(self.domain)
            prediction = self.predict_storage(data)
        else:
            raise TypeError("Unrecognized argument (instance of '{}')"
                            .format(type(data).__name__))

        # Parse the result into value and probs
        multitarget = len(self.domain.class_vars) > 1
        if isinstance(prediction, tuple):
            value, probs = prediction
        elif prediction.ndim == 1 + multitarget:
            value, probs = prediction, None
        elif prediction.ndim == 2 + multitarget:
            value, probs = None, prediction
        else:
            raise TypeError("model returned a %i-dimensional array",
                            prediction.ndim)

        # Ensure that we have what we need to return
        if ret != Model.Probs and value is None:
            value = np.argmax(probs, axis=-1)
        if ret != Model.Value and probs is None:
            if multitarget:
                max_card = max(len(c.values)
                               for c in self.domain.class_vars)
                probs = np.zeros(value.shape + (max_card,), float)
                for i in range(len(self.domain.class_vars)):
                    probs[:, i, :] = one_hot(value[:, i])
            else:
                probs = one_hot(value)
            if ret == Model.ValueProbs:
                return fix_dim(value), fix_dim(probs)
            else:
                return fix_dim(probs)

        # Return what we need to
        if ret == Model.Probs:
            return fix_dim(probs)
        if isinstance(data, Instance) and not multitarget:
            value = Value(self.domain.class_var, value[0])
        if ret == Model.Value:
            return fix_dim(value)
        else:  # ret == Model.ValueProbs
            return fix_dim(value), fix_dim(probs)
开发者ID:PrimozGodec,项目名称:orange3,代码行数:81,代码来源:base.py

示例9: new_table

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
 def new_table():
     return Table.from_list(Domain([ContinuousVariable("a")]), [[1]])
开发者ID:ales-erjavec,项目名称:orange3,代码行数:4,代码来源:test_distance.py

示例10: from_file

# 需要导入模块: from Orange.data import Table [as 别名]
# 或者: from Orange.data.Table import from_list [as 别名]
    def from_file(cls, filename):
        """
        Load distance matrix from a file

        The file should be preferrably encoded in ascii/utf-8. White space at
        the beginning and end of lines is ignored.

        The first line of the file starts with the matrix dimension. It
        can be followed by a list flags

        - *axis=<number>*: the axis number
        - *symmetric*: the matrix is symmetric; when reading the element (i, j)
          it's value is also assigned to (j, i)
        - *asymmetric*: the matrix is asymmetric
        - *row_labels*: the file contains row labels
        - *col_labels*: the file contains column labels

        By default, matrices are symmetric, have axis 1 and no labels are given.
        Flags *labeled* and *labelled* are obsolete aliases for *row_labels*.

        If the file has column labels, they follow in the second line.
        Row labels appear at the beginning of each row.
        Labels are arbitrary strings that connot contain newlines and
        tabulators. Labels are stored as instances of `Table` with a single
        meta attribute named "label".

        The remaining lines contain tab-separated numbers, preceded with labels,
        if present. Lines are padded with zeros if necessary. If the matrix is
        symmetric, the file contains the lower triangle; any data above the
        diagonal is ignored.

        Args:
            filename: file name
        """
        with open(filename, encoding=detect_encoding(filename)) as fle:
            line = fle.readline()
            if not line:
                raise ValueError("empty file")
            data = line.strip().split()
            if not data[0].strip().isdigit():
                raise ValueError("distance file must begin with dimension")
            n = int(data.pop(0))
            symmetric = True
            axis = 1
            col_labels = row_labels = None
            for flag in data:
                if flag in ("labelled", "labeled", "row_labels"):
                    row_labels = []
                elif flag == "col_labels":
                    col_labels = []
                elif flag == "symmetric":
                    symmetric = True
                elif flag == "asymmetric":
                    symmetric = False
                else:
                    flag_data = flag.split("=")
                    if len(flag_data) == 2:
                        name, value = map(str.strip, flag_data)
                    else:
                        name, value = "", None
                    if name == "axis" and value.isdigit():
                        axis = int(value)
                    else:
                        raise ValueError("invalid flag '{}'".format(
                            flag, filename))
            if col_labels is not None:
                col_labels = [x.strip()
                              for x in fle.readline().strip().split("\t")]
                if len(col_labels) != n:
                    raise ValueError("mismatching number of column labels")

            matrix = np.zeros((n, n))
            for i, line in enumerate(fle):
                if i >= n:
                    raise ValueError("too many rows".format(filename))
                line = line.strip().split("\t")
                if row_labels is not None:
                    row_labels.append(line.pop(0).strip())
                if len(line) > n:
                    raise ValueError("too many columns in matrix row {}".
                                     format("'{}'".format(row_labels[i])
                                            if row_labels else i + 1))
                for j, e in enumerate(line[:i + 1 if symmetric else n]):
                    try:
                        matrix[i, j] = float(e)
                    except ValueError as exc:
                        raise ValueError(
                            "invalid element at row {}, column {}".format(
                                "'{}'".format(row_labels[i])
                                if row_labels else i + 1,
                                "'{}'".format(col_labels[j])
                                if col_labels else j + 1)) from exc
                    if symmetric:
                        matrix[j, i] = matrix[i, j]
        if col_labels:
            col_labels = Table.from_list(
                Domain([], metas=[StringVariable("label")]),
                [[item] for item in col_labels])
        if row_labels:
            row_labels = Table.from_list(
#.........这里部分代码省略.........
开发者ID:675801717,项目名称:orange3,代码行数:103,代码来源:distmatrix.py


注:本文中的Orange.data.Table.from_list方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。