Showing posts with label dmx. Show all posts
Showing posts with label dmx. Show all posts

Wednesday, March 21, 2012

DMX vs Visual Studio

Hi

Are there any (important?) advantages of using data mining through DMX instead of Visual Studio 2005 on the SQL server 2005?

/Dennis

DMX is the only solution for querying the mining models, and BI Dev Studio also uses DMX in the prediction query builder.

In general, as far as mining object manipulation is concerned, DMX and the XMLA-based Analysis Services Scripting Language (aka DDL or ASSL), the script used by BI Dev Studio, have similar features.

There are a few differences, however, mostly deriving from the fact that DMX is designed as an extension for SQL, for application developers and, therefore, it is more concise (so that it can be embedded or generated by applications).

Some DDL features not supported by DMX:

full control over the metadata of mining objects. Properties such as Description, bindings, name bindings are only supported in DDL and not in DMX

DMX Tutorials for AdventureWorks

Can anybody help me find a comprehensive tutorial on DMX executed against the AdventureWorks database on Analysis Services on SQL Server 2005?We don't have a dedicated DMX tutorial available currently but the DMX reference in Books Online as well as the Tips & Tricks section at www.sqlserverdatamining.com would be good resources to start with.

DMX to read cluster characteristics

Hi,

Can you send me or point me to a DMX code to read cluster characteristics programatically ?

Thanks,

The information displayed in the Cluster Characteristics viewer is available through a stored procedure call.

CALL System.Microsoft.AnalysisServices.System.DataMining.Clustering.GetClusterCharacteristics('Table1_CL','001',0.0005)

The first parameter is the model name, the second is the NODE_UNIQUE_NAME for the cluster whose characteristics are to be rendered and the last parameter is a threshold.

You can get the list of all clusters and their associated NODE_UNIQUE_NAME with a query like:

SELECT NODE_UNIQUE_NAME, NODE_CAPTION, NODE_DESCRIPTION, NODE_TYPE FROM [Table1_CL].CONTENT WHERE NODE_TYPE=5

(NODE_TYPE=5 identifies a Cluster node)

Hope this helps

|||

Hi Bogdan,

This worked greart. Thanks.

Can you also let me know the online material or book where I can get some more information of this kind about DMX to access information from SSAS DataMining model ? We are looking forward to write more of such codes to get information from the mining model programatically.

Thanks,

Vikas

|||

There isn't a lot of documentation on the stored procedures that retrieve summarized/derived information from the algorithms. All of the information is derived from the content (i.e. SELECT * FROM <model>.CONTENT). You can use SQL Profiler to inspect the queries that are sent from the viewers to the server to access the syntax and how the sprocs are called. Also, you can look at the sample thin client viewer code that ships with the product to see the characteristic and discrimination calls against clustering and naive bayes models.

To get a better idea of how the content looks per algorithm, you can download a sample plug-in viewer we wrote from http://www.sqlserverdatamining.com/DMCommunity/Downloads/Links_LinkRedirector.aspx?id=1349. This viewer provides a nicer interface for navigating generic content, decoding node types and value types and such.

|||

Here's one way of getting the characteristics that distinguish a cluster. Feedback welcome:

http://www.codeplex.com/ASStoredProcedures/Wiki/View.aspx?title=ClusterNaming&referringTitle=Home

DMX to read cluster characteristics

Hi,

Can you send me or point me to a DMX code to read cluster characteristics programatically ?

Thanks,

The information displayed in the Cluster Characteristics viewer is available through a stored procedure call.

CALL System.Microsoft.AnalysisServices.System.DataMining.Clustering.GetClusterCharacteristics('Table1_CL','001',0.0005)

The first parameter is the model name, the second is the NODE_UNIQUE_NAME for the cluster whose characteristics are to be rendered and the last parameter is a threshold.

You can get the list of all clusters and their associated NODE_UNIQUE_NAME with a query like:

SELECT NODE_UNIQUE_NAME, NODE_CAPTION, NODE_DESCRIPTION, NODE_TYPE FROM [Table1_CL].CONTENT WHERE NODE_TYPE=5

(NODE_TYPE=5 identifies a Cluster node)

Hope this helps

|||

Hi Bogdan,

This worked greart. Thanks.

Can you also let me know the online material or book where I can get some more information of this kind about DMX to access information from SSAS DataMining model ? We are looking forward to write more of such codes to get information from the mining model programatically.

Thanks,

Vikas

|||

There isn't a lot of documentation on the stored procedures that retrieve summarized/derived information from the algorithms. All of the information is derived from the content (i.e. SELECT * FROM <model>.CONTENT). You can use SQL Profiler to inspect the queries that are sent from the viewers to the server to access the syntax and how the sprocs are called. Also, you can look at the sample thin client viewer code that ships with the product to see the characteristic and discrimination calls against clustering and naive bayes models.

To get a better idea of how the content looks per algorithm, you can download a sample plug-in viewer we wrote from http://www.sqlserverdatamining.com/DMCommunity/Downloads/Links_LinkRedirector.aspx?id=1349. This viewer provides a nicer interface for navigating generic content, decoding node types and value types and such.

|||

Here's one way of getting the characteristics that distinguish a cluster. Feedback welcome:

http://www.codeplex.com/ASStoredProcedures/Wiki/View.aspx?title=ClusterNaming&referringTitle=Home

DMX Shape query error

Hi I created a DMX query to retrieve predictions based on previous customer purchases and wanted to filter out my input data by only purchases made in the current year. I keep receiving this error:

Code Snippet

===================================

Internal error: An unexpected error occurred (file 'dmxinit.cpp', line 1343, function 'DMXNodeInput::InitFromASTOpenRowset'). (Microsoft SQL Server 2005 Analysis Services)


Program Location:

at Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Microsoft.AnalysisServices.AdomdClient.IExecuteProvider.Execute(ICommandContentProvider contentProvider, AdomdPropertyCollection commandProperties, IDataParameterCollection parameters)
at Microsoft.AnalysisServices.AdomdClient.AdomdCommand.Execute()
at Microsoft.AnalysisServices.Controls.QueryResultGridStorage.ThreadProc()

And, here's my query:

Code Snippet

SELECTFLATTENED

(SELECT *

FROMPredictAssociation([PredictTable],

10,

INCLUDE_NODE_ID,

INCLUDE_STATISTICS

)

WHERE$NODEID <> ''

)

FROM

[Mining Model]

NATURALPREDICTIONJOIN

SHAPE {

OPENQUERY( [datasrc],

'SELECT ''1234'' AS [Customer_D_SID]'

)

} APPEND ({

SHAPE {

OPENQUERY( [datasrc],

'SELECT [Product_D_SID],[Customer_D_SID], [Transaction_Date]

FROM [Base_Sales_F]

WHERE [Customer_D_SID] = ''1234'' '

)

} APPEND ({

OPENQUERY( [datasrc],

'SELECT [Calendar_D_SID],[CALENDAR_YR_NBR]

FROM [dbo].[Calendar_D]

WHERE [CALENDAR_YR_NBR] >= ''2007'' '

)

} RELATE [Calendar_D_SID] TO [Transaction_Date]) AS B

} RELATE B.[Customer_D_SID] TO [Customer_D_SID]) AS [PredictTable]

AS T

I figured the only way to associate the calendar table with the sales table was to use a nested shape statement... is this wrong? Thanks for any help!

The internal error is being raised because your SHAPE statement is generating 2 levels of nesting which doesn't match your model defnition (SQL Server DM only supports single-level nesting i.e. nested tables cannot have table columns).

You need to remove the second nested join and instead, use a view on the transaction table that includes the column (CALENDAR_YR_NBR) you want to filter on.

|||Thank you! Making a view solved my problem.sql

DMX Query, Group by

I'm having some problem with this DMX prediction query. This is the first time I'm trying out the GROUP BY statement in the DMX query and I keep getting "Parse: the statement dialect could not be resolved due to ambiguity." message.

Is Group By supported by the DMX? What am I missing? If not supported, could I insert the result into a temporary table using SELECT ... INTO.. FROM and run a group by on a temporary table?

This is what the DMX query looks like...

SELECT
t.[AgeGroupName],
t.[ChildrenStatusName],
t.[EducationName],
Sum(t.[Profit]) as Profit
From
[Revenue Estimate DT]
PREDICTION JOIN
OPENQUERY([DM Reports DM],
'SELECT
[AgeGroupName],
[ChildrenStatusName],
[EducationName],
[Profit],
[IncomeName],
[HomeOwnerName],
[SexName],
[Country],
[ProductTypeCode],
[ProductName],
[MailCount],
[OrderAmount],
[SalesAmount],
[MailCost]
FROM
(SELECT AgeGroupName, ChildrenStatusName, EducationName, IncomeName, HomeOwnerName, MaritalStatusName, SexName, JobName, JobTypeCode,
CompanyTypeCode, Country, ProductTypeCode, ProductName, SUM(MailCount) AS MailCount, SUM(OrderAmount) AS OrderAmount, SUM(SalesAmount)
AS SalesAmount, SUM(MailCost) AS MailCost, SUM(Profit) AS Profit, MIN(RevenueEstimateID) AS ReKey
FROM [DataMining.RevenueEstimate.Predict]
GROUP BY AgeGroupName, ChildrenStatusName, EducationName, IncomeName, HomeOwnerName, MaritalStatusName, SexName, JobName, JobTypeCode,
CompanyTypeCode, Country, ProductTypeCode, ProductName, ClientID
HAVING (ClientID = 1)) as [Prediction]
') AS t
ON
[Revenue Estimate DT].[Age Group Name] = t.[AgeGroupName] AND
[Revenue Estimate DT].[Education Name] = t.[EducationName] AND
[Revenue Estimate DT].[Income Name] = t.[IncomeName] AND
[Revenue Estimate DT].[Home Owner Name] = t.[HomeOwnerName] AND
[Revenue Estimate DT].[Sex Name] = t.[SexName] AND
[Revenue Estimate DT].[Country] = t.[Country] AND
[Revenue Estimate DT].[Product Type Code] = t.[ProductTypeCode] AND
[Revenue Estimate DT].[Product Name] = t.[ProductName] AND
[Revenue Estimate DT].[Mail Count] = t.[MailCount] AND
[Revenue Estimate DT].[Order Amount] = t.[OrderAmount] AND
[Revenue Estimate DT].[Sales Amount] = t.[SalesAmount] AND
[Revenue Estimate DT].[Mail Cost] = t.[MailCost] AND
[Revenue Estimate DT].[Profit] = t.[Profit] AND
[Revenue Estimate DT].[Children Status Name] = t.[ChildrenStatusName]
GROUP BY t.[AgeGroupName],
t.[ChildrenStatusName],
t.[EducationName]

Hello

GROUP BY is not supported in DMX, and neither are temporary tables. A solution would be to execute the query, store the results inside SQL Server, then execute the group by inside the relational engine.

You can find some details on executing predictions from the relational engine in this article: http://www.sqlserverdatamining.com/DMCommunity/TipsNTricks/3914.aspx

|||Or you could do as Bogdan suggests without storing the results and performing SQL operations on an OPENROWSET DMX query result

dmx query probablity ?

CREATE MINING MODEL mortgage
(
[id] long key,
Edu_Status long DISCRETE,
Work_Status long DISCRETE,
age long CONTINUOUS,
asset_value long CONTINUOUS,
Net_income long CONTINUOUS,
paid_Status long DISCRETE PREDICT
)USING MICROSOFT_DECISION_TREES

i have a mining model above and i am designing a web cross ablication to see probablity of the a costumers' paid status.can you write for me dmx command for selecting paid status that have same criteria(ex;age=30 net income=2000,Edu_status=college) and when i write dxm window(select * from [paid_Status] ) it only shows "4" one row one column why ? as you see i dont know

dmx and datamining well..:)

string dxmcommand = "";

private AdomdCommand ascommand = new AdomdCommand();

private AdomdConnection asconnection=new AdomdConnection();

private AdomdDataReader asreader=new AdomdDataReader();

ascommand.CommandText = dmxcommand;

if I understand your question correctly, then the query would be something like:

SELECT Paid_Status, PredictProbability(Paid_Status)

FROM mortgage NATURAL PREDICTION JOIN

(SELECT 30 AS Age, 2000 as Net_Income ) AS T

This query will return the predicted value for Paid_Status as well as the proability for that prediction. Note that I did not include "College" as Edu_status. The reason is that the Edu_status column of the mining model is defined as "LONG DISCRETE" and "College" is a string, so it cannot be mapped to a long. You will have to convert "College" to the numeric code which I suppose it is used in describing this string, then add "<Numeric_Code_For_College> AS Edu_Status" to the query

Also, in C#, the sequence of operations should be along this line:

AdomdConnection cn = new AdomdConnection();

cn.ConnectionString = "Data Source=localhost; Initial Catalog=<Your Database>";

cn.Open(); // open the connection

AdomdCommand cmd = new AdomdCommand();

cmd.Connection = cn; // associate the command with the current connection

cmd.CommandText = dmxcommand;

AdomdDataReader rdr = cmd.ExecuteReader(); // obtain the reader from the command execution instead of creating it with new

Hope this helps

DMX Query for regression coefficients

How do I write a DMX query to return the coefficients of the independent variables in my regression equation?

Thanks,

Carrie

All algorithm content is in the content schema rowset available through

SELECT * FROM <model name>.CONTENT

Although the schema is the same for all algorithms, each uses the schema slightly differently. The schema itself is difficult to decode, but you can download a plug-in viewer from http://www.sqlserverdatamining.com/dmcommunity/_downloads/1348.aspx that decodes all the types/etc into their parts. Once you do this, you will see what columns/etc you need from the content.

|||

We do not have the sgKey.snk file. Can we generate one? If so how?

Cryptographic failure while signing assembly 'C:\Documents and Settings\dtm\My Documents\dot net examples\Generic Content Viewer\GenericContentTreeViewerSetup\obj\Debug\GenericContentTreeView.dll' -- 'Error reading key file 'c:\Documents and Settings\dtm\My Documents\dot net examples\Generic Content Viewer\GenericContentTreeViewerSetup\sgKey.snk' -- The system cannot find the file specified. '

Thanks

|||Something happened to the download - the snk file isn't the only one missing - we're looking into it. However, the setup should have installed the viewer anyway, so you should see it in BI Dev Studio, did it not?|||

I understand the content viewer now. I thought maybe I was looking for something different but now I see.

Three more questions:

1. My regressor variable has three values associated with it. I understand the first (the coefficient in the regression equation) and the third, used to calculate the constant - but what is the second value? A screenshot would probably be more helpful.

2. How do I set an input variable to regressor in the mining wizard. It is not listed as a modeling flag option. If I have more than one regressor - will both regressors be included as part of the regression equation?

3. In my regression trees, if a node does not have a regression equation associated with it, is the model overtrained? How do I interpret these results?

Thanks so much,

Carrie

|||

1: I don't have it in front of me right now, so a screenshot would help :)

2: When you create a decision tree with continuous inputs and outputs, I believe the wizard automatically marks all continuous values as REGRESSOR. You can verify this by going to the Mining Models pane in the Data Mining designer. Click on a column name under the mining model (not the mining structure) and look at its properties in the property panel. This is where you can set algorithm-specific modeling flags, and where you would set or clear the REGRESSOR flag.

3. I wouldn't say it was necessarily overtrained, just that there were no significant regressors for that node. For example, assume I had a bunch of demographic data including Age and IQ as my only continuous values and I tried to predict either one. Statistically speaking, they should be independent and there shouldn't be any regressions - just constants. That being said, and since it may not be the case for your model, there are a couple of options open to you. If you think the model may be overfitting, you can increase the MINIMUM_SUPPORT parameter, or the COMPLEXITY_PENALTY parameter. Both of these have the impact of reducing the size of your tree. Additionally, the decision tree algorithm has a FORCE_REGRESSOR parameter allowing you to specify a regressor that will be included in any regression, regardless of how minimal its contribution

|||Is there a dmx query that will return the actual numeric value of the diamond (residual) in each node of the regression tree?|||I am just making sure my question is still in the cue....thanks|||

Assuming your model name was "cp" and your attribute name was "IQ", I think this is the query you want

select FLATTENED NODE_CAPTION,
NODE_NAME,
(select ATTRIBUTE_VALUE AS mean,
[VARIANCE] as [variance]
from NODE_DISTRIBUTION WHERE VALUETYPE=3)
as stats
from cp.content WHERE ATTRIBUTE_NAME='IQ'

DMX Query for regression coefficients

How do I write a DMX query to return the coefficients of the independent variables in my regression equation?

Thanks,

Carrie

All algorithm content is in the content schema rowset available through

SELECT * FROM <model name>.CONTENT

Although the schema is the same for all algorithms, each uses the schema slightly differently. The schema itself is difficult to decode, but you can download a plug-in viewer from http://www.sqlserverdatamining.com/dmcommunity/_downloads/1348.aspx that decodes all the types/etc into their parts. Once you do this, you will see what columns/etc you need from the content.

|||

We do not have the sgKey.snk file. Can we generate one? If so how?

Cryptographic failure while signing assembly 'C:\Documents and Settings\dtm\My Documents\dot net examples\Generic Content Viewer\GenericContentTreeViewerSetup\obj\Debug\GenericContentTreeView.dll' -- 'Error reading key file 'c:\Documents and Settings\dtm\My Documents\dot net examples\Generic Content Viewer\GenericContentTreeViewerSetup\sgKey.snk' -- The system cannot find the file specified. '

Thanks

|||Something happened to the download - the snk file isn't the only one missing - we're looking into it. However, the setup should have installed the viewer anyway, so you should see it in BI Dev Studio, did it not?|||

I understand the content viewer now. I thought maybe I was looking for something different but now I see.

Three more questions:

1. My regressor variable has three values associated with it. I understand the first (the coefficient in the regression equation) and the third, used to calculate the constant - but what is the second value? A screenshot would probably be more helpful.

2. How do I set an input variable to regressor in the mining wizard. It is not listed as a modeling flag option. If I have more than one regressor - will both regressors be included as part of the regression equation?

3. In my regression trees, if a node does not have a regression equation associated with it, is the model overtrained? How do I interpret these results?

Thanks so much,

Carrie

|||

1: I don't have it in front of me right now, so a screenshot would help :)

2: When you create a decision tree with continuous inputs and outputs, I believe the wizard automatically marks all continuous values as REGRESSOR. You can verify this by going to the Mining Models pane in the Data Mining designer. Click on a column name under the mining model (not the mining structure) and look at its properties in the property panel. This is where you can set algorithm-specific modeling flags, and where you would set or clear the REGRESSOR flag.

3. I wouldn't say it was necessarily overtrained, just that there were no significant regressors for that node. For example, assume I had a bunch of demographic data including Age and IQ as my only continuous values and I tried to predict either one. Statistically speaking, they should be independent and there shouldn't be any regressions - just constants. That being said, and since it may not be the case for your model, there are a couple of options open to you. If you think the model may be overfitting, you can increase the MINIMUM_SUPPORT parameter, or the COMPLEXITY_PENALTY parameter. Both of these have the impact of reducing the size of your tree. Additionally, the decision tree algorithm has a FORCE_REGRESSOR parameter allowing you to specify a regressor that will be included in any regression, regardless of how minimal its contribution

|||Is there a dmx query that will return the actual numeric value of the diamond (residual) in each node of the regression tree?|||I am just making sure my question is still in the cue....thanks|||

Assuming your model name was "cp" and your attribute name was "IQ", I think this is the query you want

select FLATTENED NODE_CAPTION,
NODE_NAME,
(select ATTRIBUTE_VALUE AS mean,
[VARIANCE] as [variance]
from NODE_DISTRIBUTION WHERE VALUETYPE=3)
as stats
from cp.content WHERE ATTRIBUTE_NAME='IQ'

DMX Query examples

Can you give an example on how exactly to write each of the following? (I am clearly not a programmer :))

TopCount ( <table expr>,<rank expr>,<n-items>) =

TopPercent ( <table expr>,<rank expr>,<percent>) =

PredictTimeSeries ( <table expr>,<n1>,<n2>) =

PredictAssociation ( <table expr>,<n>) =

Thanks,

Carrie

SELECT TopCount(PredictHistogram(MyAttribute),$Probability,3), // returns top 3 values by probability
TopPercent(PredictHistogram(MyAttribute),$Support,0.20) // returns top values that contain at least 20% of the total support
FROM MyModel
PREDICTION JOIN
...

SELECT PredictTimeSeries(MyNestedTableTimeSeriesColumn, 2, 5) // predicts steps 2-5 in the series
FROM MyTimeSeriesModel

SELECT PredictAssociation(MyNestedTable, 5) // returns top 5 associated items
FROM My Model
PREDICTION JOIN
...

|||

So I did.....

select TopCount(PredictHistogram(Returnwithplay),$Support,.20)

From [REC FT All Cube DT]

PREDICTION JOIN

And received the following ( I think the query completed with errors):

Executing the query ...

Parser: The end of the input was reached.

Execution complete

|||And I tried

select PredictTimeSeries([Slot Theo Win],2,5) FROM [Player Market]

and received the following error:

Executing the query ...

Error (Data mining): The specified DMX column was not found in the context at line 1, column 26.

Execution complete

My time series is set up as the following.......

Player Market:

Date Dim Predict

Day Key

Rated Slot Theo Predict Only

Rated Table Theo Predict Only

Player Market Dim Key

|||

PredictTimeSeries only works on models using the Microsoft_Time_Series algorithm. Also, it doesn't seem that you have a column called "Slot Theo Win" in your data set.

It seems you would need a model somewhat like

CREATE MINING MODEL [Player Market]
(
DateDim DATE KEY TIME,
PlayerMarketDim TEXT KEY,
RatedSlotTheo DOUBLE CONTINUOUS PREDICT_ONLY,
RatedSlotTheo DOUBLE CONTINUOUS PREDICT_ONLY
) USING Microsoft_Time_Series

sql

Monday, March 19, 2012

DMX query and ASP.Net

I am trying to get along with SQL server 2005, made the mining model and i use this DMX query to get the time series prediction. Now this is working and i get results in SQL server management studio. I cant get predection result in to aspx. I found this article but still...nothing

http://www.aspnetpro.com/newsletterarticle/2004/10/asp200410ri_l/asp200410ri_l.asp

After spending some weeks of testing and reading I came up with this:

Itsa part of the code of cross web application, I managed to make a modelof timeseries in SQL server and I have hopefully (since I dont get anyerrors) run my dmx query through aspx. BUT I can get the result todisplay in aspx. My guess is because the original code was made forstring variables and I am tring to get numeric variables in it. Isuppose that all I need to do is to get the result from the DMX queryin the array

'Connect to Analysis Server and execute query
Dim asSession As New AnalysisServerSession
asSession.Connect()
If False = asSession.ExecuteAndFetchResult(strDMX) Then
Return
End If


'Read prediction results and build list of recommendations
vRecommendedItems.Clear()
While asSession.asDataReader.Read()
Dim type As String = asSession.asDataReader.GetDataTypeName(0)
' If type = "DBTYPE_WVARCHAR" Or type = "String" Then

If type = "String" Then
Try
Dim val As string = asSession.asDataReader.GetString(0)
vRecommendedItems.Add(val)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End If
End While

And here is my DMX query

Private Shared Sub GetRecommendations( _
ByVal vInputItems As ArrayList, _
ByRef vRecommendedItems As ArrayList)

'Templates for generating DMX prediction join statement
Dim strDMX As String = _
"SELECT PredictTimeSeries([Apot Sales],5)" + _
"FROM [Sales]"

********************************

I would appriciate any answers since this project is for my diploma and I really cant seem to get through

Thanks

Try changing

"SELECT PredictTimeSeries([Apot Sales],5)" + _
"FROM [Sales]

to

"SELECT PredictTimeSeries([Apot Sales],5)AS 'APOT' FROM Sales"

Giving the column a name should allow it to be displayed.

DMX query and ASP

I am trying to get along with SQL server 2005, just made the mining model and i use this DMX query to get the time series prediction. Now this is working and i get results in SQL server management studio.

SELECT PredictTimeSeries([Apot Sales],5)

FROM [Sales Bycom]

I tried running this as a query in ASP but obviously this can't be done

Here is my question. I have made an SQL server connection in ASP. But how can I get the prediction results displayed in to ASP?

Thanx

You will need to make an Analysis Server connection to execute the DMX query from ASP. Take a look at the code download at the bottom of this article for an example of how to use DMX queries from ASP: http://www.aspnetpro.com/newsletterarticle/2004/10/asp200410ri_l/asp200410ri_l.asp.|||Ok thanx I will check it out|||After spending some weeks of testing and reading I came up with this:

Its a part of the code of cross web application, I managed to make a model of timeseries in SQL server and I have hopefully (since I dont get any errors) run my dmx query through aspx. BUT I can get the result to display in aspx. My guess is because the original code was made for string variables and I am tring to get numeric variables in it. I suppose that all I need to do is to get the result from the DMX query in the array

'Connect to Analysis Server and execute query
Dim asSession As New AnalysisServerSession
asSession.Connect()
If False = asSession.ExecuteAndFetchResult(strDMX) Then
Return
End If

'Read prediction results and build list of recommendations
vRecommendedItems.Clear()
While asSession.asDataReader.Read()
Dim type As String = asSession.asDataReader.GetDataTypeName(0)
' If type = "DBTYPE_WVARCHAR" Or type = "String" Then

If type = "String" Then
Try
Dim val As string = asSession.asDataReader.GetString(0)
vRecommendedItems.Add(val)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End If
End While

And here is my DMX query

Private Shared Sub GetRecommendations( _
ByVal vInputItems As ArrayList, _
ByRef vRecommendedItems As ArrayList)

'Templates for generating DMX prediction join statement
Dim strDMX As String = _
"SELECT PredictTimeSeries([Apot Sales],5)" + _
"FROM [Sales]"

********************************

I would appriciate any answers since this project is for my diploma and I really cant seem to get through

Thanks

|||What error(s) are you seeing? Keep in mind that PredictTimeSeries(<col>, N) returns a table with two columns - the first column is a time index ($TIME) and the second column contains the predicted values for the column you're predicting.|||Thanks Raman Iyer , The weird thing is that I dont get any errors neither any results

in the place where the results appear I get "Microsoft.AnalysisServices.AdomdClient.AdomdDataReader"

here is the whole code from predict.vb.asp

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports Microsoft.AnalysisServices.AdomdClient

Namespace MovieCrossSellApplication

Partial Public Class ShoppingBasket_Recommendations
Inherits System.Web.UI.Page

Protected Overrides Sub OnInit(ByVal e As EventArgs)
'
' CODEGEN: This call is required by the ASP.NET Web Form Designer.
'
InitializeComponent()
MyBase.OnInit(e)
End Sub 'OnInit

'/ <summary>
'/ Required method for Designer support - do not modify
'/ the contents of this method with the code editor.
'/ </summary>
Private Sub InitializeComponent()
End Sub 'InitializeComponent

Private Shared Sub GetRecommendations( _
ByVal vInputItems As ArrayList, _
ByRef vRecommendedItems As ArrayList)

'Templates for generating DMX prediction join statement
Dim strDMX As String = _
"SELECT PredictTimeSeries([Apot Sales],5) " + _
"FROM [Sales] "

' "SELECT FLATTENED TopCount(" + _
' "Predict([Customer Movies], INCLUDE_STATISTICS)," + _
' "$AdjustedProbability, 5) From [Movie Recommendations] " + _
' "NATURAL PREDICTION JOIN (SELECT ("
'Dim strDMX2 As String = ") AS [Customer Movies]) AS t"

'Iterate shopping basket and produce input case
'Dim cItems As Integer = vInputItems.Count
' Dim strDMX As String = ""
' Dim i As Integer
'For i = 0 To cItems - 1
' Dim item As String = vInputItems(i).ToString()
' item = item.Replace("’", "’’")
'strDMX += "SELECT " + "'" + item + "' AS " + "[Movie]"
' If i < cItems - 1 Then
' strDMX += " UNION "
'End If
'Next i

'Put together DMX prediction query to get 5 recommendations
'strDMX = strDMX1 + strDMX '+ strDMX2

'Connect to Analysis Server and execute query
Dim asSession As New AnalysisServerSession
asSession.Connect()
If False = asSession.ExecuteAndFetchResult(strDMX) Then
Return
End If

'Read prediction results and build list of recommendations
vRecommendedItems.Clear()
While asSession.asDataReader.Read()
Dim type As String = asSession.asDataReader.GetDataTypeName(0)
' If type = "DBTYPE_WVARCHAR" Or type = "String" Then

'If type = "String" Then
Try
Dim val As string = asSession.asDataReader.GetString(0)
vRecommendedItems.Add(val)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
'End If
End While

'Disconnect from Analysis Server
asSession.DisConnect()

End Sub 'GetRecommendations

Public Sub Button1_Click( _
ByVal sender As Object, _
ByVal e As System.EventArgs) 'Handles Me.Button1.Click

' Parse the input into an ArrayList of strings.
Dim alInputItems As New ArrayList()
Dim splitchar As Char() = {";"c}
Dim szInputItems As String() = Me.TextBox1.Text.Split(splitchar, 20)
Dim i As Integer
For i = 0 To szInputItems.Length - 1
alInputItems.Add(szInputItems(i).Trim())
Next i

' Add items to the shopping basket
dgShoppingBasket.DataSource = alInputItems
dgShoppingBasket.DataBind()

' Get top 5 recommendations
Dim alRecommendedItems As New ArrayList(5)
GetRecommendations(alInputItems, alRecommendedItems)

' Display recommendations
dgRecommendations.DataSource = alRecommendedItems
dgRecommendations.DataBind()
End Sub 'Button1_Click

End Class 'ShoppingBasket_Recommendations

'
' AnalysisServerSession manages
' - connecting to Analysis Server using ADOMD.NET,
' - executing commands and
' - fetching results
'
' Need to add reference to Microsoft.AnalysisServices.AdomdClient.dll
' (located under Program Files\Microsoft.NET\ADOMD.NET\90).
' You may also change this class to use ADO.NET (System.Data.Oledb)
' instead if neccessary, by replacing the AdomdConnection, AdomdCommand
' and AdomdDataReader with OledbConnection, OledbCommand and
' OledbDataReader. The rest of the code should stay the same.
'
Public Class AnalysisServerSession
Protected asCommand As Microsoft.AnalysisServices.AdomdClient.AdomdCommand
Protected asConnection As Microsoft.AnalysisServices.AdomdClient.AdomdConnection
Public asDataReader As Microsoft.AnalysisServices.AdomdClient.AdomdDataReader
Public szServer As String = "localhost"
Public szCatalog As String = "myDSS"

Public Sub New()
asCommand = Nothing
asConnection = Nothing
asDataReader = Nothing
End Sub 'New

Public Function Connect() As Boolean
Dim asConnectionString As String = _
"Provider=MSOLAP.3;Data Source=" + _
szServer + ";Initial Catalog=" + szCatalog

asConnection = New AdomdConnection(asConnectionString)
asConnection.Open()

Return True
End Function 'Connect

Public Function ExecuteAndFetchResult(ByVal strCommand As string) As Boolean
If asConnection Is Nothing Then
Return False
End If
If asCommand Is Nothing Then
asCommand = New AdomdCommand()
End If
strCommand = strCommand.Replace("NaN", "null")
strCommand = strCommand.Replace("Infinity", "null")

Try
If Not (asDataReader Is Nothing) Then
If Not asDataReader.IsClosed Then
asDataReader.Close()
End If
End If
asCommand.Connection = asConnection
asCommand.CommandText = strCommand
asDataReader = asCommand.ExecuteReader()

Catch e As Exception

Log(e.Message)
Return False
End Try
Return True
End Function 'ExecuteAndFetchResult

Public Function DisConnect() As Boolean
Try
If Not (asConnection Is Nothing) Then
asConnection.Close()
End If
If Not (asCommand Is Nothing) Then
asCommand.Connection = Nothing
End If
If Not (asDataReader Is Nothing) Then
asDataReader.Close()
End If
Catch e As Exception
Console.WriteLine(e.Message)
End Try
Return True
End Function 'DisConnect

Private Sub Log(ByVal message As String)
'Log the message to some place
System.Diagnostics.Debug.Assert(False, message)
Return
End Sub 'Log

End Class 'AnalysisServerSession

End Namespace 'MovieCrossSellApplication

Any help appreciated
|||OK I think I am getting somewhere......

Raman Iyer you should be right I must have 2 collums in order to save the results in an array,
can't figure out how I can do that checked some tutorials but came up with nothing.....

If anyone could help or suggest a web site?

Dim asSession As New AnalysisServerSession
asSession.Connect()
If False = asSession.ExecuteAndFetchResult(strDMX) Then
Return
End If

'Dim vDSSItems(10) as string
While asSession.asDataReader.Read()

Dim val As string = asSession.asDataReader.GetString(0)
vDSSItems.add(val)
end while

DMX query and ASP

I am trying to get along with SQL server 2005, just made the mining model and i use this DMX query to get the time series prediction. Now this is working and i get results in SQL server management studio.

SELECT PredictTimeSeries([Apot Sales],5)

FROM [Sales Bycom]

I tried running this as a query in ASP but obviously this can't be done

Here is my question. I have made an SQL server connection in ASP. But how can I get the prediction results displayed in to ASP?

Thanx

You will need to make an Analysis Server connection to execute the DMX query from ASP. Take a look at the code download at the bottom of this article for an example of how to use DMX queries from ASP: http://www.aspnetpro.com/newsletterarticle/2004/10/asp200410ri_l/asp200410ri_l.asp.|||Ok thanx I will check it out|||After spending some weeks of testing and reading I came up with this:

Its a part of the code of cross web application, I managed to make a model of timeseries in SQL server and I have hopefully (since I dont get any errors) run my dmx query through aspx. BUT I can get the result to display in aspx. My guess is because the original code was made for string variables and I am tring to get numeric variables in it. I suppose that all I need to do is to get the result from the DMX query in the array

'Connect to Analysis Server and execute query
Dim asSession As New AnalysisServerSession
asSession.Connect()
If False = asSession.ExecuteAndFetchResult(strDMX) Then
Return
End If


'Read prediction results and build list of recommendations
vRecommendedItems.Clear()
While asSession.asDataReader.Read()
Dim type As String = asSession.asDataReader.GetDataTypeName(0)
' If type = "DBTYPE_WVARCHAR" Or type = "String" Then

If type = "String" Then
Try
Dim val As string = asSession.asDataReader.GetString(0)
vRecommendedItems.Add(val)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End If
End While

And here is my DMX query

Private Shared Sub GetRecommendations( _
ByVal vInputItems As ArrayList, _
ByRef vRecommendedItems As ArrayList)

'Templates for generating DMX prediction join statement
Dim strDMX As String = _
"SELECT PredictTimeSeries([Apot Sales],5)" + _
"FROM [Sales]"

********************************

I would appriciate any answers since this project is for my diploma and I really cant seem to get through

Thanks|||What error(s) are you seeing? Keep in mind that PredictTimeSeries(<col>, N) returns a table with two columns - the first column is a time index ($TIME) and the second column contains the predicted values for the column you're predicting.|||Thanks Raman Iyer , The weird thing is that I dont get any errors neither any results

in the place where the results appear I get "Microsoft.AnalysisServices.AdomdClient.AdomdDataReader"

here is the whole code from predict.vb.asp

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports Microsoft.AnalysisServices.AdomdClient

Namespace MovieCrossSellApplication

Partial Public Class ShoppingBasket_Recommendations
Inherits System.Web.UI.Page

Protected Overrides Sub OnInit(ByVal e As EventArgs)
'
' CODEGEN: This call is required by the ASP.NET Web Form Designer.
'
InitializeComponent()
MyBase.OnInit(e)
End Sub 'OnInit

'/ <summary>
'/ Required method for Designer support - do not modify
'/ the contents of this method with the code editor.
'/ </summary>
Private Sub InitializeComponent()
End Sub 'InitializeComponent

Private Shared Sub GetRecommendations( _
ByVal vInputItems As ArrayList, _
ByRef vRecommendedItems As ArrayList)

'Templates for generating DMX prediction join statement
Dim strDMX As String = _
"SELECT PredictTimeSeries([Apot Sales],5) " + _
"FROM [Sales] "

' "SELECT FLATTENED TopCount(" + _
' "Predict([Customer Movies], INCLUDE_STATISTICS)," + _
' "$AdjustedProbability, 5) From [Movie Recommendations] " + _
' "NATURAL PREDICTION JOIN (SELECT ("
'Dim strDMX2 As String = ") AS [Customer Movies]) AS t"

'Iterate shopping basket and produce input case
'Dim cItems As Integer = vInputItems.Count
' Dim strDMX As String = ""
' Dim i As Integer
'For i = 0 To cItems - 1
' Dim item As String = vInputItems(i).ToString()
' item = item.Replace("’", "’’")
'strDMX += "SELECT " + "'" + item + "' AS " + "[Movie]"
' If i < cItems - 1 Then
' strDMX += " UNION "
'End If
'Next i

'Put together DMX prediction query to get 5 recommendations
'strDMX = strDMX1 + strDMX '+ strDMX2

'Connect to Analysis Server and execute query
Dim asSession As New AnalysisServerSession
asSession.Connect()
If False = asSession.ExecuteAndFetchResult(strDMX) Then
Return
End If

'Read prediction results and build list of recommendations
vRecommendedItems.Clear()
While asSession.asDataReader.Read()
Dim type As String = asSession.asDataReader.GetDataTypeName(0)
' If type = "DBTYPE_WVARCHAR" Or type = "String" Then

'If type = "String" Then
Try
Dim val As string = asSession.asDataReader.GetString(0)
vRecommendedItems.Add(val)
Catch e As Exception
Console.WriteLine(e.Message)
End Try
'End If
End While

'Disconnect from Analysis Server
asSession.DisConnect()

End Sub 'GetRecommendations

Public Sub Button1_Click( _
ByVal sender As Object, _
ByVal e As System.EventArgs) 'Handles Me.Button1.Click

' Parse the input into an ArrayList of strings.
Dim alInputItems As New ArrayList()
Dim splitchar As Char() = {";"c}
Dim szInputItems As String() = Me.TextBox1.Text.Split(splitchar, 20)
Dim i As Integer
For i = 0 To szInputItems.Length - 1
alInputItems.Add(szInputItems(i).Trim())
Next i

' Add items to the shopping basket
dgShoppingBasket.DataSource = alInputItems
dgShoppingBasket.DataBind()

' Get top 5 recommendations
Dim alRecommendedItems As New ArrayList(5)
GetRecommendations(alInputItems, alRecommendedItems)

' Display recommendations
dgRecommendations.DataSource = alRecommendedItems
dgRecommendations.DataBind()
End Sub 'Button1_Click

End Class 'ShoppingBasket_Recommendations

'
' AnalysisServerSession manages
' - connecting to Analysis Server using ADOMD.NET,
' - executing commands and
' - fetching results
'
' Need to add reference to Microsoft.AnalysisServices.AdomdClient.dll
' (located under Program Files\Microsoft.NET\ADOMD.NET\90).
' You may also change this class to use ADO.NET (System.Data.Oledb)
' instead if neccessary, by replacing the AdomdConnection, AdomdCommand
' and AdomdDataReader with OledbConnection, OledbCommand and
' OledbDataReader. The rest of the code should stay the same.
'
Public Class AnalysisServerSession
Protected asCommand As Microsoft.AnalysisServices.AdomdClient.AdomdCommand
Protected asConnection As Microsoft.AnalysisServices.AdomdClient.AdomdConnection
Public asDataReader As Microsoft.AnalysisServices.AdomdClient.AdomdDataReader
Public szServer As String = "localhost"
Public szCatalog As String = "myDSS"

Public Sub New()
asCommand = Nothing
asConnection = Nothing
asDataReader = Nothing
End Sub 'New

Public Function Connect() As Boolean
Dim asConnectionString As String = _
"Provider=MSOLAP.3;Data Source=" + _
szServer + ";Initial Catalog=" + szCatalog

asConnection = New AdomdConnection(asConnectionString)
asConnection.Open()

Return True
End Function 'Connect

Public Function ExecuteAndFetchResult(ByVal strCommand As string) As Boolean
If asConnection Is Nothing Then
Return False
End If
If asCommand Is Nothing Then
asCommand = New AdomdCommand()
End If
strCommand = strCommand.Replace("NaN", "null")
strCommand = strCommand.Replace("Infinity", "null")

Try
If Not (asDataReader Is Nothing) Then
If Not asDataReader.IsClosed Then
asDataReader.Close()
End If
End If
asCommand.Connection = asConnection
asCommand.CommandText = strCommand
asDataReader = asCommand.ExecuteReader()

Catch e As Exception

Log(e.Message)
Return False
End Try
Return True
End Function 'ExecuteAndFetchResult

Public Function DisConnect() As Boolean
Try
If Not (asConnection Is Nothing) Then
asConnection.Close()
End If
If Not (asCommand Is Nothing) Then
asCommand.Connection = Nothing
End If
If Not (asDataReader Is Nothing) Then
asDataReader.Close()
End If
Catch e As Exception
Console.WriteLine(e.Message)
End Try
Return True
End Function 'DisConnect

Private Sub Log(ByVal message As String)
'Log the message to some place
System.Diagnostics.Debug.Assert(False, message)
Return
End Sub 'Log

End Class 'AnalysisServerSession

End Namespace 'MovieCrossSellApplication

Any help appreciated|||OK I think I am getting somewhere......

Raman Iyer you should be right I must have 2 collums in order to save the results in an array,
can't figure out how I can do that checked some tutorials but came up with nothing.....

If anyone could help or suggest a web site?

Dim asSession As New AnalysisServerSession
asSession.Connect()
If False = asSession.ExecuteAndFetchResult(strDMX) Then
Return
End If

'Dim vDSSItems(10) as string
While asSession.asDataReader.Read()

Dim val As string = asSession.asDataReader.GetString(0)
vDSSItems.add(val)
end while

DMX Query

Hi,

I am having a DMX Query as follows.

SELECT [Englishproductname],( SELECT $TIME, [Profit], PredictVariance([Profit]) FROM PredictTimeSeries([Profit],5)) FROM [ProductSales_Forecast]


It displays as
English productname and the Expression as columns.
The expression consists of time, profit as nested one.

I need to have no nested queries.
I want englishproductname to repeat for all the columns inside the expressions.
I don't want to display as expressions.
Repeatation is not a problem for me.

Plz help in this regard.

Tx in advance

Have you tried :

SELECT FLATTENED [Englishproductname],( SELECT $TIME, [Profit], PredictVariance([Profit]) FROM PredictTimeSeries([Profit],5)) FROM [ProductSales_Forecast]

If I understand correctly your requirements, this should do it

thanks

DMX Queries with MS Time Series

Hi!

I have a table Month_Sales(Month, product_1, .., product_n). The value of column product_i is the sale in this month.

so when i build MS Time Series for this domain, i want to query to find top m product is seld most in next month?

How do i buid that query?

DMX doesn't provide a way to order by the forecast value. However, you should be able to easily do this in client side code. Assuming your model looks like this:

CREATE MINING MODEL SalesForecast(
Product TEXT KEY,
Month LONG KEY TIME,
Sales LONG CONTINUOUS)
USING Microsoft_Time_Series

The following query will return the prediction for the next month for all products:

SELECT Product, Sales from SalesForecast

You can sort the query result by Sales in client code and pick the top N..

DMX in TSQL?

Hi, I'm new to Transact-SQL and I'm trying to throw a DMX query I have created into a stored procedure because I think it's the only way to pass variables into an openquery statement! It seems that no matter what I try gets me the error 'Incorrect usage of quotes'. I'm trying to use code like this:

Code Snippet

AS

BEGIN

DECLARE @.OPENQUERY nvarchar(4000), @.TSQL nvarchar(4000), @.LinkedServer nvarchar(4000)

SET @.LinkedServer = 'DMSERVER'

SET @.OPENQUERY = 'SELECT * FROM OPENQUERY('+ @.LinkedServer + ','''

SET @.TSQL = 'SELECT FLATTENED * FROM ['+@.miningModel+'].CONTENT'')'

EXEC (@.OPENQUERY+@.TSQL)

END

Which I found from some one else's posting on the data mining forums. I'm completely clueless as to how to make this work - Can I even do what I want to do? It seems like the brackets are causing all the fuss, but they're necessary for DMX queries. Any ideas? Thanks!

Code Snippet


AS

BEGIN

DECLARE @.OPENQUERY nvarchar(4000), @.TSQL nvarchar(4000), @.LinkedServer nvarchar(4000)

SET @.LinkedServer = 'DMSERVER'

SET @.OPENQUERY = 'SELECT * FROM OPENQUERY('+ @.LinkedServer + ','''


SET @.TSQL = 'SELECT * FROM ['+@.miningModel+'].CONTENT'')'


EXEC (@.OPENQUERY+@.TSQL)

END


|||

Still doesn't work...here's the error:

Code Snippet

TITLE: Microsoft Report Designer

An error occurred while retrieving the parameters in the query.
SqlCommand.DeriveParameters failed because the SqlCommand.CommandText property value is an invalid multipart name "AS
BEGIN
DECLARE @.OPENQUERY nvarchar(4000), @.TSQL nvarchar(4000), @.LinkedServer nvarchar(4000)
SET @.LinkedServer = 'abc'
SET @.OPENQUERY = 'SELECT * FROM OPENQUERY('+ @.LinkedServer + ','''
SET @.TSQL = 'SELECT * FROM ['+@.miningModel+'].CONTENT'')'
EXEC (@.OPENQUERY+@.TSQL)

END", incorrect usage of quotes.


ADDITIONAL INFORMATION:

SqlCommand.DeriveParameters failed because the SqlCommand.CommandText property value is an invalid multipart name "AS
BEGIN
DECLARE @.OPENQUERY nvarchar(4000), @.TSQL nvarchar(4000), @.LinkedServer nvarchar(4000)
SET @.LinkedServer = 'abc'
SET @.OPENQUERY = 'SELECT * FROM OPENQUERY('+ @.LinkedServer + ','''
SET @.TSQL = 'SELECT * FROM ['+@.miningModel+'].CONTENT'')'
EXEC (@.OPENQUERY+@.TSQL)

END", incorrect usage of quotes. (System.Data)


BUTTONS:

OK


|||are you initializing the variable @.miningModel?

|||

I have it defined as a report parameter in reporting svcs, with default value of 'PRRelational'... Even if I make it a local variable it still throws the same error...

EDIT: Turns out I was doing this from the wrong location...! Thanks. Will post if I get it to work.

EDIT2: Post shows how to do this: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1676053&SiteID=1&mode=1

DMX from Java

My preferred programming language is Java (sorry Microsoft). I've searched for examples of running DMX queries into an Analysis Services database from Java but failed to locate any. I've seen suggestions that XMLA could be used but again, I can't locate any examples (in any language). For my current project I ran up the white flag and used C# instead but this wouldn't be an option in other cases. It would be possible to make the DMX calls from C# objects and call those from Java but that's pretty labourious to code.

Suggestions?

have you tried the XMLA Thin Client sample at http://www.sqlserverdatamining.com/DMCommunity/LiveSamples/124.aspx ?

|||I found that page but I didn't find any code sample to go with it.|||There's an old(er) code sample here http://www.sqlserverdatamining.com/DMCommunity/SQLServer2000/Links_LinkRedirector.aspx?id=96