2018年2月27日星期二

记录一下go 安装相关的东西

我要参考的安装流程
http://blog.csdn.net/beyond__devil/article/details/68064202

我遇到的错误及解决方法:
1.如果你之前安装过go,那么再次安装前,你需要将安装的go卸载干净。

2.基于上述安装流程,笔者checkout到1.4.3版本,并运行./all.bash,出现以下错误

 runtime/cgo(.text): unexpected relocation type 298
runtime/cgo(.text): unexpected relocation type 298


解决方案:
在命令行输入:export CGO_ENABLED=0
问题解决,编译好的1.4.3在终端上打出的结果如下
 Installed Go for linux/amd64 in /home/xxx/go
Installed commands in /home/xxx/go/bin


3.查看github官网的版本,我将版本checkout到1.9.4版本,运行./all.bash,运行成功,结果如下:
##### API check
Go version is "go1.9.4", ignoring -next /home/xxx/go/api/next.txt

ALL TESTS PASSED

---
Installed Go for linux/amd64 in /home/xxx/go
Installed commands in /home/xxx/go/bin
*** You need to add /home/xxx/go/bin to your PATH.

配置环境变量后,我以为已经成功了,但是当我使用go install进行编译时,出现以下错误:
($GOPATH not set. For more details see: 'go help gopath')




2018年2月26日星期一

bazel 系统学习笔记

立一个flag,15天内系统的学习一下bazel(2月27-3月14日)
1.Introduction介绍
bazel从有WORKSPACE文件的源代码目录构建软件。在一个workspace中的资源文件被组织成packages,一个package是一个包含相关资源文件和BUILD文件的目录,BUILD文件指定如何从资源中编译软件。

2. Workspace, Package and Targets
 2.1 workspace
 workspace指的是你想要构建的资源的软件目录,WORKSPACE可以空,也可以包含workspace rules.

 2.2 Package
workspace的基础单元就是package,一个package是一个包含相关资源文件和BUILD文件的目录,更直观的理解,他就是WORKSPACE下的第一级包,再下层就不是了。package的作用在于你可以指定它的可见性,如
package(default_visibility = ["//visibility:public"])

2.3 Targets
一个package就相当于一个容器,package里面的内容被称为targets。大多数targets都属于以下这两种类型: files或者rules。除此之外,还有一种类型的target,被称之为package group,但是它的数量很少。

files又被分为两种类型,source files(即资源文件)是由编程人员写的完成特定任务的文件,他们被提交到代码仓库。generated files,是由构建工具根据规则生成的特定文件。

rule指定输入文件和输出文件之间的关联,rule中的输出文件一定是generated 文件, rule中的输入文件可能是source或者generated文件。这很容易理解,因为规则的依赖项可能是已经构建好的规则的输出结果。

2.4  Labels
 所有的targets都属于一个唯一的package,target的名字被称为label,典型的label如下:
//my/app/main:app_binary
一个label由两部分组成,一个是package name(my/app/main),另一个是target name
(app_binary),每一个label唯一的指向一个targets,//代表从WORKSPACE所在目录开始
一种特殊情况(//my/app  和//my/app:app等价    :app 和 app等价)
 
 
3.Rules

rules规定输入和输出之间的关联,下面主要介绍针对Python的bazel rules

首先,每个rule都有一个name属性,你最好好好的定义它,使得下一个编码人员可以看懂你写的
意思。这一点在py_binary和py_test中尤为重要。每个规则都有自己对应的属性。
srcs: 属性表示所指定的label的列表,实际上就是要编译的资源文件的列表
outs:  表示输出label的列表, 他与srcs属性相似但有两个不同的地方,



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的平均和年龄的最大值。


leetcode 17

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