我有一个包含三列类型/名称/价格的数据集,并希望根据类型和名称来预测价格。
此处的类型/名称是分类字符串值。价格是数字目标变量。
我的数据集看起来像:
Type Name Price
A ec1 1.5
B ec2 2
A ec2 3
C ec1 1
B ec3 1
我必须为此数据集创建一个模型,并要预测类型/名称。
Type-A和Name ec2的预计价格是多少?
您能否提供示例代码。
同样,数据集将没有固定的列数。只有目标变量固定为价格。自变量可能具有“类型/名称/日期..etc”字段。
最佳答案
我将字符串值转换为数字以适合线性模型
from sklearn.linear_model import LinearRegression
from sklearn.feature_extraction import DictVectorizer
import StringIO
data ='''Type,Name,Price
A,ec1,1.5
B,ec2,2
A,ec2,3
C,ec1,1
B,ec3,1'''
df = pd.read_csv(StringIO.StringIO(data))
mapping = {}
cols = df.drop('Price', axis=1).columns
for col in cols:
mapping[col] = {name: i for i, name in enumerate(df[col].unique())}
def mapping_func(row):
return pd.Series([mapping[col][row[col]] for col in cols])
X = df.apply(mapping_func, axis=1)
y = df['Price']
model = LinearRegression()
model.fit(X, y)
print model.predict([ mapping['Type']['B'], mapping['Name']['ec2']] )
输出:
[ 1.57692308]
关于python - python中线性回归中的字符串预测,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46588660/