我有一个火花数据框如下:
predictions.show(5)
+------+----+------+-----------+
| user|item|rating| prediction|
+------+----+------+-----------+
|379433| 31| 1| 0.08203495|
| 1834| 31| 1| 0.4854447|
|422635| 31| 1|0.017672742|
| 839| 31| 1| 0.39273006|
| 51444| 31| 1| 0.09795039|
+------+----+------+-----------+
only showing top 5 rows
Run Code Online (Sandbox Code Playgroud)
预测是预测的评级,评级是隐含评级(计数).
现在我想检查我的推荐算法的AUC.
我首先尝试了pyspark.ml.BinaryClassificationEvaluator,因为它直接在数据框上工作.
# getting the evaluationa metric
from pyspark.ml.evaluation import BinaryClassificationEvaluator
evaluator = BinaryClassificationEvaluator(rawPredictionCol="prediction")
print evaluator.evaluate(predictions)
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
---------------------------------------------------------------------------
IllegalArgumentException Traceback (most recent call last)
<ipython-input-65-c642ea9c2cf5> in <module>()
4
5 evaluator = BinaryClassificationEvaluator(rawPredictionCol="prediction")
----> 6 print evaluator.evaluate(predictions)
7
8 #print evaluator.evaluate(predictions, {evaluator.metricName: "areaUnderPR"})
/Users/i854319/spark/python/pyspark/ml/evaluation.py in …Run Code Online (Sandbox Code Playgroud) python apache-spark pyspark apache-spark-ml apache-spark-mllib
我正在尝试使用Python Pandas导入CSV文件.此文件中的示例数据如下所示,其中第一行是以逗号分隔的列名.
End Customer Organization ID,End Customer Organization Name,End Customer Top Parent Organization ID,End Customer Top Parent Organization Name,Reseller Top Parent ID,Reseller Top Parent Name,Business,Rev Sum Division,Rev Sum Category,Product Family,Version,Pricing Level,Summary Pricing Level,Detail Pricing Level,MS Sales Amount,MS Sales Licenses,Fiscal Year,Sales Date
11027676,Baroda Western Uttar Pradesh Gramin Bankgfhgfnjgfnmjmhgmghmghmghmnghnmghnmhgnmghnghngh,4078446,Bank Of Barodadfhhgfjyjtkyukujkyujkuhykluiluilui;iooi';po'fserwefvegwegf,1809012,"Hcl Infosystems Ltd - Partnerdghftrutyhb frhywer5y5tyu6ui7iukluyj,lgjmfgnhfrgweffw",Server & CALsdgrgrfgtrhytrnhjdgthjtyjkukmhjmghmbhmgfngdfbndfhtgh,SQL Server & CALdfhtrhtrgbhrghrye5y45y45yu56juhydsgfaefwe,SQL CALdhdfthtrutrjurhjethfdehrerfgwerweqeadfawrqwerwegtrhyjuytjhyj,SQL CALdtrye45y3t434tjkabcjkasdhfhasdjkcbaksmjcbfuigkjasbcjkasbkdfhiwh,2005,Openfkvgjesropiguwe90fujklascnioawfy98eyfuiasdbcvjkxsbhg,Open Lklbjdfoigueroigbjvwioergyuiowerhgosdhvgfoisdhyguiserhguisrh,"Open Stddfm,vdnoghioerivnsdflierohgushdfovhsiodghuiohdbvgsjdhgouiwerho",125.85,1,FY07,12/28/2006
12835756,Uttam Strips Pvt Ltd,12835756,Uttam Strips Pvt Ltd,12565538,Redington C/O Fortis Financial Services Ltd,MBS,Dynamics ERP,Dynamics NAV,Dynamics NAV Business Essentials,Non-specific,Other,MBS …Run Code Online (Sandbox Code Playgroud) 我想试试applymapPandas DataFrame对象方法的功能.这是用例:
假设我的DataFrame df1如下:
Age ID Name
0 27 101 John
1 22 102 Bob
2 19 103 Alok
3 27 104 Tom
4 32 105 Matt
5 19 106 Steve
6 5 107 Tom
7 55 108 Dick
8 67 109 Harry
Run Code Online (Sandbox Code Playgroud)
现在我想创建一个标志变量,其逻辑是如果元素的长度小于2,则flag = 1 else flag = 0.
为了运行这个元素,我想使用applymap方法.为此,我创建了一个用户定义的函数,如下所示:
def f(x):
if len(str(x))>2:
df1['Flag']=1
else:
df1['Flag']=0
Run Code Online (Sandbox Code Playgroud)
然后我跑df1.applymap(f)了给了:
Age ID Name
0 None None None
1 None None None
2 None …Run Code Online (Sandbox Code Playgroud) 我在sklearn中运行了一些模型.这是相同的代码.
# Function for Stochastic Gradient Descent Logistic Regression with Elastic Net
def SGDlogistic(k_fold,train_X,train_Y):
"""Method to implement Multi-class SVM using
Stochastic Gradient Descent
"""
from sklearn.linear_model import SGDClassifier
scores_sgd_lr = []
for train_indices, test_indices in k_fold:
train_X_cv = train_X[train_indices]
train_Y_cv= train_Y[train_indices]
test_X_cv = train_X[test_indices]
test_Y_cv= train_Y[test_indices]
sgd_lr=SGDClassifier(loss='log',penalty='elasticnet')
scores_sgd_lr.append(sgd_lr.fit(train_X_cv,train_Y_cv).score(test_X_cv,test_Y_cv))
print("The mean accuracy of Stochastic Gradient Descent Logistic on CV data is:", np.mean(scores_sgd_lr))
return sgd_lr
def test_performance(test_X,test_Y,classifier,name):
"""This method checks the performance of each algorithm on test data."""
from sklearn import metrics …Run Code Online (Sandbox Code Playgroud) 我已经安装了anaconda,也已经下载了Spark 1.6.2。我正在使用此答案中的以下说明为Jupyter配置Spark,请在此处输入链接说明
我已经下载并解压缩spark目录为
~/spark
Run Code Online (Sandbox Code Playgroud)
现在,当我进入该目录并进入bin时,会看到以下内容
SFOM00618927A:spark $ cd bin
SFOM00618927A:bin $ ls
beeline pyspark run-example.cmd spark-class2.cmd spark-sql sparkR
beeline.cmd pyspark.cmd run-example2.cmd spark-shell spark-submit sparkR.cmd
load-spark-env.cmd pyspark2.cmd spark-class spark-shell.cmd spark-submit.cmd sparkR2.cmd
load-spark-env.sh run-example spark-class.cmd spark-shell2.cmd spark-submit2.cmd
Run Code Online (Sandbox Code Playgroud)
我还按照上述答案将环境变量添加到了.bash_profile和.profile中。
现在在spark / bin目录中,我要检查的第一件事是pyspark命令是否首先在Shell上运行。
所以我在做cd spark / bin之后就这样做
SFOM00618927A:bin $ pyspark
-bash: pyspark: command not found
Run Code Online (Sandbox Code Playgroud)
按照所有步骤后的答案,我可以做
pyspark
Run Code Online (Sandbox Code Playgroud)
在任何目录的终端中,它应该启动一个带有Spark引擎的Jupyter笔记本。但是,即使外壳中的pyspark无法正常工作,也请忘记使其在juypter笔记本上运行
请告知这里出了什么问题。
编辑:
我做了
open .profile
Run Code Online (Sandbox Code Playgroud)
在主目录中,这就是存储在路径中的内容。
export PATH=/Users/854319/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin:/Users/854319/spark/bin
export PYSPARK_DRIVER_PYTHON=ipython
export PYSPARK_DRIVER_PYTHON_OPTS='notebook' pyspark
Run Code Online (Sandbox Code Playgroud) 我使用了 spark 的 word2vec 算法来计算文本的文档向量。
然后我使用findSynonyms模型对象的功能来获取几个单词的同义词。
我看到这样的事情:
w2vmodel.findSynonyms('science',4).show(5)
+------------+------------------+
| word| similarity|
+------------+------------------+
| physics| 1.714908638833209|
| fiction|1.5189824643358183|
|neuroscience|1.4968051528391833|
| psychology| 1.458865636374223|
+------------+------------------+
Run Code Online (Sandbox Code Playgroud)
我不明白为什么余弦相似度被计算为大于 1。余弦相似度应该在 0 和 1 或 max -1 和 +1 之间(取负角)。
为什么这里大于1?这里出了什么问题?
我正在使用gensim加载预训练的快速文本模型。我从fasttext 网站下载了受英语维基百科训练的模型。
这是我编写的用于加载预训练模型的代码:
from gensim.models import FastText as ft
model=ft.load_fasttext_format("wiki.en.bin")
Run Code Online (Sandbox Code Playgroud)
我尝试检查人声中是否包含以下短语(由于这些是经过预先训练的模型,因此这是极少的机会)。
print("internal executive" in model.wv.vocab)
print("internal executive" in model.wv)
False
True
Run Code Online (Sandbox Code Playgroud)
因此,词汇中不存在“内部主管”一词,但我们仍然有与此对应的词向量。
model.wv["internal executive"]
Out[46]:
array([ 0.0210917 , -0.15233646, -0.1173932 , -0.06210957, -0.07288644,
-0.06304111, 0.07833624, -0.17026938, -0.21922196, 0.01146349,
-0.13639058, 0.17283678, -0.09251394, -0.17875175, 0.01339212,
-0.26683623, 0.05487974, -0.11843193, -0.01982722, 0.37037706,
-0.24370994, 0.14269598, -0.16363597, 0.00328478, -0.16560239,
-0.1450972 , -0.24787527, -0.01318423, 0.03277111, 0.16175713,
-0.19367714, 0.16955379, 0.1972683 , 0.09044111, 0.01731548,
-0.0034324 , -0.04834719, 0.14321515, 0.01422525, -0.08803893,
-0.29411593, -0.1033244 , 0.06278021, 0.16452256, 0.0650492 ,
0.1506474 …Run Code Online (Sandbox Code Playgroud) 我在名为 docker_test 的目录中有一个 Dockerfile。docker_test 的结构如下:
M00618927A:docker_test i854319$ ls
Dockerfile hello_world.py
Run Code Online (Sandbox Code Playgroud)
我的 dockerfile 如下所示:
### Dockerfile
# Created by Baktaawar
# Pulling from base Python image
FROM python:3.6.7-alpine3.6
# author of file
LABEL maintainer="Baktawar"
# Set the working directory of the docker image
WORKDIR /docker_test
COPY . /docker_test
# packages that we need
RUN pip --no-cache-dir install numpy pandas jupyter
EXPOSE 8888
ENTRYPOINT ["python"]
CMD ["hello_world.py"]
Run Code Online (Sandbox Code Playgroud)
我运行命令
docker build -t dockerfile .
Run Code Online (Sandbox Code Playgroud)
它开始构建过程,但随后出现以下错误,无法在图像中安装 numpy 等
Sending build context to Docker daemon …Run Code Online (Sandbox Code Playgroud) 所以我正在 Spark 中构建一个推荐系统。虽然我已经能够使用初始手动超参数值在数据集上评估和运行算法。我想通过让交叉验证估计器从超参数值网格中进行选择来自动化它。所以我为此写了以下函数
def recommendation(train):
""" This function trains a collaborative filtering
algorithm on a ratings training data
We use a Cross Validator and Grid Search to find the right hyper-parameter values
Param:
train----> training data
TUNING PARAMETERS:
alpha----> Alpha value to calculate the confidence matrix (only for implicit datasets)
rank-----> no. of latent factors of the resulting X, Y matrix
reg------> regularization parameter for penalising the X, Y factors
Returns:
model-> ALS model object
"""
from pyspark.ml.tuning import CrossValidator, …Run Code Online (Sandbox Code Playgroud) 我有一个有趣的问题。
我正在使用 Pipeline 对象来运行 ML 任务。
这就是我的 Pipeline 对象的样子。
jpsa_mlp.pipeline.getStages()
Out[244]:
[StringIndexer_479d82259c10308d0587,
Tokenizer_4c5ca5ea35544bb835cb,
StopWordsRemover_4641b68e77f00c8fbb91,
CountVectorizer_468c96c6c714b1000eef,
IDF_465eb809477c6c986ef9,
MultilayerPerceptronClassifier_4a67befe93b015d5bd07]
Run Code Online (Sandbox Code Playgroud)
该管道对象内的所有估计器和转换器都已编码为类方法的一部分,其中 JPSA 是类对象。
现在我想提出一种超参数调整的方法。所以我用下面的:
self.paramGrid = ParamGridBuilder()\
.addGrid(self.pipeline.getStages()[5].layers, [len(self.pipeline.getStages()[3].vocab),10,3])\
.addGrid(self.pipeline.getStages()[5].maxIter, [100,300])\
.build()
Run Code Online (Sandbox Code Playgroud)
问题是对于神经网络分类器来说,超参数之一基本上是隐藏层的大小。MLP分类器的层属性需要输入层、隐藏层和输出层的大小。输入和输出是固定的(基于我们拥有的数据)。所以我想将输入层的大小作为特征向量的大小。但是,我不知道特征向量的大小,因为管道对象内用于创建特征向量(计数向量化器、IDF)的估计器尚未适合数据。
pipeline对象将使用Spark的交叉验证器对象在交叉验证期间拟合数据。然后只有我才能让 CountVectorizerModel 知道特征向量的大小。
如果我实现了 Countvectorizer,那么我可以使用 countvectorizerModel.vocab 来获取特征向量的长度,并将其用作 mlp 层属性中输入层值的参数。
那么,如何为 mlp 的层添加超参数(隐藏层和输入层大小)?
python ×9
apache-spark ×5
pyspark ×5
pandas ×2
docker ×1
fasttext ×1
gensim ×1
nlp ×1
scikit-learn ×1