2018年1月17日星期三

Surprise

1.Introduction

Surprise 是一个用于构造和分析推荐系统的python库。
Surprise设计的五个原因:
  • 让用户更好的控制他们的实验,我们尽量清晰的在文档中描述清楚算法。
  • 提供数据集,用户可以使用库中自带的数据集,也可以使用自己的。
  • 提供各种即用型预测算法,如基线算法,邻域算法,基于矩阵分解(SVD,PMF,SVD ++,NMF)等等。 此外,还内置了各种相似性测量(余弦,MSD,皮尔森等)。
  • 方便实现新的算法思路。
  • 提供评估,分析和比较算法性能的工具。 交叉验证程序可以使用功能强大的CV迭代器(灵感来自scikit-learn优秀的工具),以及对一组参数进行彻底搜索,轻松运行。

2.Basic usage


# 基本的使用规则
from surprise import SVD
from surprise import Dataset
from surprise.model_selection import cross_validate
# Load the movielens-100k dataset (download it if needed),
data = Dataset.load_builtin('ml-100k')
# We'll use the famous SVD algorithm.
algo = SVD()
# Run 5-fold cross-validation and print results
cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)

 

3.Using prediction algorithm

位于surprise/prediction_algorithms,其中algo_base是基类,里面实现了一些关键的算法,如predict,fit,test.

4.Train-test split and the fit() method(examples.train_test_split.py)


# 数据集的划分
from surprise import SVD
from surprise import Dataset
from surprise import accuracy
from surprise.model_selection import train_test_split

# Load the movielens-100k dataset (download it if needed)
data = Dataset.load_builtin('ml-100k')

# sample random trainset and testset
# test set is made of 25% of the ratings
trainset, testset = train_test_split(data, test_size=.25)

# we'll use the famous SVD algorithm.
algo = SVD()

# Train the algorithm on the trainset, and predict ratings for the dataset
algo.fit(trainset)
predictions = algo.test(testset)

# predictions = algo.fit(trainset).test(testset)

# Then compute RMSE
accuracy.rmse(predictions)

5.Train on the whole trainset and the predict() method(examples/perdict_ratings.py)


# 预测
from surprise import KNNBasic
from surprise import Dataset

# load the movielens-100k dataset
data = Dataset.load_builtin('ml-100k')

# Retrieve the trainset
trainset = data.build_full_trainset()

# Build an algorithm, and train it.
algo = KNNBasic()
algo.fit(trainset)

uid = str(196)
iid = str(302)

pred = algo.predict(uid, iid, r_ui=4, verbose=True)

6 Use a custom dataset(examples/load_custom_dataset.py)


# 导入一个自己的数据集
from surprise import BaselineOnly
from surprise import Dataset
from surprise import Reader
from surprise.model_selection import cross_validate

# path to dataset file
file_path = os.path.expanduser('~/.surprise_data/ml-100k/u.data')

# As we're loading a custom dataset, we need to define a reader. In the
# movielens-100k dataset, each line has the following format:
# 'user item rating timestamp', separated by '\t' characters.

Reader = Reader(line_format='user item rating timestamp', sep='\t')
data = Dataset.load_from_file(file_path, reader=reader)

# we can now use this dataset as we plase
cross_validate(BaselineOnly(), data, verbose=True)


7.Use cross-validation iterators


# 使用cross-validation迭代器
from surprise import SVD
from surprise import Dataset
from surprise import accuracy
from surprise.model_selection import Kfold

# Load the movielens-100k dataset
data = Dataset.load_builtin('ml-100k')

# define a cross-validation iterator
kf = KFold(n_splits=3)

algo = SVD()
For trainset, testset in kf.split(data):
# train and test algorithm
algo.fit(trainset)
predictions = algo.test(testset)
accuracy.rmse(predictions, verbose=True)

8.Tune algorithm parameters with GridSearchCV

# 找出最好的参数

from surprise import SVD
from surprise import Dataset
from surprise.model_selection import GridSearchCV

# Use movielens-100k
data = Dataset.load_builtin('ml-100k')
param_grid = {'n_epochs': [5, 10], 'lr_all': [0.002, 0.005], 'reg_all': [0.4, 0.6]}
gs = GridSearchCV(SVD, param_grid, measures=['rmse', 'mae'], cv=3)
gs.fit(data)

print(gs.best_score['rmse'])
print(gs.best_params['rmse'])

algo = gs.best_estimator['rmse']

algo.fit(data.build_full_trainset())

关于数据集的简单描述:

  • u.data  全部数据的完整集合,来自943个用户对1682部电影的全部评级,每个用户至少评论了20部电影。用户和
    电影都是从1开始标注的。数据是无序的,每一列的标签如下:
    user id | item id | rating | timestamp, 时间戳以1970/1/1号作为起点
  • u.info    用户,电影及评级的数量
  • u.item   电影的属性,每列意义如下:
movie id | movie title | release date | video release date | IMDb URL | unknown | Action | Adventure |
Animation | Children's | Comedy | Crime| Documentary | Drama | Fantasy | Fil-Nori | Horror | Musical |Mystery | Romance | Sci-Fi | Thriller | War | Western |
最后19个字段是流派,电影可以一次属于几个流派,电影ID u.data 数据集中使用。
  • u.genre   一个流派的列表
  • u.user    用户的人口统计信息,这是一个统计卡,每列意义如下:
user id | age | gender | occupation(职位) | zip code |
user id u.data 数据集中使用
  • u.occupation  一个职位的列表
  • u1.base    数据集u1.base u1.test u5.base,u5.test,他们是将u数据80%20%分为训练和测试数据。
                 u1.test     u1u5 中的每一个都是不相交的测试集,如果是5倍交叉验证,就要用到,他们可以由脚本
                 u2.base    mku.shu.data上生成
                 u2.test
                 u3.base
                 u3.test
                 u4.base
                 u4.test
                 u5.base
                 u5.test

  • ua.base    ua.testub.test都有且只有每个用户都10个对电影的评级,他们不相交
                 ua.test      mku.shu.data上生成
                 ub.base

                  ub.test

2018年1月16日星期二

1. globals()   globals() 函数会以字典类型返回当前位置的全部全局变量。

如:
{'LazyLoader': <class 'utils.lazy_loder.LazyLoader'>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'main_test.py', '__package__': None, '__name__': '__main__', '__doc__': None, 'print_function': _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 65536)}

2018年1月9日星期二

spark sql and data frame

Overview
spark sql 是处理结构化数据的Spark模块,与spark的基础RDD模块不同,这个模块提供了更多结构化的信息,与spark sql交互的方式包括SQL和Dataset api.

以下的所有例子都可以在spark-shell shell,pyspark shell和sparkR shell中使用。

SQL
使用spark sql的一种方式是执行SQL查询,Spark SQL也可以用来从现有的Hive安装中读取数据,关于更多的信息,请参考 Hive Tables 部分。 当在另一种编程语言中调用sql时,结果返回的类型会是Dataset/DataFrame类型。你也可以使用 command-line 和 JDBC/ODBC与sql进行交互。

Datasets 和 DataFrames
一个Dataset就是一个数据分布的集合。Dataset是在spark 1.6后添加的新的接口,它提供了RDDs的优点(强壮的类型和使用匿名函数)和Spark sql优化执行引擎的优点,Dataset api在Scala和java中是可以获取的。但是由于python的动态特性,许多Dataset API的优点也已经可用了。R语言的情况也是相似的。

一个DataFrame是一个组织成命名列的DataSet,它的概念等同于一个关系数据库的表或者R/Python中的Data frame, DataFrame 可以从多种资源构造:结构化的数据文件,Hive中的表,扩展的数据库或者从已经存在的RDDs。DataFrame的API对Scala,Java,Python和R都公开。

Getting Started

Starting Point: SparkSession
在spark中,所有函数的入口点是SparkSession类。去创建一个基本的SparkSession,请使用
SparkSession.builder:

from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()
源码可以去 这里

Creating DataFrames
在创建SparkSession的前提下,应用可以创建DataFrames从现存的RDD,Hive table或者Spark 数据资源。
举一个例子,创建一个DataFrame使用一个JSON文件。

# spark is an existing SparkSession
df = spark.read.json("examples/src/main/resources/people.json")
# Displays the content of the DataFrame to stdout
df.show()
# +----+-------+
# | age|   name|
# +----+-------+
# |null|Michael|
# |  30|   Andy|
# |  19| Justin|
# +----+-------+
源码可以去 这里

Untyped Dataset Operations(aka DataFrame Operations)
# spark, df are from the previous example
# Print the schema in a tree format
df.printSchema()
# root
# |-- age: long (nullable = true)
# |-- name: string (nullable = true)

# Select only the "name" column
df.select("name").show()
# +-------+
# |   name|
# +-------+
# |Michael|
# |   Andy|
# | Justin|
# +-------+

# Select everybody, but increment the age by 1
df.select(df['name'], df['age'] + 1).show()
# +-------+---------+
# |   name|(age + 1)|
# +-------+---------+
# |Michael|     null|
# |   Andy|       31|
# | Justin|       20|
# +-------+---------+

# Select people older than 21
df.filter(df['age'] > 21).show()
# +---+----+
# |age|name|
# +---+----+
# | 30|Andy|
# +---+----+

# Count people by age
df.groupBy("age").count().show()
# +----+-----+
# | age|count|
# +----+-----+
# |  19|    1|
# |null|    1|
# |  30|    1|
# +----+-----+
更完整的DataFrame操作可以查看 API文档 笔者看完API文档,会将比较常用的API写在下面。

由于笔者主要看的是data frame,接下来要去看API文档,下面不再翻译

更具体的内容你可以参考 这里


————————————————我是分割线———————————————————

DataFrame的API常用操作
  一个DataFrame就相当于Spark Sql中的一个关系数据库,他可以通过SQLContext中的很多函数创建,例如:
people = sqlContext.read.parquet("...")
一旦创建,就可以用很多方法去操作它:
ageCol = people.age
一个更复杂的例子:
# To create DataFrame using SQLContext
people = sqlContext.read.parquet("...")
department = sqlContext.read.parquet("...")

people.filter(people.age > 30).join(department, people.deptId == department.id) \
  .groupBy(department.name, "gender").agg({"salary": "avg", "age": "max"})
上述例子的意思就是先做一个people表的筛选,再取people表和department的union, 然后根据department里面的name和gender属性对表进行一个分组,然后在分好的组里取salary的平均和年龄的最大值。


2018年1月1日星期一

question answering

1. Introduction
 1.1. 什么是question answering(QA)系统?
 系统自动回答用户提出的问题(自然语言的形式)

 1.2. QA涉及的领域
  信息检索(Information retrieval), 人工智能(artificial intelligence), 软件工程(software engineering), 自然语言处理(natural language processing), 知识库(kownledge  base), Linguistic.
+
语义(semantic web), 关联的数据(Linked data)

 1.2.1 信息检索
信息检索是以数据驱动(query driven)来获取数据的一种方法
  1.2.1.1 系统返回一系列的文档
  1.2.1.2 用户浏览检索到的文档并且找出自己想要的信息

 1.2.2 QA
QA是一种以问题驱动(answer driven)来获取信息的方法
  1.2.2.1 用户用自然语言询问问题(基于短语的,整个句子,关键字)
  1.2.2.2 系统返回一系列短回答
  1.2.2.3 包含更多复杂的功能

1.2.3 检索问题慢慢转变为QA问题














但引擎缺乏将复杂的问题转化为答案的能力
















 1.3. 自然语言查询可以分为不同的类别
  1.3.1  factoid查询 : WH 问题如(when, who, where)
  1.3.2   yes/no查询:如(Is berlin capital of Germany?)
  1.3.3   定义查询:如(what is leukemia?)
  1.3.4   原因后果查询: 如(How, Why, What. What are the consequences of the Iraq war? )
  1.3.5 步骤查询:(which are the steps for getting a Master degree)
  1.3.6 比较查询: (What are the differences between the model A and B?)
  1.3.7 查询并给定指定词:(list of hard disks similar to hard disk X.)
  1.3.8 查询意见:(What is the opinion of the majority of Americans about the Iraq war?)

1.4. 语料类型
  1.4.1 结构化的数据(关系数据库,RDF知识库)
  1.4.2 半结构化数据(XML 数据库)
  1.4.3 文本(text)
  1.4.4 多模态数据(image, voice, video)

 1.5 QA系统的种类
   1.5.1 开放领域(领域独立的QA系统,其可以回答任意语料的任意查询)
     1.5.1.1 优点 覆盖了广泛范围的查询
     1.5.1.2 缺点 准确率低
   1.5.2  特定领域
    1.5.2.1 优点 高准确率
    1.5.2.2 缺点 查询范围受到限制
    1.5.2.3 缺点 需要领域专家

 1.6 研究QA系统有需要吗?

































2. Preliminary concepts




















2.1 语义
 






















 2.2 type of answer











 2.3 entity recognition





















原文来自于: https://www.slideshare.net/shekarpour/tutorial-on-question-answering-systems?from_action=save

leetcode 17

17.   Letter Combinations of a Phone Number Medium Given a string containing digits from   2-9   inclusive, return all possible l...