<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mariano Jimenez on Medium]]></title>
        <description><![CDATA[Stories by Mariano Jimenez on Medium]]></description>
        <link>https://medium.com/@mariano.jimenez?source=rss-89c261953619------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mon_bmqYTRtvrS3uMtXo4g.jpeg</url>
            <title>Stories by Mariano Jimenez on Medium</title>
            <link>https://medium.com/@mariano.jimenez?source=rss-89c261953619------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:39:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mariano.jimenez/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Uso de lenguaje natural en el AI Lakehouse de Oracle]]></title>
            <link>https://medium.com/@mariano.jimenez/uso-de-lenguaje-natural-en-el-ai-lakehouse-de-oracle-2d1b53a7c88e?source=rss-89c261953619------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d1b53a7c88e</guid>
            <dc:creator><![CDATA[Mariano Jimenez]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 11:52:23 GMT</pubDate>
            <atom:updated>2025-10-17T13:03:24.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*IL2MqK_hCcKliHC_6-edQA.png" /></figure><p>Al leer el <a href="https://jvillacanass.medium.com/conectando-oracle-autonomous-ai-lakehouse-con-aws-glue-catalog-usando-el-formato-de-datos-apache-c0358b714de6">post </a>de mi compañero Jorge Villacañas podemos darnos cuenta de lo sencillo e interesante que resulta crear un Oracle Autonomous AI Lakehouse a partir de tablas en formato apache Iceberg en AWS. Las capacidades que proporciona esta funcionalidad de Autonomous Database son incuestionables ya que permite reducir los silos de datos, simplificar su gestión y conocimiento y por lo tanto, acelerar la implantación de soluciones analíticas completas.</p><p>El siguiente paso es utilizar las capacidades de la inteligencia artificacial para interrogar y/o explorar acerca de los datos y su entorno.</p><p>Para ello vamos a utilizar el servidor MCP para Oracle database descrito en este <a href="https://blogs.oracle.com/database/post/introducing-mcp-server-for-oracle-database">post</a>.</p><p>Lo primero es pedirle al servidor MCP que se conecte a la base de datos autonoma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1O2nTsnulIyVcS7c39Sbg.png" /></figure><p>Dado que lo desconocemos absolutamente todo respecto al modelo de datos, preguntamos a la IA por él. Dado que sólo quiero saber acerca de las tablas de usuario, así se lo hago saber:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gIR3DQATMFRVOqMEf3DBQg.png" /></figure><p>La respuesta es interesante:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*iWzWNFoNkhg2KgJkB3Lv2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Gm2US70OY4EnkyONpXvJg.png" /></figure><p>La IA, mediante el acceso al catálogo de Autonomous Database, nos indica el origen de los datos (lineage) y la cardinalidad de los mismos (en este caso se ve que es una base de datos de sample o de demo). Lo más interesante, en este caso, es que la IA nos indica que el modelo de datos es una combinación de tablas maestras locales y tablas de datos en AWS Glue/Iceberg .</p><p>Interrogamos ahora a la IA para que nos de información acerca del propio contenido de los mismos. Si quisiera realizar la query para obtener el resultado tendría que estudiar el modelo y realizar alguna prueba, probablemente, para llegar al resultado. Sin embargo, el uso de la IA y el servidor MCP de Oracle Database nos permite realizar la query en lenguaje natural y que sean estas piezas las que trasladen las peticiones al lenguaje SQL para obtener los resultados esperados:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*AWPiuszZF85jXl9AQY5zbw.png" /></figure><p>La respuesta, como no podía ser otra, es exactamente la misma que se obtiene el el post original, poniendo en evidencia la capacidad de analisis del modelo de datos del motor MCP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*wWHieNPZ8bRSKlkP0uQDKQ.png" /></figure><p>Sin embargo puedo ir más allá, y le puedo pedir que haga un gráfico html para una visualización más eficaz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*Gayl9w1MZi5MicZc8LtfUw.png" /></figure><p>la IA genera automáticamente el script html que genera el gráfico:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*QRjylSD3UW9l7rmmV9geHQ.png" /></figure><p>El resultado es el siguiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*VpHBuXEr0bPwToZMtJXz-A.png" /></figure><p>¡Fantástico!</p><p>Esta es una pequeña demostración de lo fácil y potente que puede llegar a ser el crear un entorno analítico completo con las capacidades del Autonomous AI lakehouse, donde podemos reunir datos de todas las tipologías y en cualquier entorno y, mediante el uso de las capacidades del servidor MCP de la base de datos Oracle explorarlo y explotarlo usando el lenguaje natural.</p><p>Espero que os haya gustado,</p><p>¡hasta la próxima!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d1b53a7c88e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Oracle Database: A True Convergent Database.]]></title>
            <link>https://medium.com/@mariano.jimenez/oracle-database-a-true-convergent-database-a6e1ba20bff4?source=rss-89c261953619------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6e1ba20bff4</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[converged-database]]></category>
            <dc:creator><![CDATA[Mariano Jimenez]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 08:40:14 GMT</pubDate>
            <atom:updated>2025-10-01T08:40:14.619Z</atom:updated>
            <content:encoded><![CDATA[<h3>JSON and Vector data types compatibility</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*lpJyutajgwI-978MiqouWA.png" /></figure><p>At Oracle, we proudly assert that Oracle Database is the ultimate convergent database. This means it seamlessly handles all types of data and workloads with optimal efficiency. The most recent example of this is the introduction of vector data type in Oracle Database 23ai, which further expands the list of supported data types and their capabilities.</p><p>A few weeks ago, someone asked me about calculating vector distances in Oracle Database using JSON elements. This question inspired this post</p><h3><strong>Data Creation</strong></h3><p>To illustrate the compatibility between JSON and vector data types in Oracle Database, I’ve created a JSON file (degrees.json) and uploaded it to an Oracle Cloud Infrastructure (OCI) bucket. This file contains data for 49 degrees from Spanish universities. Each row represents a degree and includes the following standardized fields:</p><ul><li><strong>DEGREE_ID</strong>: A unique identifier for each degree.</li><li><strong>SCORE</strong>: The cut-off mark required for admission to the degree.</li><li><strong>UMAP_VECTOR</strong>: A two-dimensional vector representation of the PDF brochure explaining the degree. This is stored as a sequence of numbers within brackets, e.g., [12.278578758239746, 5.584525108337402]. See my <a href="https://medium.com/@mariano.jimenez/estudio-de-grados-universitarios-mediante-t%C3%A9cnicas-vectoriales-24fa6a784416">post</a> about university degrees for more info about UMAP dimensional reduction.</li><li><strong>UNIVERSITY</strong>: The university offering the degree, either “UCM” (Universidad Complutense de Madrid) or “UAM” (Universidad Autónoma de Madrid).</li><li><strong>TYPE</strong>: A personal classification of the study type, with values such as: “HS” Health Sciences, “NU” Nutrition and Food Science, “SC” Sciences, “SO” Social Sciences, “ED” Education, “NC” Natural Sciences, “HU” Humanities and Arts</li><li><strong>DEGREE_NAME</strong>: The full name of the degree.</li></ul><p><strong>Example Entry</strong>:</p><pre>{&quot;DEGREE_ID&quot;:33,&quot;SCORE&quot;:12.806,&quot;UMAP_VECTOR&quot;:&quot;[12.278578758239746, 5.584525108337402]&quot;,&quot;UNIVERSITY&quot;:&quot;UCM&quot;,&quot;TYPE&quot;:&quot;SC&quot;,&quot;DEGREE_NAME&quot;:&quot;Mathematics and Data Science&quot;}</pre><h3>Loading JSON Data into an Autonomous Database Collection</h3><p>Next, I created the collection DEGREES_JSON_COLL in an Oracle Autonomous Database and loaded the degrees.json file into it directly from OCI object storage.</p><pre>BEGIN<br>DBMS_CLOUD.COPY_COLLECTION(<br>            collection_name =&gt; &#39;DEGREES_JSON_COLL&#39;,<br>            credential_name =&gt; &#39;ocicredential&#39;,<br>            file_uri_list   =&gt; &#39;https://objectstorage.eu-frankfurt-1.oraclecloud.com/n/emeasespainsandbox/b/streamBucketOutput/o/degrees.json&#39;  <br>            );<br>END;<br>/<br>desc DEGREES_JSON_COLL;</pre><p>The collection is designed with a single column, DATA, which stores each JSON row as is.</p><pre>---------------------------<br><br>Name    Null?    Type    <br>DATA             JSON    <br><br>---------------------------</pre><p>Now we can select a row to control how the json has been inserted. Notice that an additional _id tag has been automatically added to each JSON row.</p><pre>select * from DEGREES_JSON_COLL fetch FIRST row only;</pre><pre>DATA<br>{&quot;DEGREE_ID&quot;:35,&quot;SCORE&quot;:9.282,&quot;UMAP_VECTOR&quot;:&quot;[10.936450004577637, 5.482945919036865]&quot;,&quot;UNIVERSITY&quot;:&quot;UCM&quot;,&quot;TYPE&quot;:&quot;ED&quot;,&quot;DEGREE_NAME&quot;:&quot;Pedagogy&quot;,&quot;_id&quot;:&quot;68dcd74db7aeeb7d67210d4b&quot;}</pre><h3><strong>Performing Vector Operations</strong></h3><p>We now can use the UMAP_VECTOR tag inside the json row to explore compatibilities between vector and json data types</p><pre>SELECT to_vector(json_value(data, &#39;$.UMAP_VECTOR&#39; RETURNING VARCHAR2(50))) as UMAP_VECTOR<br>FROM DEGREES_JSON_COLL<br>WHERE json_value(data,  &#39;$.DEGREE_ID&#39; RETURNING NUMBER) = 37 ;</pre><pre>UMAP_VECTOR<br>[1.48401108E+001,4.33535051E+000]</pre><p>this way we can estimate vector distance!</p><pre>select VECTOR_DISTANCE(<br>    (SELECT to_vector(json_value(data, &#39;$.UMAP_VECTOR&#39; RETURNING VARCHAR2(50))) FROM DEGREES_JSON_COLL WHERE json_value(data,  &#39;$.DEGREE_ID&#39; RETURNING NUMBER) = 37)<br>  , (SELECT to_vector(json_value(data, &#39;$.UMAP_VECTOR&#39; RETURNING VARCHAR2(50))) FROM DEGREES_JSON_COLL WHERE json_value(data,  &#39;$.DEGREE_ID&#39; RETURNING NUMBER) = 36))<br>  as vectordistance_from_json</pre><pre>VECTORDISTANCE_FROM_JSON<br>0.045357642866116765</pre><p>And finally we can identify the 3 closest degrees to referenced one based on vector distance. Note that we are using allways the json collection DEGREES_JSON_COLL</p><pre>select json_value( data,&#39;$.DEGREE_ID&#39; RETURNING NUMBER) as ID_GRADO, json_value( data, &#39;$.DEGREE_NAME&#39; RETURNING VARCHAR2(30)) as DEGREE_NAME<br> from  DEGREES_JSON_COLL order by <br>VECTOR_DISTANCE(to_vector(&#39;[1.48401108E+001,4.33535051E+000]&#39;), to_vector(json_value(data, &#39;$.UMAP_VECTOR&#39; RETURNING VARCHAR2(50))))<br>FETCH FIRST 3 ROWS ONLY;</pre><pre>ID_GRADO DEGREE_NAME<br>37 Psychology<br>14 Nursing<br>23 Medicine</pre><p>Now we can load all data into a table from collection, loading directly from json to vector data type. Firstly we create the table</p><pre>CREATE TABLE &quot;DEGREES_FROM_JSON&quot;<br>   ( <br> &quot;DEGREE_ID&quot; NUMBER, <br> &quot;UMAP_VECTOR&quot; VECTOR, <br> &quot;UNIVERSITY&quot; VARCHAR2(3 BYTE), <br> &quot;TYPE&quot; VARCHAR2(2 BYTE), <br> &quot;DEGREE_NAME&quot; VARCHAR2(120 BYTE), <br> &quot;SCORE&quot; NUMBER(5,3) <br>    )   ;</pre><p>And finally load data into the new table</p><pre>insert into DEGREES_FROM_JSON <br>    (<br>     DEGREE_ID, <br>     UMAP_VECTOR,<br>     UNIVERSITY,<br>     TYPE,<br>     DEGREE_NAME, <br>     SCORE<br>    )<br>    select jt.DEGREE_ID, <br>           to_vector(jt.UMAP_VECTOR), <br>           jt.UNIVERSITY, <br>           jt.TYPE, <br>           jt.DEGREE_NAME, <br>           jt.SCORE<br>    from DEGREES_JSON_COLL, json_table( DATA, &#39;$[*]&#39;COLUMNS <br>    ( DEGREE_ID NUMBER PATH &#39;$.DEGREE_ID&#39;,<br>      UMAP_VECTOR  CLOB PATH  &#39;$. UMAP_VECTOR&#39;,<br>      UNIVERSITY  VARCHAR2(3) PATH  &#39;$.UNIVERSITY&#39;,<br>      TYPE  VARCHAR2(2) PATH  &#39;$.TYPE&#39;,<br>      DEGREE_NAME VARCHAR2(120) PATH  &#39;$.DEGREE_NAME&#39;,<br>      SCORE NUMBER(5,3) PATH  &#39;$.SCORE&#39;<br>      )) as jt;</pre><p>49 rows inserted.</p><pre>SELECT COUNT(*) from DEGREES_FROM_JSON;<br>SELECT * FROM DEGREES_FROM_JSON fetch FIRST 5 row only;</pre><pre>COUNT(*)    <br>         49 <br><br><br>---------------------------<br><br>DEGREE_ID    UMAP_VECTOR                          UNIVERSITY    TYPE    DEGREE_NAME                               SCORE     <br>          35 [1.093645E+001,5.48294592E+000]      UCM           ED      Pedagogy                                      9.282 <br>          36 [1.03924809E+001,6.9068079E+000]     UAM           NU      Food Science and Technology                   8.864 <br>          37 [1.48401108E+001,4.33535051E+000]    UAM           HS      Psychology                                   10.739 <br>          40 [1.39101839E+001,5.67264891E+000]    UAM           SO      Business Administration and Management       10.667 <br>          41 [1.43659544E+001,4.94040251E+000]    UAM           NC      Science Degree                                 8.05 <br><br><br>---------------------------</pre><p>I hope you’ve enjoyed this post and gained some insights into the compatibility and integration of JSON and vector data types in Oracle Database. If you’ve learned something new along the way, our goals have been more than achieved.</p><p>Thank you for reading!</p><p><em>¡Hasta la próxima!</em></p><p>You can find more info <a href="https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/json-compatibility-vector-data-type.html">here</a>, <a href="https://docs.oracle.com/en/database/oracle/oracle-database/23/adjsn/loading-external-json-data.html">here </a>and <a href="https://oracle-base.com/articles/23/json-collections-23">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6e1ba20bff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estudio de grados universitarios mediante técnicas vectoriales.]]></title>
            <link>https://medium.com/@mariano.jimenez/estudio-de-grados-universitarios-mediante-t%C3%A9cnicas-vectoriales-24fa6a784416?source=rss-89c261953619------2</link>
            <guid isPermaLink="false">https://medium.com/p/24fa6a784416</guid>
            <dc:creator><![CDATA[Mariano Jimenez]]></dc:creator>
            <pubDate>Mon, 05 May 2025 15:05:58 GMT</pubDate>
            <atom:updated>2025-05-07T06:51:21.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*b4ENka7s9H-fPHG4RA9OZg.png" /></figure><p>Al acabar el examen de cualificación universitaria (EBAU), mi hijo menor tenía que seleccionar el grado que quería estudiar. Para ello tenía que cuadrar la oferta universitaria con sus deseos y capacidades con el resultado del examen.</p><p>Teniendo en cuenta, además, que no tiene por qué saber cuál es el contenido de las carreras, ni las asignaturas, ni las salidas profesionales. El quiere poder preguntar “qué carrera debo estudiar” indicando en lenguaje natural cuáles son sus gustos o deseos.</p><p>Decidí echarle una mano y, de paso, mostrar cómo sacar partido de las capacidades vectoriales de Oracle Autonomous. Este post es el resultado de ese estudio.</p><p>Parto ya de los datos cargados en una tabla en ADB 23ai. Si alguien está interesado en cómo realicé la carga de los datos que me lo haga saber. Además, decidí hacerlo con un notebook de OML. Es una herramienta muy versátil que me permite sacarle mucho partido directamente a los datos de una ADB.</p><p>Obtuve algunas decenas de folletos (pdf) de grados de universidades públicas en castellano ( Universidad Complutense de Madrid, UCM y Universidad Autonoma de Madrid, UAM) a los que realicé el siguiente preprocesado de datos:</p><ul><li>Extracción de texto al que no realicé ninguna técnica de chunk.</li><li>Generación de los vectores con el texto de los folletos de los grados (mediante uso del servicio de embedding de OCI GenAI) y carga de los mismos.</li><li>Extracción de algunos metadatos del grado, como la universidad que lo imparte, nota de corte o las asignaturas estudiadas en el primer año.</li><li>También llevé a cabo una reducción de dimensionalidad del vectores de acuerdo a UMAP (Uniform Manifold Approximation and Projection for Dimension Reduction) <a href="https://umap-learn.readthedocs.io/en/latest/">https://umap-learn.readthedocs.io/en/latest/</a></li></ul><p>El resultado es una tabla con las siguientes columnas:</p><p>- ID_GRADO: Identificador del grado (número).<br>- UMAP_X: 1er componente del modelo UMAP del vector del texto (número).<br>- UMAP_Y: 2º componente del modelo UMAP del vector del texto (número).<br>- UNIVERSIDAD: Universidad que imparte el grado: UCM o UAM. <br>- TIPOESTUDIO: Clasificación funcional del grado: Sociales, Educación, CC de la Salud, Ciencias, Estadística y Matemáticas, Nutrición y deporte y Letras. <br>- NOMBRE_CORTO: Nombre corto del grado. <br>- NOMBRE_GRADO: Nombre del grado. <br>- PDFFILE: Fichero folleto donde se encuentra la información del grado.<br>- VECTORTEXTO: Vector con el contenido semántico del texto del folleto.<br>- ASIGNATURAS_PRIMERO: Asignaturas del primer año del grado (json).<br>- NOTA_CORTE: Nota de corte para cursar el grado.<br>- TEXTO: Texto del folleto.</p><p>Comparamos en primer lugar la distancia vectorial para una serie de grados, en concreto, entre el grado de Maestro/a en educación infantil de la UAM y</p><p>-Maestro en Educación infantil UCM<br>-Pedagogia UCM<br>-Musicología UCM<br>-Matemáticas UCM</p><pre>%sql<br>select g1.id_grado as grado1,  (g1.nombre_grado || &#39; &#39; ||g1.universidad) as grado_universidad1,<br>       g2.id_grado as grado2,  (g2.nombre_grado || &#39; &#39; ||g2.universidad) as grado_universidad2,<br>       vector_distance(g1.vectortexto, g2.vectortexto, COSINE) as distance<br>   from grados_universidad g1, grados_universidad g2<br>   where <br>   g1.id_grado in (13) and g2.id_grado in (13, 17, 22, 35, 44) <br>   order by distance;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZq4d8EbU8ZweyrFKdl4MA.png" /></figure><p>Aquí podemos ver cómo el grado de maestro en educación infantil de la UAM se aleja vectorialmente de los otros grados a medida que nos alejamos “funcionalmente” de él.</p><p>Para ver completamente el espacio vectorial generado a partir de los grados, voy a utilizar los componentes UMAP guardados en la tabla. UMAP es una técnica que, al igual que por ejemplo, componentes principales, reduce la dimensionalidad de un elemento para ajustarla a nuestras necesidades.</p><p>En mi caso utilice UMAP para reducir la dimensionalidad de los vectores (1024 dimensiones) a 2 (UMAP_X e UMAP_Y). Esto nos permitirá visualizarlos cómodamente en un plano. El notebook de ADB me permite ejecutar un pequeño programa python y utilizar la librería oml de OML4Py para visualizar la información generada por el modelo UMAP:</p><pre>import matplotlib.pyplot as plt<br>import oml<br>import pandas as pd<br><br>GRADOS_UNIVERSIDAD = oml.sync(table=&#39;GRADOS_UNIVERSIDAD&#39;)<br><br>x= GRADOS_UNIVERSIDAD[:, 3].pull()<br>y= GRADOS_UNIVERSIDAD[:, 4].pull()<br>tipo=GRADOS_UNIVERSIDAD[:, 6].pull()<br>univ=GRADOS_UNIVERSIDAD[:, 5].pull()<br>nombre=GRADOS_UNIVERSIDAD[:, 7].pull()<br><br>dfU= pd.DataFrame(univ, columns=[&#39;univ&#39;])<br>dfE= pd.DataFrame(tipo, columns=[&#39;tipo&#39;])<br><br>markerU = {&#39;UCM&#39; : &#39;d&#39;, &#39;UAM&#39;: &#39;o&#39;}<br>s=dfU[&#39;univ&#39;].map(markerU)<br><br>colorsE = {&#39;SO&#39;:&#39;blue&#39;, &#39;ED&#39;:&#39;orange&#39;, &#39;SA&#39;:&#39;green&#39;, &#39;CI&#39;:&#39;black&#39;, &#39;ES&#39;:&#39;red&#39;, &#39;OT&#39;:&#39;purple&#39;, &#39;NU&#39;:&#39;yellow&#39;,&#39;LE&#39;:&#39;pink&#39; }<br>col=dfE[&#39;tipo&#39;].map(colorsE)<br><br>fig, ax = plt.subplots(figsize=(20,10))<br><br>for _s, c, _x, _y in zip(s, col, x, y):<br>    ax.scatter(_x, _y, marker=_s, c=c,  alpha=.6, s=400)<br>    <br>for i, label in enumerate(nombre):<br>    plt.annotate(label, (x[i] + 0.07, y[i]- 0.02), rotation=0, size=12)<br>       <br>plt.title(&quot;VISUALIZACION DE LA DISTANCIA VECTORIAL DE LOS GRADOS&quot;)<br>plt.xlabel(&quot;1er componente UMAP&quot;)<br>plt.ylabel(&quot;2o componente UMAP&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*kRwE8N1Sql0AUMQWcN04Ag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*HP869TvTtOAVyxiUSUSlPA.png" /></figure><p>Se ven algunas curiosidades como el sesgo general provocado por la universidad que genera el folleto o cómo el grado de economía de la UCM quizá estaría mejor clasificado como Estadística y Matemáticas que como Ciencias Sociales.</p><p>Con ADB podemos generar vectores al vuelo, es decir, a partir de un texto que no esté guardado en una base de datos:</p><pre>%script<br> select dbms_vector.utl_to_embedding( <br>    &#39;hola&#39;,<br>    json(&#39;<br>    {&quot;provider&quot;: &quot;ocigenai&quot;,<br>    &quot;credential_name&quot;: &quot;ocicredentialwcomp&quot;,<br>    &quot;url&quot;: &quot;https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com/20231130/actions/embedText&quot;,<br>    &quot;model&quot;: &quot;cohere.embed-multilingual-v3.0&quot;}<br>    &#39;)<br>    ) as vector_al_vuelo<br>    from dual;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzKXKFE3qGDIBD5tSlYWSg.png" /></figure><p>En este caso he utilizado nuestro servicio OCI GENAI para generar los vectores. También podríamos utilizar un modelo en formato onnx embebido dentro de la base de datos para realizar la misma acción. Podeis consultar mi <a href="https://medium.com/@mariano.jimenez/building-and-loading-vectors-into-an-oracle-autonomous-database-using-an-embedding-model-1a17909a9af4">post relativo a la generación de vectores en ADB</a> al respecto.</p><p>Ya dispongo de todas las piezas para construir una función que me permita interrogar a la base de datos acerca de los grados guardados a partir de preguntas que puedan reflejar los deseos e intereses de los estudiantes. No necesito conocer lo que quiero estudiar sino qué me gusta y que ese deseo sea trasladado a un vector que compare en distancia vectorial con el texto vectorizado de los folletos de los grados:</p><pre>%script<br>create or replace PROCEDURE dime_que_carrera <br>(sentence IN VARCHAR2) <br>AS <br>  question_vector vector;<br>BEGIN <br>   select dbms_vector.utl_to_embedding(sentence,<br>   json(&#39;<br>   {&quot;provider&quot;: &quot;ocigenai&quot;,<br>   &quot;credential_name&quot;: &quot;ocicredentialwcomp&quot;,<br>   &quot;url&quot;: &quot;https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com/20231130/actions/embedText&quot;,<br>   &quot;model&quot;: &quot;cohere.embed-multilingual-v3.0&quot;}<br>   &#39;)<br>   ) <br>   into question_vector;<br>   dbms_output.put_line(to_char(sentence));<br>   dbms_output.put_line(&#39;&#39;);<br>   FOR t IN <br>   (<br>   select id_grado, nombre_grado, universidad, tipoestudio<br>   from grados_universidad<br>   order by vector_distance(vectortexto, question_vector, COSINE)<br>   FETCH FIRST 3 ROWS ONLY<br>   ) <br>   LOOP <br>      dbms_output.put_line(to_char(t.id_grado) || &#39;  &#39; || t.nombre_grado || &#39;  &#39; || t.universidad  ); <br>   END LOOP; <br>END;<br>/</pre><p>y su ejecución:</p><pre>%script<br>EXEC DIME_QUE_CARRERA (<br>&#39;Me gustaría trabajar como profesor de niños pequeños&#39;<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*3md__OUOe4HzIsATBV6HqQ.png" /></figure><pre>%script<br>EXEC DIME_QUE_CARRERA (<br>&#39;me gustaría trabajar en la industria alimentaria&#39;<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*ZIwDYetTKsQ47lzrFw-8dw.png" /></figure><p>Modificamos ahora la función para añadirle filtros a la consulta. En este caso seleccionaremos grados en función de la distancia vectorial pero filtrando por la universidad que imparte el grado y la nota de corte que se requiere:</p><pre>%script <br>create or replace PROCEDURE dime_que_carrera_con_nota_de_corte<br>(<br>sentence IN VARCHAR2,<br>universidad_selection IN VARCHAR2,<br>nota_selection IN number<br>) <br>AS <br>  question_vector vector;<br>BEGIN <br>   select dbms_vector.utl_to_embedding(sentence,<br>   json(&#39;<br>   {&quot;provider&quot;: &quot;ocigenai&quot;,<br>   &quot;credential_name&quot;: &quot;ocicredentialwcomp&quot;,<br>   &quot;url&quot;: &quot;https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com/20231130/actions/embedText&quot;,<br>   &quot;model&quot;: &quot;cohere.embed-multilingual-v3.0&quot;}<br>   &#39;)<br>   ) <br>   into question_vector;<br>   dbms_output.put_line(to_char(sentence)|| &#39; en &#39; || universidad_selection || &#39; con &#39; || nota_selection || &#39; de nota:&#39; );<br>   dbms_output.put_line(&#39;&#39;);<br>   <br>   FOR t IN <br>   (<br>   select id_grado, nombre_grado, universidad, nota_corte<br>   from grados_universidad<br><br>   where (universidad = universidad_selection or universidad_selection = &#39;TODAS&#39;)<br>   and  nota_corte &lt;= nota_selection<br><br>   order by vector_distance(vectortexto, question_vector, COSINE)<br>   FETCH FIRST 3 ROWS ONLY<br>   ) <br>   LOOP <br>      dbms_output.put_line(to_char(t.id_grado) || &#39;  &#39; || t.nombre_grado || &#39;  &#39; || t.universidad || &#39;  &#39; || t.nota_corte ); <br>   END LOOP; <br>   <br>END;<br>/</pre><p>Hacemos alguna pregunta a la base de datos:</p><pre><br>%script<br>EXEC dime_que_carrera_con_nota_de_corte (<br>&#39;me gustaría trabajar en la industria alimentaria&#39;, <br>&#39;UAM&#39;, <br>10);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*-u1hQ4OR6eoWGxdaTnUWYg.png" /></figure><pre>%script<br>EXEC dime_que_carrera_con_nota_de_corte (<br>&#39;me gustaría trabajar en la industria alimentaria&#39;, <br>&#39;TODAS&#39;, <br>9);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*J-Ng5wOZtRI7wm1CUCZpXw.png" /></figure><p>Dado que ADB es una base de datos convergente (soporta todo tipo de datos) podemos realizar consultas mezclando columnas de todo tipo. En este caso vamos a complementar el filtro construido utilizando también las asignaturas del primer año. Acordaos que éstas están almacenadas en formato JSON:</p><pre>%script<br>create or replace PROCEDURE dime_que_carrera_con_asignaturas<br>(<br>sentence IN VARCHAR2,<br>universidad_selection IN VARCHAR2,<br>nota_selection IN number,<br>asignatura_selection IN VARCHAR2<br>) <br>AS <br>  question_vector vector;<br>BEGIN <br>   select dbms_vector.utl_to_embedding(sentence,<br>   json(&#39;<br>   {&quot;provider&quot;: &quot;ocigenai&quot;,<br>   &quot;credential_name&quot;: &quot;ocicredentialwcomp&quot;,<br>   &quot;url&quot;: &quot;https://inference.generativeai.eu-frankfurt-1.oci.oraclecloud.com/20231130/actions/embedText&quot;,<br>   &quot;model&quot;: &quot;cohere.embed-multilingual-v3.0&quot;}<br>   &#39;)<br>   ) <br>   into question_vector;<br>   dbms_output.put_line(to_char(sentence)|| &#39; en &#39; || universidad_selection || &#39; con &#39; || nota_selection || &#39; de nota y en primero con asignatura de &#39; || asignatura_selection  );<br>   dbms_output.put_line(&#39;&#39;);<br>   <br>   <br>   FOR t IN <br>   (<br>   select id_grado, nombre_grado, universidad, nota_corte, min(vector_distance(vectortexto, question_vector, COSINE)) as distancia_vectorial<br>   from grados_universidad, json_table(asignaturas_primero, &#39;$[*]&#39; COLUMNS (asignatura VARCHAR2(200 CHAR) PATH &#39;$&#39;)) as &quot;JT&quot;<br><br>   where (universidad = universidad_selection or universidad_selection = &#39;TODAS&#39;)<br>   and nota_corte &lt;= nota_selection<br>   and asignatura like to_char(&#39;%&#39; || asignatura_selection || &#39;%&#39;)<br>   group by id_grado, nombre_grado, universidad, nota_corte<br>   <br>   order by distancia_vectorial<br>   <br>   FETCH FIRST 3 ROWS ONLY<br>   ) <br>   LOOP <br>      dbms_output.put_line(to_char(t.id_grado) || &#39;  &#39; || t.nombre_grado || &#39;  &#39; || t.universidad || &#39;  &#39; || t.nota_corte  ); <br>   END LOOP; <br>         <br>END;<br>/<br></pre><p>Y podemos lanzar las preguntas:</p><pre>%script <br>exec dime_que_carrera_con_asignaturas(<br>&#39;me gustaría trabajar en la industria alimentaria&#39;, <br>&#39;TODAS&#39;, <br>10, <br>&#39;Matemáticas&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*_PiK7-2yyTfgIubqi0BBYQ.png" /></figure><pre>%script <br>exec dime_que_carrera_con_asignaturas(<br>&#39;Me gustaría trabajar como profesor de niños pequeños&#39;, <br>&#39;UAM&#39;, <br>10, <br>&#39;Matemáticas&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*S6afW-SJNCpqOkz0rQYShg.png" /></figure><p>Hemos creado un selector de grados universitarios a partir de la información pública de los grados con el que los estudiantes pueden utilizar lenguaje natural para identificar aquellos grados que se adaptan mejor a sus intereses, sin tener que analizar en profundidad el contenido de los grados. Pueden utilizar filtros adicionales para facilitar esa labor y adaptar la búsqueda de una manera directa en función de la nota de corte o las asignaturas del primer año.</p><p>¡Espero que os haya gustado!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24fa6a784416" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and loading vectors into an Oracle Autonomous Database using a pretrained model inside the…]]></title>
            <link>https://medium.com/@mariano.jimenez/building-and-loading-vectors-into-an-oracle-autonomous-database-using-an-embedding-model-1a17909a9af4?source=rss-89c261953619------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a17909a9af4</guid>
            <category><![CDATA[autonomous-database]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Mariano Jimenez]]></dc:creator>
            <pubDate>Mon, 05 May 2025 06:52:49 GMT</pubDate>
            <atom:updated>2025-05-05T15:18:52.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building and loading vectors into an Oracle Autonomous Database using a pretrained model inside the database.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*0G-hG4sLsG2bCyHd4700iw.png" /></figure><p>In this post, I’m going to create and load vectors into a table in an Oracle autonomous database using a pretrained model inside the database. I’m going to take data from the MOVIE table used in the Oracle Data Studio Live Lab —<a href="https://livelabs.oracle.com/pls/apex/f?p=133:180:9896448370237::::wid:789"> Self-service tools for everyone using Oracle Autonomous Database</a>. I remind you that Oracle Live Labs are a very useful tool for learning about Oracle services in a very practical way.</p><p>For this post I need an ABD with admin privileges, object storage and an OCI user with granted privileges to write and read object storage.</p><p>I will also use the ADB user “userbd01” from which I will create the MOVIE table and load the data using the <a href="https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/DBMS_CLOUD.html#GUID-9428EA51-5DDD-43C2-B1F5-CD348C156122">DBMS_CLOUD.COPY_DATA</a> procedure.</p><pre>CREATE TABLE MOVIE <br>( <br> MOVIE_ID     NUMBER , <br> TITLE        VARCHAR2 (200) , <br> BUDGET       NUMBER , <br> GROSS        NUMBER , <br> LIST_PRICE   NUMBER , <br> GENRES       VARCHAR2 (4000) , <br> SKU          VARCHAR2 (30) , <br> YEAR         NUMBER , <br> OPENING_DATE DATE , <br> VIEWS        NUMBER , <br> CAST         VARCHAR2 (4000) , <br> CREW         VARCHAR2 (4000) , <br> STUDIO       VARCHAR2 (4000) , <br> MAIN_SUBJECT VARCHAR2 (4000) , <br> AWARDS       VARCHAR2 (4000) , <br> NOMINATIONS  VARCHAR2 (4000) , <br> RUNTIME      NUMBER , <br> SUMMARY      VARCHAR2 (16000) <br>) <br>;</pre><pre>DBMS_CLOUD.COPY_DATA(<br>table_name =&gt;&#39;MOVIE&#39;,<br>file_uri_list =&gt;&#39;https://objectstorage.us-ashburn-1.oraclecloud.com/p/zL6bsboZrSxJP-0ilfUpROTwwyhzvkUrZu9OEwcU5_B_NAGzHKBG_WqW2OnNYxKk/n/c4u04/b/datastudio/o/prepareandanalyze/MOVIE.csv&#39;,<br>format =&gt;&#39;{&quot;type&quot; : &quot;csv&quot;, &quot;skipheaders&quot; : 1}&#39;<br> );</pre><p>We can search for movies in our table based on the loaded data using SQL:</p><pre>SELECT movie_id, title, year FROM movies WHERE title like &#39;%Alien%&#39;</pre><p>The result would be:</p><pre>MOVIE_ID TITLE                                      YEAR <br>-------- ------------------------------------------ ---- <br>     201 Alien Abduction                            2005 <br>    3017 The Alien Factor                           1978 <br>     202 Alien Origin                               2012 <br>     203 Alien Thunder                              1974 <br>    3823 Voyage of the Rock Aliens                  1984 <br>     763 Codependent Lesbian Space Alien Seeks Same 2011 <br>     204 Alienator                                  1989 <br>     205 Aliens                                     1986 <br>     200 Alien                                      1979 <br>      83 AVH: Alien vs. Hunter                      2007 <br>    2162 My Stepmother Is an Alien                  1988</pre><p>We can make the search as complicated as we want, but we won’t be able to find movies about, saying, “aliens invade the Earth”.</p><p>That’s what vector search is for!.</p><p>To do this, we will create MOVIE_W_VECTOR table as a MOVIE twin table with a vector column with the vector embedding from summary text. The summary column describes in two text lines the plot of the film and some relevant features.</p><pre>CREATE TABLE MOVIE_W_VECTOR<br>( <br> MOVIE_ID     NUMBER , <br> TITLE        VARCHAR2 (200) , <br> BUDGET       NUMBER , <br> GROSS        NUMBER , <br> LIST_PRICE   NUMBER , <br> GENRES       VARCHAR2 (4000) , <br> SKU          VARCHAR2 (30) , <br> YEAR         NUMBER , <br> OPENING_DATE DATE , <br> VIEWS        NUMBER , <br> CAST         VARCHAR2 (4000) , <br> CREW         VARCHAR2 (4000) , <br> STUDIO       VARCHAR2 (4000) , <br> MAIN_SUBJECT VARCHAR2 (4000) , <br> AWARDS       VARCHAR2 (4000) , <br> NOMINATIONS  VARCHAR2 (4000) , <br> RUNTIME      NUMBER , <br> SUMMARY      VARCHAR2 (16000) ,<br> SUMMARY_VECTOR VECTOR<br>);</pre><p>To build and load the vectors, the first thing we need is an embedding model that will transform texts into vectors. <a href="https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/onnx-pipeline-models-text-embedding.html">Oracle is providing a Hugging Face all-MiniLM-L12-v2 model in ONNX format</a>, available for download <a href="https://adwc4pm.objectstorage.us-ashburn-1.oci.customer-oci.com/p/VBRD9P8ZFWkKvnfhrWxkpPe8K03-JIoM5h_8EJyJcpE80c108fuUjg7R5L5O7mMZ/n/adwc4pm/b/OML-Resources/o/all_MiniLM_L12_v2_augmented.zip">here</a>. We unzip the file and transfer the ONNX model to an object storage of our choice.</p><p>Now we’ll download the model to a directory created in autonomous and then transfer it to the database. To do this, firstly, as the admin user, I <a href="https://docs.oracle.com/en/cloud/paas/autonomous-database/serverless/adbsb/create-directory.html">create the DM_DIRECTORY directory</a> and grant userbd01 privileges to work with the directory and the model.</p><pre>GRANT DB_DEVELOPER_ROLE TO userbd01;<br>GRANT create mining model TO userbd01;<br><br>CREATE OR REPLACE DIRECTORY DM_DIRECTORY as &#39;models&#39;;<br>GRANT READ ON DIRECTORY DM_DIRECTORY TO userbd01;<br>GRANT WRITE ON DIRECTORY DM_DIRECTORY TO userbd01;</pre><p>I must create a credential to be used with userbd01 (if I don’t have one) <a href="https://docs.oracle.com/en/cloud/paas/autonomous-database/serverless/adbsb/dbms-cloud-subprograms.html#GUID-742FC365-AA09-48A8-922C-1987795CF36A">that allows me to access Object Storage</a>. The private key and the fingerprint are part of the OCI API Signing Key. You can find <a href="https://docs.oracle.com/en-us/iaas/Content/API/Concepts/apisigningkey.htm">here</a> the way to create an API Signing Key on OCI.</p><pre>BEGIN<br>DBMS_CLOUD.CREATE_CREDENTIAL (<br> credential_name =&gt;&#39;ocicredential&#39;,<br> user_ocid       =&gt;&#39;ocid1.user.oc1..aaaaaaaana[............]wz44u4lh3sq&#39;,<br> tenancy_ocid    =&gt;&#39;ocid1.tenancy.oc1..aaaaaaaa3c4mibmpdb657mibv3q4dp2wx32525llme6hyzy5bjd7q7dnumba&#39;,<br> private_key     =&gt;&#39;MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJnhEUSWvOeXSB<br>nBs2OhQ/K35sV8PSfziUpvX/wLi7Rhm+uIzbx75o4lOkhZqq0BgR1mv1MqLgM246<br>9KGi1vJZ9Sg4PQd18JK8TBygMXV4f8geD4LHALxm2W8TiILWma2v4MPWTJZSftX+<br>[..............................................................]<br>wMgBC8A2JKqjOABSaRqr06QYF7pnGAkil2Zgl5YA80+rgb455dCaDLbv7IIlj9eu<br>s02LaNZf5LtaBIuKJT0l2yaV&#39;,<br> fingerprint     =&gt;&#39;80:90:19:[.........]13:6e&#39;);<br>END;<br>/</pre><p>Load the model into the directory:</p><pre>BEGIN <br>   DBMS_CLOUD.GET_OBJECT(<br>     credential_name =&gt; &#39;ocicredential&#39;,<br>     object_uri =&gt; &#39;https://objectstorage.eu-frankfurt-1.oraclecloud.com/n/[.........]/b/ai_bucket/o/all-MiniLM-L12-v2.onnx&#39;,<br>     file_name =&gt; &#39;all-MiniLM-L12-v2.onnx&#39;,<br>     directory_name =&gt; &#39;DM_DIRECTORY&#39;); <br>END;<br>/</pre><p>Now we can load the model from directory to the database</p><pre>BEGIN<br>DBMS_VECTOR.LOAD_ONNX_MODEL(<br> directory  =&gt; &#39;DM_DIRECTORY&#39;, <br> file_name  =&gt; &#39;all-MiniLM-L12-v2.onnx&#39;, <br> model_name =&gt; &#39;ALLMINLLML12V2&#39;);         <br>END;<br>/</pre><p>We test how it works:</p><pre>SELECT VECTOR_EMBEDDING(allminllml12v2 USING &#39;hello!&#39; as data) AS embedding;</pre><pre>EMBEDDING  <br>----------------------------------------------------------------------------                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             ---------<br>[-8.22120756E-002,1.65477619E-002,2.23228242E-002,-7.20694754E-003,.........]</pre><p>To insert all data into the new table we can use:</p><pre>INSERT INTO MOVIE_W_VECTOR <br> SELECT mo.movie_id<br>      , mo.title<br>      , mo.budget<br>      , mo.gross<br>      , mo.LIST_PRICE<br>      , mo.genres<br>      , mo.SKU<br>      , mo.year<br>      , mo.OPENING_DATE<br>      , mo.views<br>      , mo.cast<br>      , mo.crew<br>      , mo.studio<br>      , mo.MAIN_SUBJECT<br>      , mo.awards<br>      , mo.NOMINATIONS<br>      , mo.runtime<br>      , mo.summary<br>      , (SELECT VECTOR_EMBEDDING (allminllml12v2 USING mo.summary as data))<br>from movie MO;<br>commit;</pre><p>Once the vectors are loaded, you can ask for the vector distance:</p><pre>select movie_id<br>     , title<br>     , year<br>from MOVIE_W_VECTOR <br>     order by vector_distance (SUMMARY_VECTOR, <br>                              (SELECT VECTOR_EMBEDDING(ALLMINLLML12V2 <br>                               USING &#39;aliens invade the Earth&#39; as data)))<br> FETCH FIRST 3 ROWS ONLY</pre><pre>MOVIE_ID TITLE                          YEAR <br>-------- ------------------------------ ---- <br>    1378 H. G. Wells&#39; War of the Worlds 2005 <br>    1645 Invasion of the Pod People     2007 <br>     201 Alien Abduction                2005  </pre><p>You can find more info <a href="https://docs.oracle.com/en/database/oracle/oracle-database/23/vecse/generate-vector-embeddings-node.html">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a17909a9af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting with Oracle Cloud Infrastructure (2)]]></title>
            <link>https://medium.com/@mariano.jimenez/forecasting-with-oracle-cloud-infrastructure-2-8b1081d89bc4?source=rss-89c261953619------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b1081d89bc4</guid>
            <category><![CDATA[oci]]></category>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[oml]]></category>
            <dc:creator><![CDATA[Mariano Jimenez]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 10:59:42 GMT</pubDate>
            <atom:updated>2024-09-25T10:59:42.994Z</atom:updated>
            <content:encoded><![CDATA[<p>As promised in <a href="https://medium.com/@mariano.jimenez/forecasting-with-oracle-cloud-infrastructure-1-2-f65956bee909">my article on forecasts with OCI operator</a>, I am publishing an other way to forecast data with OCI. This case with Oracle Machine Learning, which is a feature within Oracle Database that allows algorithms to be launched on data without extracting it from the database. By doing so, you can avoid implementing additional data governance or extraction processes. Additionally, it will maximize scalability, improve memory resource management, and increase performance.</p><p>The easiest way to use OML capabilities in Oracle Database is to use Database Actions within Autonomous service since Database Actions are functionalities managed as a service within Autonomous.</p><p>First we will proceed to load the data into Autonomous using the Data Load functionality. I have prepared a .csv file with date (<em>fecha</em>), average temperature (<em>tm_mes</em>) and maximum temperature (<em>tm_max</em>) recorded in Barcelona during 2015 to 2022. We will use data to 2015 for training model and 2022 data to test the model. Data has been extracted from Spanish Weather Agency (<a href="https://opendata.aemet.es/centrodedescargas/inicio">AEMET) Opendata web page</a>. Csv file has the follow structure:</p><pre>fecha,tm_mes,tm_max<br>2015-01-01,10.0,14.7<br>2015-02-01,9.6,14.1<br>...<br>...</pre><p>First we proceed to load the data into Autonomous using the Data Load functionality. This easy wizard lets us to load data in few seconds from the .csv to the new table BCN_DATA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KyHmUoGPvq54gK1994BVg.png" /></figure><p>To study data and solve the forecasting problem, we will create a notebook within the Machine Learning tool. The service offers notebook examples to facilitate access to machine learning algorithms. Time Series examples are offered for R, Python, and PL/SQL. We could select OML4SQL Time Series ESM and create Notebook from here or just create a new Notebook from scratch.</p><p>To explore data in the new Notebook in a graphical view we only have to select data from the table. Zeppeling notebook will do the rest for us.</p><pre>%sql<br><br>SELECT TO_CHAR(FECHA,&#39;YYYY-MON&#39;) MONTH, <br>TM_MES AS AVERAGE_TEMP, <br>TM_MAX AS MAX_TEMP from BCN_DATA ORDER BY FECHA;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtQPalu3IdAATiBaU6Zzxg.png" /></figure><p>We can see how temperature fluctuates annually. Since Maximum temperature and Average temperature follow the same pattern, we will build the model just for averaged temperature using the procedure DBMS_DATA_MINING.CREATE_MODEL2 with some data related to model:</p><pre>%script<br><br>BEGIN DBMS_DATA_MINING.DROP_MODEL(&#39;ESM_BCN_FORECAST&#39;);<br>EXCEPTION WHEN OTHERS THEN NULL; END;<br>/<br><br>DECLARE<br>    v_setlst DBMS_DATA_MINING.SETTING_LIST;<br>BEGIN<br>    <br>    v_setlst(&#39;ALGO_NAME&#39;)            := &#39;ALGO_EXPONENTIAL_SMOOTHING&#39;;<br>    v_setlst(&#39;EXSM_INTERVAL&#39;)        := &#39;EXSM_INTERVAL_MONTH&#39;; <br>    v_setlst(&#39;EXSM_PREDICTION_STEP&#39;) := &#39;12&#39;;                 <br>    v_setlst(&#39;EXSM_MODEL&#39;)           := &#39;EXSM_WINTERS&#39;;      <br>    v_setlst(&#39;EXSM_SEASONALITY&#39;)     := &#39;12&#39;;                     <br><br>    DBMS_DATA_MINING.CREATE_MODEL2(<br>        MODEL_NAME          =&gt; &#39;ESM_BCN_FORECAST&#39;,<br>        MINING_FUNCTION     =&gt; &#39;TIME_SERIES&#39;,<br>        DATA_QUERY          =&gt; &#39;SELECT FECHA, TM_MES from BCN_DATA where fecha &lt; to_date(&#39;&#39;01-01-2022&#39;&#39;, &#39;&#39;dd-MM-yyyy&#39;&#39;) ORDER BY FECHA&#39;,<br>        SET_LIST            =&gt; v_setlst,<br>        CASE_ID_COLUMN_NAME =&gt; &#39;FECHA&#39;,<br>        TARGET_COLUMN_NAME  =&gt;&#39;TM_MES&#39;);</pre><p>There are some important parameters to be populated based on the data: EXSM_SEASONALITY which represents the data cycle (each 12 Months data repeats the season). EXSM_INTERVAL indicates the time interval to be considered (Monthly).</p><p>CASE_ID_COLUMN_NAME indicates the case identification and TARGET_COLUMN_NAME is the column to predict. DATA_QUERY allows you to filter the exact data you need for your model(before January 2022). <a href="https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/DBMS_DATA_MINING.html#GUID-A95A0A38-8A5A-4470-B49F-80D81C588BFC">Here </a>you can find a detailed description of the parameters.</p><p>When running the model, a number of objects of type VM$?&lt;model name&gt; is generated which are documented <a href="https://docs.oracle.com/en/database/oracle/machine-learning/oml4sql/23/dmprg/model-detail-views.html#GUID-5C42C10E-C780-4733-9C85-03C2C94D6E3F">here</a>:</p><p>DM$VPESM_BCN_FORECAST Contains a series of records with original time series values, estimated values for the training data, and forecast for the number of points defined by EXSM_PREDICTION_STEP. DM$ VGESM_BCN_FORECAST includes overall model information as well as model quality for estimated values.</p><p>But you may want to estimate the general trend for all the data. That will show us if the averaged temperature follows a trend during the period 2015–2021. We can estimate it using a linear model. This will easily show if the averaged temperature follows an upward trend during the period 2015–2021.</p><p>First we prepare the data to facilitate the calculations: We create a table with the original data by adding a column that represents the values ​​of X for a linear algorithm.</p><pre>%script<br><br>BEGIN EXECUTE IMMEDIATE &#39;DROP SEQUENCE SEQ_X&#39;;<br>EXCEPTION WHEN OTHERS THEN NULL; END;<br>/<br>CREATE SEQUENCE SEQ_X MINVALUE 0 INCREMENT BY 1;<br><br>BEGIN EXECUTE IMMEDIATE &#39;DROP TABLE BCN_DATA_WX&#39;;<br>EXCEPTION WHEN OTHERS THEN NULL; END;<br>/<br>CREATE TABLE BCN_DATA_WX AS SELECT * FROM BCN_DATA;<br>ALTER TABLE BCN_DATA_WX ADD X number(3);<br>UPDATE BCN_DATA_WX SET X=SEQ_X.nextval;</pre><p>Now we can create the linear model using the new column X and averaged temperature:</p><pre>%script<br><br>BEGIN DBMS_DATA_MINING.DROP_MODEL(&#39;ESM_BCN_DATA_TREND&#39;);<br>EXCEPTION WHEN OTHERS THEN NULL; END;<br>/<br><br>DECLARE<br>    v_setlst DBMS_DATA_MINING.SETTING_LIST;<br>BEGIN<br>    <br>    v_setlst(&#39;PREP_AUTO&#39;) := &#39;OFF&#39;;<br>    v_setlst(&#39;ALGO_NAME&#39;) := &#39;ALGO_GENERALIZED_LINEAR_MODEL&#39;;<br> <br>    DBMS_DATA_MINING.CREATE_MODEL2(<br>        MODEL_NAME          =&gt; &#39;ESM_BCN_DATA_TREND&#39;,<br>        MINING_FUNCTION     =&gt; &#39;REGRESSION&#39;,<br>        DATA_QUERY          =&gt; &#39;SELECT FECHA, X, TM_MES from BCN_DATA_WX  where fecha &lt; to_date(&#39;&#39;01-01-2022&#39;&#39;, &#39;&#39;dd-MM-yyyy&#39;&#39;) ORDER BY FECHA&#39;,<br>        SET_LIST            =&gt; v_setlst,<br>        CASE_ID_COLUMN_NAME =&gt; &#39;FECHA&#39;,<br>        TARGET_COLUMN_NAME  =&gt;&#39;TM_MES&#39;);<br>END;</pre><p>We can check coefficients for the created model</p><pre>SELECT ATTRIBUTE_NAME, COEFFICIENT FROM DM$VDESM_BCN_DATA_TREND;<br></pre><pre>ATTRIBUTE_NAME  COEFFICIENT <br>                17.134509803921585 <br>X                0.00926597144882017</pre><p>The model says that averaged temperature grows 0.0093 degrees each month (in average) with a initial averaged temperature of 17.1345. That means that the annual average temperature trend is that it grows 0.11 degrees each year, 0,67 degrees between Jan 2015 and Dec 2021!!</p><p>For a graphic representation we’ve prepared some data</p><pre>%script<br><br>BEGIN EXECUTE IMMEDIATE &#39;DROP TABLE BCN_PREDICTIONS&#39;;<br>EXCEPTION WHEN OTHERS THEN NULL; END;<br>/<br>create table BCN_PREDICTIONS as select * FROM DM$VPESM_BCN_FORECAST;<br>ALTER TABLE BCN_PREDICTIONS ADD X number(3);<br><br>BEGIN EXECUTE IMMEDIATE &#39;DROP SEQUENCE SEQ_X&#39;;<br>EXCEPTION WHEN OTHERS THEN NULL; END;<br>/<br><br>CREATE SEQUENCE SEQ_X MINVALUE 0 INCREMENT BY 1;<br>update BCN_PREDICTIONS set X=seq_X.nextval;<br><br>alter table BCN_PREDICTIONS add TREND_TEMP float;<br>update BCN_PREDICTIONS set TREND_TEMP=ROUND(PREDICTION(ESM_BCN_DATA_TREND using X), 5);<br><br>alter table BCN_PREDICTIONS add REAL_TEMP float;<br>UPDATE BCN_PREDICTIONS p SET    p.REAL_TEMP = (SELECT b.TM_MES FROM   BCN_DATA b WHERE  p.case_id = b.fecha) WHERE  EXISTS (SELECT 1 FROM  BCN_DATA WHERE  fecha = p.case_id);</pre><p>Firstly we can see the trend, real data and estimated data</p><pre>%sql<br><br>SELECT TO_CHAR(CASE_ID,&#39;YYYY-MON&#39;) DATE_ID, <br>    VALUE REAL_TEMP, <br>    round(PREDICTION,2) EST_TEMP, <br>    round(LOWER,2) EST_TEMP_LOWER, <br>    round(UPPER,2) EST_TEMP_UPPER,<br>    round(TREND_TEMP,4) TREND_TEMP<br>from BCN_PREDICTIONS where TO_CHAR(CASE_ID,&#39;YYYY-MON&#39;) &gt; &#39;2020-JAN&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LU4myLHPrWyxZQ382tCcA.png" /></figure><p>And now we can see a detailed graph with prediction for year 2022 compared to real year 2022 averaged temperature</p><pre>%sql<br><br>SELECT TO_CHAR(CASE_ID,&#39;YYYY-MON&#39;) DATE_ID, <br>    round(PREDICTION,2) EST_TEMP,<br>    round(UPPER,2) EST_TEMP_UPPER, <br>    round(LOWER,2) EST_TEMP_LOWER,<br>    REAL_TEMP <br>from BCN_PREDICTIONS where TO_CHAR(CASE_ID,&#39;YYYY-MON&#39;) &gt; &#39;2022-JAN&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpsAN-UWx-7ptSJ0Be7pBg.png" /></figure><p>Curiously, the upper estimate is the one that is closest to the real value of the averaged temperature. In fact, <a href="https://www.lavanguardia.com/mediterranean/20240531/9693369/signs-climate-change-spain-temperature-warm-record-meteorological-aemet.html">2022 was the hottest year recorded in Spain since 1961</a>!!.</p><p>mjb</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b1081d89bc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting with Oracle Cloud Infrastructure (1/2)]]></title>
            <link>https://medium.com/@mariano.jimenez/forecasting-with-oracle-cloud-infrastructure-1-2-f65956bee909?source=rss-89c261953619------2</link>
            <guid isPermaLink="false">https://medium.com/p/f65956bee909</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[oci]]></category>
            <dc:creator><![CDATA[Mariano Jimenez]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 12:41:33 GMT</pubDate>
            <atom:updated>2024-09-04T15:41:42.284Z</atom:updated>
            <content:encoded><![CDATA[<p>A few weeks ago a client asked me for information about the alternatives that we offer as a service to carry out a forecasting study. I will briefly explain two alternatives for forecasting from OCI. One based on the forecasting operator and one based on OML. This first post is for forecasting operator alternative and OML case will be posted in some days.</p><p>CASE 1 FORECASTING USING FORECASTING OPERATOR FROM OCI DATASCIENCE</p><p>A time series is a collection of data referenced to time values. The time series will be univariate if it is composed of the time variable and only an additional variable or multivariate if it is composed of several variables among the time variable.</p><p>Forecasting is the capability of predicting values from a historical time series.</p><p>OCI Operators is a suite of pre-built solutions designed to meet a wide range of needs in the field of data Science (<a href="https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/index.html"><em>https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/index.html</em></a>). They offer a user-friendly and low-code API that makes it accessible to users without much knowledge, solving complex datascience tasks. In particular, the forecasting operator makes it possible to estimate values from time series of historical data without needing to be an expert in time series analysis, univariate or multivariate.</p><p>ADS is a python library maintained by the Oracle Cloud Infrastructure Data Science service team. It speeds up common data science activities by providing tools that automate and/or simplify common data science tasks, along with providing a data scientist friendly pythonic interface to Oracle Cloud Infrastructure (OCI). The Forecasting Operator is a component of ADS, so you need to install ADS prior to use it and this can be done through PyPi or through the Oracle-provided Conda Packs. In <a href="https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/forecasting_operator/install.html"><em>https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/forecasting_operator/install.html</em></a> is all the information about it.</p><p>Anyway, the easiest way to use the forecasting operator is using OCI Data Science Service because all libraries or utilities you will need are already installed.</p><p>Here <a href="https://medium.com/a-guide-to-oracle-cloud-ai/launch-a-data-science-service-on-oracle-cloud-ecd8772e31fe"><em>https://medium.com/a-guide-to-oracle-cloud-ai/launch-a-data-science-service-on-oracle-cloud-ecd8772e31fe</em></a> and here: <a href="https://www.rittmanmead.com/blog/2023/03/introduction-to-oracle-data-science-service-part-1/"><em>https://www.rittmanmead.com/blog/2023/03/introduction-to-oracle-data-science-service-part-1/</em></a> you can find how to deploy Oracle Data Science Service:</p><p>Once we have created and opened a notebook and from the Launcher Tab, we open the Environment Explorer tool and install the Conda environment designed to forecast: AI Forecasting Operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNXOLoUWOl6FgQ6iiEYIPA.png" /></figure><p>We copied the command to download the latest software version and create the corresponding conda environment and we paste in a terminal tab:</p><pre>odsc conda install -s forecast_p38_cpu_v2</pre><p>Run the code and once the installation is finished, we activate the environment:</p><pre>conda activate /home/datascience/conda/forecast_p38_cpu_v2</pre><p>We initialize forecasting using the ads cli command:</p><pre>ads operator init -t forecast --output my-forecast</pre><p>The operator has created a directory called “my-forecast” where all the objects needed will be created. You can logically put another name.</p><p>We move to the created directory and see what objects have been created:</p><pre>cd my-forecast<br>ls -la<br><br>drwxr-xr-x.  8 datascience users   4096 Aug 22 10:34 .<br>drwxr-xr-x. 13 datascience users   4096 Aug 21 11:48 ..<br>-rw-r--r--.  1 datascience users    330 Aug 21 11:24 environment.yaml<br>-rw-r--r--.  1 datascience users    981 Aug 21 11:24 forecast_job_container_backend.yaml<br>-rw-r--r--.  1 datascience users   1116 Aug 21 11:24 forecast_job_python_backend.yaml<br>-rw-r--r--.  1 datascience users    173 Aug 21 11:24 forecast_operator_local_container_backend.yaml<br>-rw-r--r--.  1 datascience users     57 Aug 21 11:24 forecast_operator_local_python_backend.yaml<br>-rw-r--r--.  1 datascience users    182 Aug 22 06:32 forecast.yaml<br>-rw-r--r--.  1 datascience users   9794 Aug 21 11:24 README.md<br>-rw-r--r--.  1 datascience users   9407 Aug 21 11:24 schema.yaml</pre><p>Specifically it is in forecast.yaml where they are the variables for the execution of the forecast, and they must be adapted to the specific use case.</p><pre>kind: operator<br>spec:<br>  datetime_column:<br>    name: &lt;column name with the time series data&gt;<br>  historical_data:<br>    url: &lt;local path or url where data file is&gt;<br>  horizon: &lt;number of forecast data to get&gt;<br>  model: auto<br>  target_column: &lt;column name with the variable to be forecasted&gt;<br>type: forecast<br>version: v1</pre><p>Here you can find the description of each yaml field: <a href="https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/forecasting_operator/yaml_schema.html"><em>https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/forecasting_operator/yaml_schema.html</em></a></p><p>We modify the yaml file with the editor of our choice. For the test we will use the dataset <a href="https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"><em>https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv</em></a> with the information of passengers of airlines between 1949 and 1960 that we have downloaded previously. Passenger data comes in thousands.</p><pre>kind: operator  <br>spec:<br>  datetime_column:<br>    name: Month<br>  historical_data:<br>    url: Passengers.csv ##or https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv<br>  horizon: 20<br>  model: auto<br>  target_column: Passengers<br>type: forecast<br>version: v1</pre><p>And we launch the operator:</p><pre>ads operator run -f forecast.yaml</pre><p>The results appear in a directory called results where we can find the following files:</p><ul><li>forecast.csv (with the contents of the input, the value calculated by the model for the series (fitted) and the required forecast values)</li><li>metrics.csv (with the values of the process quality)</li><li>report.html where you can see, among others, the graphical representation of the forecast:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2j4BLGmg4R9G-9l5Y6R6A.png" /></figure><p>The report informs us aswell about the used model (SARIMAXForecaster) and hyperparameters values.</p><p>The report also shows the metrics of the model. This case results with a r2 = 0.9903 that means that 99.03 of the series values are explained with the model and MAPE (Mean absolute percentage error)= 0.037 with is simply very low.</p><p>As you can see, It is very easy to use Forecast Operator and the results are really impressive.</p><p>You can find more information here:</p><p>Where to find conda environment:<br><em> </em><a href="https://docs.oracle.com/en-us/iaas/data-science/using/conda-operators.htm"><em>https://docs.oracle.com/en-us/iaas/data-science/using/conda-operators.htm</em></a><br>Operador Forecasting Documentation:<br><em> </em><a href="https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/forecasting_operator/index.html%3Chttps:/urldefense.com/v3/__https:/accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/forecasting_operator/index.html__;!!ACWV5N9M2RV99hQ!KI3_gyLaiq2FJvprryr35gbZuEzf7QXBRzXl4QvQg3dBCJR2TGNo1xhVnUkncubMwoluiq4LiDq4Oc4x9X0EXGXElA$%3E"><em>https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/forecasting_operator/index.html&lt;https://urldefense.com/v3/__https://accelerated-data-science.readthedocs.io/en/latest/user_guide/operators/forecasting_operator/index.html__;!!ACWV5N9M2RV99hQ!KI3_gyLaiq2FJvprryr35gbZuEzf7QXBRzXl4QvQg3dBCJR2TGNo1xhVnUkncubMwoluiq4LiDq4Oc4x9X0EXGXElA$&gt;</em></a><br>and :<br><em> </em><a href="https://blogs.oracle.com/ai-and-datascience/post/bike-sharing-demand-forecasting-oci-ads"><em>https://blogs.oracle.com/ai-and-datascience/post/bike-sharing-demand-forecasting-oci-ads</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f65956bee909" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>