我正在尝试从存储在本地磁盘上的 SQLLite .db 文件加载表。在 PySpark 中有没有干净的方法可以做到这一点?
目前,我正在使用一种有效但不那么优雅的解决方案。首先,我通过 sqlite3 使用 Pandas 读取表格。一个问题是在此过程中架构信息没有被传递(可能是也可能不是问题)。我想知道是否有一种直接的方法可以在不使用 Pandas 的情况下加载表。
import sqlite3
import pandas as pd
db_path = 'alocalfile.db'
query = 'SELECT * from ATableToLoad'
conn = sqlite3.connect(db_path)
a_pandas_df = pd.read_sql_query(query, conn)
a_spark_df = SQLContext.createDataFrame(a_pandas_df)
Run Code Online (Sandbox Code Playgroud)
似乎有一种使用 jdbc 来做到这一点的方法,但我还没有弄清楚如何在 PySpark 中使用它。
我对在测试数据集中使用 cross_val_predict 感到困惑。
我创建了一个简单的随机森林模型并使用 cross_val_predict 进行预测
from sklearn.ensemble import RandomForestClassifier
from sklearn.cross_validation import cross_val_predict, KFold
lr = RandomForestClassifier(random_state=1, class_weight="balanced", n_estimators=25, max_depth=6)
kf = KFold(train_df.shape[0], random_state=1)
predictions = cross_val_predict(lr,train_df[features_columns], train_df["target"], cv=kf)
predictions = pd.Series(predictions)
Run Code Online (Sandbox Code Playgroud)
我对这里的下一步感到困惑,我如何使用上面学到的知识对测试数据集进行预测?
我试图从数据框中仅选择因子列。示例如下:
bank[,apply(bank[,names(bank)!="id"], is.factor)]
Run Code Online (Sandbox Code Playgroud)
但代码的行为很奇怪。一步步:
sapply(bank[,names(bank)!="id"], is.factor)
Run Code Online (Sandbox Code Playgroud)
我得到:
age sex region income married children car
FALSE TRUE TRUE FALSE TRUE FALSE TRUE
save_act current_act mortgage pep ageBin
TRUE TRUE TRUE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)
看起来不错。现在,我假设我只是将这个 TRUE/FALSE 矩阵传递到下一步并仅获取我需要的列:
bank[,sapply(bank[,names(bank)!="id"], is.factor)]
Run Code Online (Sandbox Code Playgroud)
但结果我得到了与原始银行数据框中相同的列。什么都没有被过滤掉。我以一种或另一种方式尝试过,但找不到解决方案。对我做错了什么有什么建议吗?
我不明白为什么它适用于不同的场景,但不适用于这个场景。基本上,一些绅士在这里帮助我改进了我的代码以刮取天气,这非常有效。然后我尝试做同样的事情来刮取 span 标签中的 ETH 值<span class="text-large2" data-currency-value="">$196.01</span>。所以,我在代码中采用了相同的技术,替换了字段,并希望它能够工作。
代码在这里:
import requests
from BeautifulSoup import BeautifulSoup
import time
url = 'https://coinmarketcap.com/currencies/litecoin/'
def ltc():
while (True):
response = requests.get(url)
soup = BeautifulSoup(response.content)
price_now = int(soup.find("div", {"class": "col-xs-6 col-sm-8 col-md-4 text-left"}).find(
"span", {"class": "text-large2"}).getText())
print(u"LTC price is: {}{}".format(price_now))
# if less than 150
if 150 > price_now:
print('Price is Low')
# if more than 200
elif 200 < price_now:
print('Price is high')
if __name__ == "__main__":
ltc()
Run Code Online (Sandbox Code Playgroud)
输出如下所示:
Traceback (most …Run Code Online (Sandbox Code Playgroud) 我有一些时间序列数据,包含三个独立的列(日期、时间、千瓦),如下所示:
Date Time kW
3/1/2011 12:15:00 AM 171.36
3/1/2011 12:30:00 AM 181.44
3/1/2011 12:45:00 AM 175.68
3/1/2011 1:00:00 AM 180.00
3/1/2011 1:15:00 AM 175.68
Run Code Online (Sandbox Code Playgroud)
直接从 Pandas 读取 csv 文件,我可以解析日期和时间:
df= pd.read_csv('C:\\Users\\desktop\\master.csv', parse_dates=[['Date', 'Time']])
Run Code Online (Sandbox Code Playgroud)
这看起来工作得很好,但问题是我想在 Pandas 中创建另一个数据框来表示月份的数值。如果我做一个:
df['month'] = df.index.month
Run Code Online (Sandbox Code Playgroud)
抛出错误:
AttributeError: 'Int64Index' object has no attribute 'month'
我还希望创建额外的数据框来表示时间戳日、分钟、小时...任何提示都非常感谢..
使用下面的精度召回图,其中召回在x轴上,精度在y轴上,我可以使用此公式来计算给定精度,召回阈值的预测数吗?
这些计算基于橙色趋势线。
假设此模型已在100个实例上进行了训练,并且是二进制分类器。
召回值为0.2时(0.2 * 100)= 20个相关实例。在召回值为0.2时,精度= .95,所以真实阳性的数量(20 * .95)=19。这是从精确召回图中计算真实阳性的数量的正确方法吗?
classification machine-learning precision-recall data-science
我有一个名为“日”的日期列,例如,2019/07/22如果我想创建一个自定义字段,将该日期转换为一周中的实际日期,例如星期日或星期一,这怎么可能?我似乎找不到适用于 presto sql 的方法。
感谢您的关注
shapley 支持逻辑回归模型吗?
运行以下代码我得到:
logmodel = LogisticRegression()
logmodel.fit(X_train,y_train)
predictions = logmodel.predict(X_test)
explainer = shap.TreeExplainer(logmodel )
Exception: Model type not yet supported by TreeExplainer: <class 'sklearn.linear_model.logistic.LogisticRegression'>
Run Code Online (Sandbox Code Playgroud)
PS 你应该对不同的模型使用不同的解释器
python machine-learning logistic-regression data-science shap
主要问题:为什么 Lasso 回归的系数不会通过 最小化而缩小到零scipy.minimize?
我正在尝试使用 scipy.minimize 创建套索模型。然而,它仅在 alpha 为零时才起作用(因此仅像基本平方误差一样)。当 alpha 不为零时,它会返回更差的结果(更高的损失),并且仍然没有一个系数为零。
我知道 Lasso 是不可微分的,但我尝试使用 Powell 优化器,它应该处理非微分损失(我也尝试过 BFGS,它应该处理非平滑)。这些优化器都不起作用。
为了测试这一点,我创建了数据集,其中 y 是随机的(此处提供是可重现的),X 的第一个特征恰好是 y*.5,其他四个特征是随机的(此处也提供是可重现的)。我希望算法将这些随机系数缩小到零并只保留第一个系数,但它没有发生。
对于套索损失函数,我使用本文中的公式(图 1,第一页)
我的代码如下:
from scipy.optimize import minimize
import numpy as np
class Lasso:
def _pred(self,X,w):
return np.dot(X,w)
def LossLasso(self,weights,X,y,alpha):
w = weights
yp = self._pred(X,w)
loss = np.linalg.norm(y - yp)**2 + alpha * np.sum(abs(w))
return loss
def fit(self,X,y,alpha=0.0):
initw = np.random.rand(X.shape[1]) #initial weights
res = minimize(self.LossLasso,
initw,
args=(X,y,alpha),
method='Powell')
return res
if __name__=='__main__': …Run Code Online (Sandbox Code Playgroud) machine-learning lasso-regression scipy data-science loss-function
我在安装惊喜包时使用以下命令。我在安装时收到错误消息,但我无法理解。我需要帮助才能成功安装此软件包。 pip 安装 scikit-惊喜
最后一个错误代码表示需要 Microsoft Visual C++ 14 或更高版本,但我安装了 14 版本,因此应该满足要求。 控制面板的屏幕截图
(base) C:\Users\S Vishal>pip install scikit-surprise
Collecting scikit-surprise
Using cached scikit-surprise-1.1.1.tar.gz (11.8 MB)
Requirement already satisfied: joblib>=0.11 in c:\programdata\anaconda3\lib\site-packages (from scikit-surprise) (0.17.0)
Requirement already satisfied: numpy>=1.11.2 in c:\programdata\anaconda3\lib\site-packages (from scikit-surprise) (1.19.2)
Requirement already satisfied: scipy>=1.0.0 in c:\programdata\anaconda3\lib\site-packages (from scikit-surprise) (1.5.2)
Requirement already satisfied: six>=1.10.0 in c:\programdata\anaconda3\lib\site-packages (from scikit-surprise) (1.15.0)
Building wheels for collected packages: scikit-surprise
Building wheel for scikit-surprise (setup.py) ... error
ERROR: Command errored out with exit …Run Code Online (Sandbox Code Playgroud) data-science ×10
python ×5
anaconda ×1
apache-spark ×1
csv ×1
dataframe ×1
date ×1
pandas ×1
presto ×1
pyspark ×1
r ×1
scikit-learn ×1
scipy ×1
shap ×1
sql ×1
sqlite ×1
trino ×1
valueerror ×1
web-scraping ×1