How to predict multiple attributes in java using weka api? - java

I have a question about how to make multiple attribute predictions using weka in java.
I have this dataset:
MONTH,LOC,CLASS,METHOD,MGOD,CGOD
1,2115,9,192,1,1
2,2115,9,192,1,1
3,2115,9,192,1,1
4,2387,9,210,2,1
5,2356,9,208,2,1
6,2356,9,208,2,1
7,2510,9,219,2,2
8,2348,9,206,2,1
9,2356,9,206,2,1
10,2356,9,206,2,1
11,2051,7,172,2,0
12,2051,7,172,2,0
13,2048,7,172,2,0
14,2048,7,172,2,0
15,2083,7,173,1,0
16,2083,7,173,1,0
17,2143,7,171,1,0
18,2143,7,171,1,0
19,1909,7,155,1,0
20,1909,7,155,1,0
21,1909,7,155,1,0
22,1909,7,155,1,0
23,1909,7,155,1,0
24,1820,6,156,1,0
25,1826,6,157,1,0
26,1826,6,157,1,0
27,1826,6,157,1,0
I would like to make a prediction for month 28 based on the previous months.
My code:
DataSource ds = new DataSource("src/main/java/dataset.arff");
Instances inst = ds.getDataSet();
inst.setClassIndex(1);
LinearRegression nb = new LinearRegression();
nb.buildClassifier(inst);
Instance novo = new DenseInstance(6);
novo.setDataset(inst);
novo.setValue(0, 28);
double prediction[] = nb.distributionForInstance(novo);
System.out.println("Prediction: "+Math.round(prediction[0]));

Related

Paypal SDK set billing plan to active

I am new to the PayPal SDK and I am trying to create a billing plan and change its status to ACTIVE. I have tried some sample Java code from the SDK tutorial but I can't get that code to work. Status remains CREATED. The code I tried can be found below.
What is missing/wrong?
The output from running the code is
Created plan with id = P-1MT21723NA428154CRJGOTXQ
Plan state = CREATED
Plan state = CREATED
Best regards /Lasse
// Build Plan object
Plan plan = new Plan();
plan.setName("T-Shirt of the Month Club Plan");
plan.setDescription("Template creation.");
plan.setType("fixed");
// Payment_definitions
PaymentDefinition paymentDefinition = new PaymentDefinition();
paymentDefinition.setName("Regular Payments");
paymentDefinition.setType("REGULAR");
paymentDefinition.setFrequency("MONTH");
paymentDefinition.setFrequencyInterval("1");
paymentDefinition.setCycles("12");
// Currency
Currency currency = new Currency();
currency.setCurrency("USD");
currency.setValue("20");
paymentDefinition.setAmount(currency);
// Charge_models
ChargeModels chargeModels = new ChargeModels();
chargeModels.setType("SHIPPING");
chargeModels.setAmount(currency);
List<ChargeModels> chargeModelsList = new ArrayList<>();
chargeModelsList.add(chargeModels);
paymentDefinition.setChargeModels(chargeModelsList);
// Payment_definition
List<PaymentDefinition> paymentDefinitionList = new ArrayList<>();
paymentDefinitionList.add(paymentDefinition);
plan.setPaymentDefinitions(paymentDefinitionList);
// Merchant_preferences
MerchantPreferences merchantPreferences = new MerchantPreferences();
merchantPreferences.setSetupFee(currency);
merchantPreferences.setCancelUrl("https://example.com/cancel");
merchantPreferences.setReturnUrl("https://example.com/return");
merchantPreferences.setMaxFailAttempts("0");
merchantPreferences.setAutoBillAmount("YES");
merchantPreferences.setInitialFailAmountAction("CONTINUE");
plan.setMerchantPreferences(merchantPreferences);
// Create payment
Plan createdPlan = plan.create(apiContext);
System.out.println("Created plan with id = " + createdPlan.getId());
System.out.println("Plan state = " + createdPlan.getState());
// Set up plan activate PATCH request
List<Patch> patchRequestList = new ArrayList<>();
Map<String, String> value = new HashMap<>();
value.put("state", "ACTIVE");
// Create update object to activate plan
Patch patch = new Patch();
patch.setPath("/");
patch.setValue(value);
patch.setOp("replace");
patchRequestList.add(patch);
// Activate plan
createdPlan.update(apiContext, patchRequestList);
System.out.println("Plan state = " + createdPlan.getState());
Got it!
I had to execute Plan.get(context, createdPlan.getId());
to get the latest state of the plan.

testing OpenNLP classifier model

I'm currently training a model for a classifier. yesterday I found out that it will be more accurate if you also test the created classify model. I tried searching on the internet how to test a model : testing openNLP model. But I cant get it to work. I think the reason is because i'm using OpenNLP version 1.83 instead of 1.5. Could anyone explain me how to properly test my model in this version of OpenNLP?
Thanks in advance.
Below is the way im training my model:
public static DoccatModel trainClassifier() throws IOException
{
// read the training data
final int iterations = 100;
InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/trainingSets/trainingssetTest.txt"));
ObjectStream<String> lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
// define the training parameters
TrainingParameters params = new TrainingParameters();
params.put(TrainingParameters.ITERATIONS_PARAM, iterations+"");
params.put(TrainingParameters.CUTOFF_PARAM, 0+"");
params.put(AbstractTrainer.ALGORITHM_PARAM, NaiveBayesTrainer.NAIVE_BAYES_VALUE);
// create a model from traning data
DoccatModel model = DocumentCategorizerME.train("NL", sampleStream, params, new DoccatFactory());
return model;
}
I can think of two ways to test your model. Either way, you will need to have annotated documents (an by annotated I really mean expert-classified).
The first way involves using the opennlp DocCatEvaluator. The syntax would be something akin to
opennlp DoccatEvaluator -model model -data sampleData
The format of your sampleData should be
OUTCOME <document text....>
documents are separated by the new line character.
The second way involves creating an DocumentCategorizer. Something like:
(the model is the DocCat model from your question)
DocumentCategorizer categorizer = new DocumentCategorizerME(model);
// could also use: Tokenizer tokenizer = new TokenizerME(tokenizerModel)
Tokenizer tokenizer = WhitespaceTokenizer.INSTANCE();
// linesample is like in your question...
for(String sample=linesample.read(); sample != null; sample=linesample.read()){
String[] tokens = tokenizer.tokenize(sample);
double[] outcomeProb = categorizer.categorize(tokens);
String sampleOutcome = categorizer.getBestCategory(outcomeProb);
// check if the outcome is right...
// keep track of # right and wrong...
}
// calculate agreement metric of your choice
Since I typed the code here there may be a syntax error or two (either I or the SO community can fix), but the idea for running through your data, tokenizing, running it through the document categorizer and keeping track of the results is how you want to evaluate your model.
Hope it helps...

How to use a compare filter with an oracle date column

Info and question
I wanna create (oracle sql) ONE_DATE > to_date('31-12-2009', 'DD-MM-YYYY')
with a SQLContainer filter.
What do the arguments have to be for the "Greater" filter?
new Greater("ONE_DATE", ???????)
Common oracle approach
This is my code so far:
Calendar c_from = new GregorianCalendar(2009, 11, 31);
Date d_from = new Date(c_from.getTimeInMillis());
currentFilter = new Greater("ONE_DATE", d_from);
However, this doesn't throw an exception nor provides any results =) (the data container is simply empty).
Timestamp approach
Have you tried passing Timestamp like new Timestamp(d_from.getTime())
Approach as suggested by Knu8:
Calendar c_from = new GregorianCalendar(2009, 11, 31);
Date d_from = new Date(c_from.getTimeInMillis());
currentFilter = new Greater("ONE_DATE", new Timestamp(d_from.getTime()));
Same result: No exception but neither a single item in the container.

Count results with MongoDB 3.0 Java Driver

I just want to get the number of results of some query. Specifically I want to know how much users were online in the past 15 minutes. So, I set the connection up with:
mongoClient = new MongoClient("localhost", 3001);
database = mongoClient.getDatabase("database1");
Then in my method i get the collection and send a query...:
MongoCollection<Document> users = database.getCollection("users");
users.find(and(gte("lastlogin",xvminago),lte("lastlogin",now)
I'm not even sure if the last step is right. But it seems so easy in Javascript and this .count()-opereration which I can't find in Java. And the documentation(s), are weird and somehow all diffrent. (I use the MongoDB Java Driver 3.0)
Use MongoCollection's count() method, applying a query filter which makes use of the Datetime object from the Joda-Time library that simplifies date manipulation in java. You can check that out here. Basically create a datetime object 15 minutes from current time:
DateTime dt = new DateTime();
DateTime now = new DateTime();
DateTime subtracted = dt.minusMinutes(15);
Then use the variables to construct a date range query for use in the count() method:
Document query = new Document("lastlogin", new Document("$gte", subtracted).append("$lte", now));
mongoClient = new MongoClient("localhost", 3001);
long count = mongoClient.getDatabase("database1")
.getCollection("users")
.count(query);
On a sharded cluster, the underlying db.collection.count() method can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress. So it's safer to use aggregate() method instead:
Iterator<Document> it = mongoClient.getDatabase("database1")
.getCollection("users")
.aggregate(Arrays.asList(
new Document("$match", new Document("lastlogin",
new Document("$gte", subtracted).append("$lte", now))
),
new Document("$group", new Document("_id", null)
.append("count",
new Document("$sum", 1)
)
)
)
).iterator();
int count = it.hasNext() ? (Integer)it.next().get("count") : 0;

How to directly query workitem History in RTC using Java API

I want to get workitems by querying RTC based on workitem's history, after specific date and time.
Something like this:
IQueryableAttribute recAttr1 = factory.findAttribute(projectArea, IItem.HISTORY_PROPERTY, auditableClient, null );
AttributeExpression projectExpr = new AttributeExpression(projectAttr, AttributeOperation.EQUALS, projectArea);
AttributeExpression recExpr1 = new AttributeExpression(recAttr1, AttributeOperation.AFTER, timeStamp );
Term term= new Term(Operator.AND);
term.add(recExpr1);
IQueryClient queryClient = (IQueryClient) teamRepository.getClientLibrary(IQueryClient.class);
IQueryResult<IResolvedResult<IWorkItem>> result = queryClient.getResolvedExpressionResults(projectArea, (Expression)term, IWorkItem.FULL_PROFILE);
Is there any property like below?
IItem.HISTORY_PROPERTY

Categories

Resources